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
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.
An element with position: absolute; is positioned relative to the nearest positioned ancestor (instead of positioned relative to the viewport, like fixed). However; if an absolute positioned element has no positioned ancestors, it uses the document body, and moves along with page scrolling.
Position fixed doesn't work with transform CSS property. It happens because transform creates a new coordinate system and your position: fixed element becomes fixed to that transformed element. To fix the problem you can remove transform CSS property from the parent element.
Fixed. The fixed value is similar to absolute as it can help you position an element anywhere relative to the document, however this value is unaffected by scrolling.
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With