Positioning issues in CSS
CSS position is divided into static (default positioning), relative (relative positioning), absolute (absolute positioning), z-index (overlay principle)
Let’s introduce them one by one:
- static: no positioning, the document appears in the normal flow, that is, in the order of top and bottom in html, left, right, bottom, top, z-index, invalid.
- fix: Position relative to the browser.
- Relative: Positioning relative to the direct parent element (it can also be considered as positioning relative to its original position).
- absolute: Absolute positioning, positioned relative to the parent non-static element.
- z-index: The larger the value, the higher the front.
code demo
Original position
After adding fix positioning
code:
#no1{
width: 500px;
height: 500px;
background-color: aqua;
position: fixed;
left: 200px;
top:200px
}
After adding a small box no2 and adding relative to the small box, the small box is positioned relative to the big box no1
Code:
#no2{
width: 300px;
height: 300px;
background-color: yellowgreen;
position:relative;
left: 50px;
top: 50px;
}
Add a no3 box and use absolut to position it relative to the parent's non-static element, that is, the no2
code:
#no3{
width: 100px;
height: 100px;
background-color: tomato;
position: absolute;
left: 100px;
top: 50px;
}
Add a z-index attribute for no3 so that it is behind.
Code:
#no3{ width: 100px; height: 100px; background-color: tomato; position: absolute; left: 100px; top: 50px ; z- index : -2 ; The original position, and absolute no longer retains the original position, and the following elements will fill in the position before the change. Demo:
#no2{
width: 300px;
height: 300px;
background-color: yellowgreen;
}
#content{
width: 200px;
height: 200px;
background-color: pink;
}
After adding relative positioning for no2, it can be seen that the content (pink square) does not move up and is filled.
#no2{
width: 300px;
height: 300px;
background-color: yellowgreen;
position: relative;
left:50px;
top:50px;
}
After adding absolute, it can be seen that the content (pink square) moves up and fills the
original position of no2.
#no2{
width: 300px;
height: 300px;
background-color: yellowgreen;
position: absolute;
left:50px;
top:50px;
}