12752

Is it possible to center an image on both axis inside a div?

Question:

I have a script that loads in a div with images running jQuery Cycle Lite Plugin.

I got the tip that I could us the "after" function in that plugin to make changes to the picture each time the image is refreshed. So I wrote this:

$("#display div").css({ margin: "0 auto", "text-align": "center", });

The html built like this:

<div id="display"> <div id="slideshow1"> <img ... /> </div> </div>

This isn't working, whats wrong?<br /> ( this is supposed to center it horizontally, i need to center it vertically to )..

<strong>edit:</strong><br /> I kind of got it working but it still needs help, anyone that knows why its acting weird? <a href="http://hem.bredband.net/noor/bildspelet.html" rel="nofollow">http://hem.bredband.net/noor/bildspelet.html</a>

thanks @pekka for the link

Answer1:

First of all, trailing commas in JavaScript objects is bad stuff, remove the last comma.

Second of all you could probably calculate it like so:

var $div = $('#display'); $div.css('position', 'relative'); var $kids = $div.children(); // I'm assuming you want to center all the slideshows? $kids.each(function() { var $this = $(this); $this.css({ left: ($div.innerWidth(true) - $this.width()) / 2, top: ($div.innerHeight(true) - $this.height()) / 2, position: 'absolute' }); });

From looking at your sample: your <div id="display"> needs to have a height set (even 100%) in the css, or it will always shrink to contain (which when all children are made absolute positioning, the height will fold to zero). Please take a look at the <a href="http://jsbin.com/asesa" rel="nofollow">jsbin example</a>

Answer2:

For stuff like this, the CSS solution is always preferable to the JS one, because a) it works with JavaScript turned off and b) it works immediately with no delay and with no timing issues related to making sure the layout has flowed into its final resting place. But is there a CSS solution in this case?

<strong>CSS</strong>

There is no way, with the markup you've given, to center an image vertically in a cross-browser way (included IEs 6-8) with just CSS. However, a small change to your markup to include a wrapping single-celled table, and then you can center vertically with vertical-align:middle. Your markup would look like this:

<div id="display"> <div id="slideshow1"> <table cellspacing=0><tr><td style="height:200px;padding:0;vertical-align:middle"> <img ... /> </td></tr></table> </div> </div>

Extra HTML cruft but it keeps it centered with no script running even as the image dimensions change.

<strong>JS</strong>

If you want to use JavaScript instead it looks like gnarf has the right idea (except why did he name all his variables starting with the dollar sign?) I'd take that and move the body into a named function so you can call it whenever you want (say recenter). For the initial render you want it to happen as soon as possible, so I'd inline the call to recenter() immediately after your slideshow DIVs in the markup.

Recommend

  • Java AWT-EventQueue-0 Error
  • Oracle instant client status
  • Get a heapdump on JVM from Tomcat 6
  • make m4 see macro when macro ends with same character as string following macro
  • Can I use preg_replace to strip the trailing \\n in multiline mode?
  • auto layout leading or trainling -16
  • How do I store this JSON object as a cookie and than read it in vanilla javascript?
  • split string (e.g. with bash) but skip part of it
  • Custom URI routing by query string with CodeIgniter?
  • awk or sed CSV file manipulation
  • Regex: Replace every Comma with Tab Not within quotes
  • How to re-render views using Angular JS
  • Any command in mysql equivalent to Oracle's autotrace for performance turning
  • Grouping by blank nodes
  • TypeError: 'builtin_function_or_method' object has no attribute '__getitem__'
  • Interpolation method that does not add unnecessary extremums
  • When interface inheritance in Java is useful?
  • android-support-v7-appcompat has same attrs as actionbarsherlock library
  • Timeout a query
  • OpenMP and File I/O
  • PyQt4 application on Windows is crashing on exit
  • Ruby 1.8.6 Array#uniq not removing duplicate hashes
  • using html data-attributes as css-variable (i.e. text-shadow)
  • How can I get the choice “H2” back in the H2 consol?
  • NHibernate manually control fetching
  • Webgrid not refreshing after delete MVC
  • Jquery UI tool tip close icon
  • Yii2: Config params vs. const/define
  • Ajax Loaded meta Tags
  • HTML download movie download link
  • Get object from AWS S3 as a stream
  • Updating server-side rendering client-side
  • Cross-Platform Protobuf Serialization
  • Validaiting emails with Net.Mail MailAddress
  • Do I've to free mysql result after storing it?
  • Traverse Array and Display in markup
  • KeystoneJS: Relationships in Admin UI not updating
  • How to set the response of a form post action to a iframe source?
  • Setting background image for body element in xhtml (for different monitors and resolutions)
  • Qt: Run a script BEFORE make