Introduction
The Review CSS series is the note for some common CSS usages.
The CSS position includes static, relative, absolute, fixed, and sticky.
1. static
- static is the default position style. The static components will be placed from left and top corner of the viewport.
code
<div class="mother-box">Mother
<div class="box" id="one">One</div>
<div class="box" id="two">Two</div>
<div class="box" id="three">Three</div>
<div class="box" id="four">Four</div>
</div>
.mother-box{
width:500px;
height: 200px;
background:green;
color:white;
overflow:scroll;
position: absolute;
}
.box{
background:red;
color:white;
height: 20%;
}
#two{
z-index: 1;
top: 100px;
left:20px;
background:blue;
}
2. relative
The relative components have the following properties:
- The component will be moved relative to the original position(static) according to top, left, right
- Moved component will not affect other components.
- The original position(static) will still be available.
code
Modify the box two
#two{
position: relative;
top: 20px;
left:20px;
background:blue;
}
3. fixed
Scroll the window from the following CodePen example. The fixed components have the following properties:
- The fixed component is fixed to the viewport even we scroll the window.
- The width of the fixed component changes (no longer as long as the mother box)
- The original position(static) will be unavailable.
code
#two{
position: fixed;
z-index: 1;
top: 100px;
left:20px;
background:blue;
}
4. absolute
The absolute components depends on the position style of the parent component. There are two conditions.
Condition 1: if the position style of the parent component is default (static)
It will perform as fixed
#two{
position: absolute;
top: 20px;
left:20px;
background:blue;
}
Condition 2: if the position style of the parent component is one of the following position style.
- relative | absolute | fixed | inherit
- The absolute component will move with the parent component when scrolling the window
.mother-box{
width:500px;
height: 200px;
background:green;
color:white;
overflow:scroll;
position: relative;
}
#two{
position: fixed;
z-index: 1;
top: 100px;
left:20px;
background:blue;
}
5. sticky
The sticky component has the following properties:
- The sticky component performs as a relative component before it arrives the position we set top, left, right
- The following example is copied from MDN (https://developer.mozilla.org/zh-CN/docs/Web/CSS/position)
That's it!
Articles
There are some of my articles. Feel free to check if you like!
- My blog-posts for software developing: https://medium.com/a-layman
- My web resume: https://jenhsuan.github.io/ALayman/cover.html
- Facebook page: https://www.facebook.com/imalayman
- My latest side project - Daily Learning: https://daily-learning.herokuapp.com/
Top comments (2)
Thanks very much for the information
No problems! Thanks for feedbacks