DIV absolute positioning - maintain position after

2020-07-18 09:21发布

问题:

I am displaying divs with position absolute.

.my_label{
        list-style:none;
        list-style-type:none;

        position:absolute;
        top:2px;
        left:10px;
        width:20px;
        height:20px;

        background-color:#FF1021;
}

once I re-size the browser window, all these divs stay at same position. and they're not absolute to the parent elements anymore. I want them to stay in relation with the surrounding objects. should I use position "relative" or is there another way? (also jQuery is welcome)

thanks a lot

回答1:

To make an element position absolutely to it's parent, the parent must be set to position:relative.

For example:

<div id="parent" style="margin:0 auto; width:500px; position:relative;">
    <div id="child" style="position:absolute; top:10px; left:10px;"></div>
</div>

This doesn't have to be the direct parent, when you set absolute positioning the element will position from the nearest ancestor with a set positioning.



回答2:

parent must have position:relative; (or some other positioning apart from static) so that it's child can be positioned absolutely relative to them.



回答3:

You need to give your parent div position:relative and your child div position absolute

Check working example at http://jsfiddle.net/remYW/