Reputation: 237
<div class='img-box'>
<img /> //position absolute
<img /> //position absolute
<img /> //position absolute
<img /> //position absolute
in this code i want to put image in center of div but it not come in center align due to absolute position of image, so, please help me to put this image in center of div. Please help me
Upvotes: 0
Views: 2444
Reputation: 349012
First, Set the div to position:relative
.
Second, add this code:
$(document).ready(function(){
var div_height = $(".img-box").height();
var div_width = $(".img-box").width();
$("img").each(function(){
$(this).css({
"top": (div_height-$(this).height())/2+"px",
"left": (div_width-$(this).width())/2+"px"
});
});
});
To center an element relative to the parent, the width of the child element has to be subtracted from the width of the parent. After dividing this result by 2, you know the desired offset of the child (relative to the parent).
Upvotes: 1
Reputation: 960
in css:
image{
position: relative;
left: 50%;
}
If the images don't line up on top of each other, I would just put them inside a smaller div with the width set to the same as the width of the image, so the second image is forced to display underneath rather than next to. And then set that second div to display in the center of the parent one using the 'left:50%'
Might not be best way to do it, but it's probably how I'd do it.
Upvotes: 0
Reputation: 5796
You can do it in css:
.img-box img {
position:relative;
margin: auto;
display:block;
}
If you've already got position:absolute applying to your img nodes it might mean you have other strange CSS that mucks this up.
Although if your intention is to have the images appear on top of each other this isn't the solution, but your question isn't clear on that.
Upvotes: 0
Reputation: 3043
if you know img width and height, you could set top and left 50%
margin: -imgHeight/2 0 0 -imgWidth/2
Upvotes: 0