Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
122 views
in Technique[技术] by (71.8m points)

html - Absolute position is not working

I'm trying to place a div with id 'absPos' in absolute position in relation to its parent div. But it is not working, the div is placed at the top left corner of the page.

My code sample is as follows

<html>
    <body>
        <div style="padding-left: 50px;">
            <div style="height: 100px">
                Some contents
            <div>

            <div style="height: 80px; padding-left: 20px;">
                <div id="absPos" style="padding: 10px; position: absolute; left: 0px; top: 0px; background-color: red;"></div>
                Some text
            </div>
        </div>
    </body>
</html>

Can you help me to solve this issue. In my actual case instead of the red background color I've to place a background image.

Regards

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Elements with absolute positioning are positioned from their offsetParent, the nearest ancestor that is also positioned. In your code, none of the ancestors are "positioned" elements, so the div is offset from body element, which is the offsetParent.

The solution is to apply position:relative to the parent div, which forces it to become a positioned element and the child's offsetParent.

<html>
    <body>
        <div style="padding-left: 50px;">
            <div style="height: 100px">
                Some contents
            <div>

            <div style="height: 80px; padding-left: 20px; position: relative;">
                <div id="absPos" style="padding: 10px; position: absolute; left: 0px; top: 0px; background-color: red;"></div>
                Some text
            </div>
        </div>
    </body>
</html>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...