Reputation: 825
Each image has a div parent, these parents' width and height are in proportion, the question is, i can't center each image inside its parent horizontally. it seems it only takes the first element's height and applies it to the rest of the elements. ![it seems it only takes the first elements height and apply it to all of the rest ][1]
function centerImages(image) {
var parent_height = $('.thumb img').parent().height();
var image_height = $('.thumb img').height();
var top_margin = (parent_height - image_height) / 2;
$('.thumb img').css( 'margin-top' , top_margin);
}
$(".thumb img").each(function() {
centerImages(this);
});
demo: http://codepen.io/waveiron/pen/ExpLd
Upvotes: 2
Views: 86
Reputation: 185
One way is to use an inline-block helper with height: 100% and vertical-align: middle on both elements.
Or, if you don't want to have an extra element in modern browsers and don't mind using IE expressions, you can use a pseudo-element and add it to IE using a convenient Expression, that runs only once per element, so there won't be any perfomance issues
If I understod your question right....
Upvotes: 0
Reputation: 2070
You are pointing to the same image all over again. Simply change to:
function centerImages(image) {
var parent_height = $(image).parent().height();
var image_height = $(image).height();
var top_margin = (parent_height - image_height) / 2;
$(image).css( 'margin-top' , top_margin);
}
$(".thumb img").each(function() {
centerImages(this);
});
Plus add 'px' as also suggested.
Upvotes: 2
Reputation: 22617
You're missing to add px
:
$('.thumb img').css( 'margin-top' , top_margin + "px");
(I'd also suggest to cache jQuery objects when possible:
var $image = $(image);
var parent_height = $image.parent().height();
var image_height = $image.height();
)
Upvotes: 0