开发者

put image in center of div where image is in absolute position

<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,开发者_C百科 so, please help me to put this image in center of div. Please help me


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).


if you know img width and height, you could set top and left 50% margin: -imgHeight/2 0 0 -imgWidth/2


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜