css制作叠层
CSS制作叠层效果的方法
使用CSS的z-index属性可以控制元素的叠放顺序。数值越大,元素越靠前显示。以下是几种常见的叠层实现方式:
使用position和z-index
.parent {
position: relative;
width: 300px;
height: 300px;
}
.layer1 {
position: absolute;
z-index: 1;
width: 200px;
height: 200px;
background: red;
}
.layer2 {
position: absolute;
z-index: 2;
width: 150px;
height: 150px;
background: blue;
top: 50px;
left: 50px;
}
使用CSS Grid实现叠层
.container {
display: grid;
}
.container > * {
grid-area: 1/1;
}
使用Flexbox实现叠层
.container {
display: flex;
}
.layer {
position: relative;
}
.layer-overlap {
position: absolute;
top: 0;
left: 0;
}
注意事项
- 只有定位元素(position不为static)才能使用z-index
- 父元素的z-index会创建新的堆叠上下文
- 负z-index值可以将元素置于父元素背景下方
- 透明度(opacity)小于1也会创建新的堆叠上下文
堆叠上下文示例
<div class="stack-container">
<div class="layer1"></div>
<div class="layer2"></div>
</div>
.stack-container {
position: relative;
height: 200px;
}
.layer1 {
position: absolute;
z-index: 1;
width: 100%;
height: 100%;
background: rgba(255,0,0,0.5);
}
.layer2 {
position: absolute;
z-index: 2;
width: 80%;
height: 80%;
background: rgba(0,0,255,0.5);
top: 10%;
left: 10%;
}






