I'm trying to create a website similar to the prototype given in Figma (linked above). This is the code I used:
<div id="Tips">
<div id="TipsHeading"> Tips
</div>
<div >
<img id="img1" src="personal.png">
<div id="WearMask"> Wear Mask </div>
</div>
CSS:
.Tips{background: #FFFFFF;
top: 1024px;}
#TipsHeading{position: absolute;
height: 66px;
top: 1053px;}
.rec2{position: absolute;
height: 369px;
top: 1192px;}
#WearMask{position: absolute;
top: 160px;}
#img1{position: absolute;
left: 24.85%;
right: 26.5%;
top: 49.36%;
bottom: 10.7%;
height: 278px;
width: 338px;}
I'm using the id property for both "TipsHeading" and "WearMask". However TipsHeading is position wrt the top of the page, and WearMask is positioned wrt to .rec2. It doesn't make sense to me.
This has happened multiple times and it's becoming very difficult for me to debug my code, please help.
CodePudding user response:
Here is what Mozilla developers says about position absolute:
The element is removed from the normal document flow, and no space is created >for the element in the page layout. It is positioned relative to its closest >positioned ancestor, if any; otherwise, it is placed relative to the initial >containing block.
position: absolute also reinitialises the position of its children like position: relative does.
In your case, TipsHeadingis positioned based on its closest positioned ancestor .Tips, whereas #WearMask is positioned based on the position of its ancestor .rec2
That being said, giving all your elements an absolute positioning will create a lot of mess in your css. Try to work with relative elements while using flex,margin and padding instead.
CodePudding user response:
The element in position: absolute is positioned relative to its first positioned ancestor element.
