首页 > IT职业 > IT图书 > 自学 CSS 之 z-index 属性
个人学习笔记,谨慎参考!
整理自慕课网,张鑫旭老师的课程 https://www.imooc.com/video/11629
测试代码
.html
<div class="father1">
<div class="son1"></div>
</div>
<div class="father2">
<div class="son2"></div>
</div>
.css
.father1{
left: 100px;
width: 200px; height: 200px;
background: #00cccc;
position: absolute;
z-index: 1;
}
.son1{
background: #008cc8;
width: 180px; height: 180px;
position: absolute;
z-index: 2;
}
.father2{
left: 120px; top: 10px;
width: 200px; height: 200px;
background: #ff6633;
position: relative;
z-index: 1;
}
.son2{
background: #ff9933;
width: 180px; height: 180px;
position: relative;
z-index: 1;
}
father1 -> z-index: 1;son1 -> z-index: 2;
father2 -> z-index: 1;son2 -> z-index: 1;
按照祖先优先,后来居上的原则,祖先元素 z-index 属性相同时,不看子元素的 z-index,同时遵守后来居上原则,则 2 排布于 1 之上。
更改代码为
father1 -> z-index: 2;son1 -> z-index: 1;
father2 -> z-index: 1;son2 -> z-index: 2;
元素按照该图的层叠顺序排布。页面的根元素天生具有层叠上下文。
参与层叠上下文,元素才有 z-index 属性的默认值为 auto,然后可参照层叠顺序表。
z-index 层叠上下文 三个要点
是不是可以理解成参与层叠上下文不代表创建了层叠上下文,设定 z-index的值后才算是创建了呢?
定位之后是 z-index 的值是auto;当定位元素的 z-index 不是 auto 的时候就会创建层叠上下文。
opacity 不为 1 是层叠上下文元素,z-index:atuo; 和 absolute 一样,所以后来居上。
opacity 为 1 是普通元素,因为文字是绝对定位,所以位于上方。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/4759/viewspace-2823200/ ,如需转载,请注明出处,否则将追究法律责任。