I'm Unable To Center An Image Inside A Div After Being Loaded With Jquery
I'm loading images dynamically with jquery and can't seem to center them inside the div. My HTML looks like this:
<
Solution 1:
Add "text-align:center;" to your containing div. Also no need for the auto margins.
Solution 2:
If you want to do it in js, give this function a try after you load your img.
setToCenterOfParent($("#current_photo"), $("#current_photo").parent());
functionsetToCenterOfParent( obj, parentObj ) {
var height = $( obj ).height();
var width = $( obj ).width();
if ( parentObj == window ) {
$( obj ).css( 'top', ( $( parentObj ).height() / 2 ) - ( height / 2 ) );
$( obj ).css( 'left', ( $( parentObj ).width() / 2 ) - ( width / 2 ) );
}
else {
$( obj ).css( 'top', ( $( parentObj ).height() / 2 ) - ( height / 2 ) + $( parentObj ).position().top );
$( obj ).css( 'left', ( $( parentObj ).width() / 2 ) - ( width / 2 ) + $( parentObj ).position().left );
}
}
Solution 3:
You can get it to work by adding this style to your img
:
display: block;
Demo: http://jsfiddle.net/Zsq8Q/3/
The fact that you are setting the src
dynamically is not the problem here, it is that an img
element is not a block element by default so the margin setting doesn't work unless you make it a block.
Solution 4:
text-align property in the container will solve the problem :
<divstyle="text-align:center; width:100%;border: solid 1px #ff0000;"><imgid="current_photo"src=""style="margin-right: auto; margin-left: auto; max-width:97%;"/></div>
Demo:
Post a Comment for "I'm Unable To Center An Image Inside A Div After Being Loaded With Jquery"