I'm trying to center an image in a div according to the width of the image after I scale it to have a height of 250px.
For example, if I had an image with dimensions 625x450 and, in my CSS file, set the height of the image to be 250px, then the width would automatically scale to 347.22px. I want to be able to detect that scaled width and then set a margin-left of (width - height)/2 to center the image.
The CSS for this example in hard-coded form would look like this (the entire fiddle is here):
.gallery {
width: 250px;
overflow: hidden;
position: relative;
}
.gallery img {
height: 250px;
width: auto;
margin-left: -48px;
}
But I want to be able to do this on the fly with images of other dimensions. I have attempted to do this by cutting out the margin-left line of the hard-coded CSS and adding some jQuery (the entire fiddle is here):
$(document).ready(function(){
oldWidth = $('.gallery img').width();
newMarg = (oldWidth - 250)/2);
$('.gallery img').css("margin-left", newMarg);
}
I have not had any success with that approach, though. It has to be something with the jQuery that I'm messing up. I'm very new to everything I'm attempting to do here, and I feel like I might be missing something simple.