在 CSS 中,您可以创建各种分区的层。CSS z-index 属性可以与 position 属性结合使用,以创建图层效果。
z-index 属性指定元素的堆叠顺序。您可以指定哪个元素应该位于顶部,哪个元素应该位于底部。
z-index 属性可以帮助您创建更复杂的网页布局。
CSS 图层 - 具有 z-index 属性
以下示例演示如何使用 z-index 属性创建图层。具有较高 z 指数值的元素位于较低 z 指数值的元素上方 −
<html>
<head>
<style>
.box1 {
position: absolute;
height: 100px;
width: 100px;
background-color: red;
z-index: 1;
padding: 3px;
left: 10px;
top: 10px;
}
.box2 {
position: absolute;
height: 100px;
width: 100px;
background-color: lightblue;
z-index: 2;
padding: 5px;
margin: 10px;
left: 50px;
top: 30px;
}
.box3 {
position: absolute;
height: 100px;
width: 100px;
background-color: yellow;
z-index: 3;
padding: 5px;
margin: 20px;
left: 80px;
top: 50px;
}
p {
margin-top: 200px;
}
</style>
</head>
<body>
<p>The element with z-index value of 1 appears behind the elements with the z-index value of 2 and 3.</p>
<div class="box1">
CSS z-index: 1
</div>
<div class="box2">
CSS z-index: 2
</div>
<div class="box3">
CSS z-index: 3
</div>
</body>
</html>
CSS 图层 - 图像和文本
以下示例演示如何使用 z-index 属性创建图层。较高的 z 指数元素位于较低的 z 指数元素上方 -
<html>
<head>
<style>
img {
height: 200px;
width: 200px;
position: absolute;
left: 0px;
top: 0px;
z-index: 2;
margin: 5px;
}
h1 {
margin-top: 30px;
z-index: 1;
color: red;
}
</style>
</head>
<body>
<img src="images/shop.png">
<h3>Tutorialspoint</h3>
</body>
</html>
CSS 图层 - 没有 z-index 属性
以下示例演示了如何在不使用 z-index 属性的情况下创建图层 -
<html>
<head>
<style>
.box1 {
position: absolute;
height: 210px;
width: 210px;
background-color: red;
padding: 10px;
left: 10px;
top: 10px;
}
.box2 {
position: absolute;
height: 150px;
width: 150px;
background-color: lightblue;
padding: 10px;
margin: 10px;
left: 30px;
top: 30px;
}
.box3 {
position: absolute;
height: 100px;
width: 100px;
background-color: yellow;
padding: 5px;
margin: 10px;
left: 60px;
top: 60px;
}
</style>
</head>
<body>
<div class="box1">
Box 1
</div>
<div class="box2">
Box 2
</div>
<div class="box3">
Box 3
</div>
</body>
</html>