CSS 定位
布局和定位的区别:
布局是屏幕平面上的,定位是垂直于屏幕的
DIV的分层:
Z轴视角从上到下分别为
内联元素 > 浮动元素 > 块级子元素 > border > background
内联元素与浮动等内联元素的覆盖是具有层叠性的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
.xiongda { background-color: red; z-index: 1; } .xionger { background-color: green; left: 50px; top: 50px; } .xiongsan { background-color: blue; left: 100px; top: 100px; }
|
属性:
position
static 默认值,处于文档流中
relative 相对定位,会浮起来,但不脱离文档流
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| .yeye { position: relative; width: 800px; height: 800px; background-color: steelblue; }
.father { width: 500px; height: 500px; background-color: skyblue; }
.son { position: absolute;
top: 100px; right: 200px; width: 200px; height: 200px; background-color: pink; }
|
abosolute 绝对定位,根据祖级元素定位,脱离文档流
加了绝对定位的盒子不能通过margin:auto设置水平居中
1 2 3 4 5 6 7 8 9 10 11 12 13
| .box { position: absolute; left: 50%; top: 50%; margin-left: -100px; margin-top: -100px; width: 200px; height: 200px; background-color: pink; }
|
fixed 固定定位,根据 viewport 进行定位
主要使用场景:可以在浏览器页面滚动时元素的位置不会改变
1 2 3 4 5 6
| .hs { position: fixed; left: 50%; top: 200px; margin-left: 400px; }
|
sticky 粘贴定位,根据与窗口之间的距离判断是否固定。
1 2 3 4 5 6 7 8 9 10 11 12 13
|
.nav { position: sticky; top: 10px; width: 800px; height: 50px; background-color: pink; margin: 100px auto; }
|
子绝父相
如果写了一个absolute,一般都得在父级补一个relative
如果写了absolut 或 fixedk,一定要补充 top 和 left
子绝父相是永远不变的,如果父元素不需要占有位置则是子绝父绝