Absolute position is not working

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>

Leave a Comment