position属性作为css布局的基础,其重要性不言而喻。
position属性有以下四种:
- static
- relative
- absolute
- fixed
1.static positioning
每一个元素都有一个默认的position值static。
一个元素在浏览器中显示的位置由这个元素在html文档中的位置决定,每一份文档按照这种布局方式就叫做一个normal flow。
block box在文档流中是从上面流到下面,inline box和inline block在文档流中是由左上角流向右下角。
2.relative positioning
相对定位时,元素还在normal flow中,其影响有两点:
- 元素原先占据的位置不变
- 元素移动后可能与其他元素发生重叠
.box2 {
position: relative;
left: 20px;
top: 20px;
}
如下图:
3.absolute positioning
绝对定位时,元素脱离了normal flow,其影响在于:
- 原先占据的位置被后面的元素填充
- 元素移动后可能会与其他元素发生重叠
- 其定位的坐标系是离它最近的一个position属性不是static的父元素
.box2 {
position: absolute;
left: 20px;
top: 20px;
}
绝对定位最值得注意的就是第三点,其定位的父元素究竟是哪一个。如果其父元素的position属性都是static,那么绝对定位的参考系是元素html,其position属性默认为relative。
绝对定位在现如今强调响应式布局的时代背景下不是很有用(摘自 CSS Mastery)。
The fact that absolutely positioned boxes don’t participate in the flow of the document makes it quite the hassle to create layouts that adapt and respond to the viewport at various widths and varying lengths of content.
4.fixed positioning
固定定位是决对定位的一个子类型。区别在于固定定位的containing block是整个视口。举两个使用的场景:
- 侧边栏固定
- 导航栏固定