标准流布局
默认情况下,元素都是按照normal flow(标准流、常规流、正常流、文档流【document flow】)进行排布
脱标:定位、浮动的元素都会脱离标准流布局
相对定位
relative
相对于自身之前的位置进行定位。
固定定位
fixed
相对于浏览器视口进行定位
绝对定位
absolute
相对于position设置为非static的父元素进行定位,若父元素均没有进行position设置,则相对于浏览器视口进行定位(类似于fixed)
position为absolute和fixed的特点
- 可以随意设置宽高
- 如果没有设置宽高,默认由内容决定
- 不再受标准流的约束
- 不再严格按照从左至右、从上至下排布
- 不再严格区分块级、行内级;块级、行内级的很多特性都会消失
- 不再给父元素汇报宽高,即:脱标后,不再占据父元素盒子的高度;
- 脱标元素内部还是按照标准流布局。
- 公式:定位参照对象的宽度 = left + right + margin-left + margin-right + 绝对定位元素的实际占用宽度
公式:定位参照对象的高度 = top + bottom + margin-top + margin-bottom + 绝对定位元素的实际占用高度
注:width,height在不设置的情况下,其默认值均为auto,即由浏览器决定其宽度和高度(参看mdn文档)
(重要)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| <style> .a { width: 500px; height: 200px; background-color: red; position: relative; }
.b { position: absolute; left: 0; right: 0; background-color: blue; height: 100px; } </style> <div class="a"> <div class="b"></div> </div>
|
说明:
a盒子的宽度=b盒子的宽度 + left + right + margin-left + margin-right
500 auto 0 0 0 0
盒子的宽度未设置值,默认为auto,则此处auto = 500
参看:https://developer.mozilla.org/zh-CN/docs/Web/CSS/width
利用该公式,我们可以让定位盒子居中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| <style> .a { width: 500px; height: 200px; background-color: red; position: relative; }
.b { position: absolute; left: 0; right: 0; margin: 0 auto; width: 100px; background-color: blue; height: 100px; } </style> <div class="a"> <div class="b"></div> </div>
|
a盒子的宽度=b盒子的宽度 + left + right + margin-left + margin-right
500 100 0 0 auto auto
margin-left/right的值为auto,浏览器会自动平均分配剩余的宽度值
类似的情况,我们可以让定位盒子的高度等于父定位盒子的高度
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| <style> .a { width: 500px; height: 200px; background-color: red; position: relative; }
.b { position: absolute; top: 0; bottom: 0; background-color: blue; width: 100px; } </style> <div class="a"> <div class="b"></div> </div>
|
可以让定位盒子在竖直方向居中
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| <style> .a { width: 500px; height: 200px; background-color: red; position: relative; }
.b { position: absolute; top: 0; bottom: 0; margin: auto 0; width: 100px; background-color: blue; height: 100px; } </style> <div class="a"> <div class="b"></div> </div>
|
也可以让定位盒子在父定位盒子中水平垂直居中
让盒子垂直居中的第一种方案
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| <style> .a { width: 500px; height: 200px; background-color: red; position: relative; }
.b { position: absolute; top: 0; bottom: 0; left: 0; right: 0; margin: auto; width: 100px; height: 100px; background-color: blue; } </style> <div class="a"> <div class="b"></div> </div>
|
如果想让子定位元素和父盒子一致,参看以下代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| <style> .a { width: 500px; height: 200px; background-color: red; position: relative; }
.b { position: absolute; top: 0; bottom: 0; left: 0; right: 0; margin: 0; background-color: blue; } </style> <div class="a"> <div class="b"></div> </div>
|
width取值为auto的不同场景
- 行内非替换元素:宽度为包裹内容的宽度
- 块级元素:宽度为包含块的宽度
- 绝对定位元素:宽度为包裹内容的宽度
粘性定位
sticky
z-index
z-index只对定位元素有效