CSS笔记第三部分
1.position定位
定位属性用于指定一个元素在文档中的定位方式。top、right、bottom、left属性决定了该元素的最终位置
position取值:
static(默认)
relative(相对定位)
absolute(绝对定位)
fixed(固定定位)
sticky(黏性定位)
relative相对定位
如果没有定位偏移量,则对元素位置没有影响
不使元素脱离文档流
不影响其他元素的布局
left、top、right、bottom是相对于当前元素自身 进行偏移的
absolute绝对定位
使元素完全脱离文档流
使内联元素支持宽高 (让内联具备块特性)
使块元素默认宽根据内容决定 (让块具备内联的特性)
如果有定位祖先元素相对于定位祖先元素 发生偏移,没有定位祖先元素相对于整个文档 发生偏移(绝对、相对、固定)
< style>
.box1 {
width : 300px; height : 300px; border : 1px black solid; margin : 180px; position : absolute; }
.box2 {
width : 100px; height : 100px; position : absolute; left : 0; bottom : 0; background : red; }
</ style>
fixed固定定位
使元素完全脱离文档流
使内联元素支持宽高 (让内联具备块特性)
使块元素默认宽根据内容决定 (让块具备内联的特性)
相对于浏览器窗口进行偏移,不受滚动条影响(可以实现返回页面顶部的效果)
sticky粘性定位
< style>
body {
height : 3000px; }
div {
background : red; position : sticky; top : 0; }
</ style>
< body>
< div> 这是一个块</ div>
</ body>
z-index定位层级
默认层级为0
嵌套的时候层级:比较同级元素的定位层级,若同级元素不存在z-index,则比较嵌套内元素的层级。
< style>
.parent {
width : 100px; height : 100px; border : 1px solid black; position : absolute; z-index : -2; }
.box1 {
width : 100px; height : 100px; background : red; position : absolute; z-index : 0; }
.box2 {
width : 100px; height : 100px; background : blue; position : absolute; left : 50px; top : 50px; z-index : -1; }
</ style>
< body>
< div class