Skip to content Skip to sidebar Skip to footer

Is It Possible To Center An Image On Both Axis Inside A Div?

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 e

Solution 1:

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 jsbin example

Solution 2:

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?

CSS

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:

<divid="display"><divid="slideshow1"><tablecellspacing=0><tr><tdstyle="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.

JS

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.

Post a Comment for "Is It Possible To Center An Image On Both Axis Inside A Div?"