I am using JQuery Cycle to produce a slideshow of images. The plugin uses display:none to hide the images that aren’t being shown yet, with the first image automatically having display:block on page load. I have this bit of JQuery code to vertically center my images inside the slideshow container, which works….for the very first image.
(....inside a (document.ready(function()......)
$('.variable').load(function() {
var imgHt= $('.variable').height();
var half= imgHt/2;
$('.variable').css("top", "50%");
$('.variable').css("margin-top", "-" + half + "px");
});
I tried this code without the .load(function() as well, and it’s not working correctly. The browser will display top:50% and margin-top:0px or it will display height:correct half height of image, and not display top:50%. Weird.
I’m assuming here that JQuery does not see image dimensions when its display is set to none. Is there a workaround to this?
P.S. These images are generated from a database, so no, I do not know the image’s height beforehand. Which is why I’m using JQuery in the first place.
The browser won’t calculate the size of any element with
display: none. The usual workaround is to show the element and use margins or absolute positioning to move the element (or more likely its container) somewhere thousands of pixels off the left side of the screen. Then the boxes will be calculated, you can do your manual positioning, then hide and remove the margin.However, since you’re using a plugin, this may not work very well. In this case, I think you’re better off modifying the plugin to display the images as you want them. It might be possible with just CSS, but that depends on the box elements used by the plugin and the styles it applies (via CSS or JS) on the boxes and the image itself.