Absolute position is not working
Solution 1:
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>
Solution 2:
If you are placing an element with absolute position, you need the base element to have a position value other than the default value.
In your case if you change the position value of the parent div to 'relative' you can fix the issue.