If I have a fixed sized container div, and an unknown sized image, how do I horizontally and vertically center it?
If setting the image as a background image and centering it that way isn't an option, the jQuery to adapt the answer you linked for static images would go:
$(".fixed-div img.variable").each(function(){
//get height and width (unitless) and divide by 2
var hWide = ($(this).width())/2; //half the image's width
var hTall = ($(this).height())/2; //half the image's height, etc.
// attach negative and pixel for CSS rule
hWide = '-' + hWide + 'px';
hTall = '-' + hTall + 'px';
$(this).addClass("js-fix").css({
"margin-left" : hWide,
"margin-top" : hTall
});
});
assuming a CSS class defined as
.variable.js-fix {
position:absolute;
top:50%;
left:50%;
}
with the fixed-width div having a height and position:relative
declared.
[important js edit: switched '.style()' to '.css()']