Absolute item position inside the list

I am trying to position a list item based on a viewport, but they end up sticking to their parents.

To reproduce the problem, I just need to create a list with an absolutely placed element:

body { background-color: lightgray; } ul { position: absolute; top: 50px; left: 50px; list-style: none; } .element { position: absolute; top: 0; left: 0; background-color: red; } 
 <ul> <li> <div class="element"> <p> Element </p> </div> </li> </ul> 

As you can see, the element is not located in the upper left corner of the viewport, but instead relative to ul .

Am I missing something? Could this be the static position of the li elements?

+5
source share
3 answers

Try using position: fixed instead. position: absolute positions the element absolutely relative to the nearest parent with position: relative , and position: fixed will position the element relative to the viewport.

Code snippet:

 body { background-color: lightgray; } ul { position: absolute; top: 50px; left: 50px; list-style: none; } .element { position: fixed; top: 0; left: 0; background-color: red; } 
 <ul> <li> <div class="element"> <p> Element </p> </div> </li> </ul> 
+2
source

If you want to make the position of an element relative to the viewport, the parent ( ul ) should not have position:absolute , So:

Method 1) remove position: absolute from ul :

 body { background-color: lightgray; } ul { top: 50px; left: 50px; list-style: none; } .element { position: absolute; top: 0; left: 0; background-color: red; } 
 <ul> <li> <div class="element"> <p> Element </p> </div> </li> </ul> 

Method 2) change the html code:

 body { background-color: lightgray; } ul { position: absolute; top: 50px; left: 50px; list-style: none; } .element { position: absolute; top: 0; left: 0; background-color: red; } 
 <ul> <li> <!--Other Content --> </li> </ul> <div class="element"> <p> Element </p> </div> 
+1
source

Try it. Remove position:absolute in the ul class and give position:relative . both body and ul have default fields set on them. so delete it.

 body { background-color: lightgray; margin:0; } ul { position: relative; list-style: none; margin:0; } .element { position: absolute; top: 0; left: 0; background-color: red; } 
 <ul> <li> <div class="element"> <p> Element </p> </div> </li> </ul> 
0
source

Source: https://habr.com/ru/post/1272447/


All Articles