CSS 佈局 - z-index 屬性
z-index
屬性用於指定元素的堆疊順序。
z-index 屬性
當元素進行定位時,它們可以與其他元素重疊。
z-index
屬性指定元素的堆疊順序(哪個元素應該在其他元素的前面或後面)。
元素可以具有正數或負數的堆疊順序
這是一個標題

由於影像的 z-index 為 -1,它將顯示在文字的後面。
注意: z-index
僅對 已定位元素(position: absolute, position: relative, position: fixed, or position: sticky)以及 flex 項(作為 display: flex 元素的直接子元素)有效。
另一個 z-index 示例
示例
在這裡,我們看到具有較高堆疊順序的元素總是顯示在堆疊順序較低的元素之上
<html>
<head>
<style>
.container {
position: relative;
}
.black-box {
position: relative;
z-index: 1;
border: 2px solid black;
height: 100px;
margin: 30px;
}
.gray-box {
position: absolute;
z-index: 3;
background: lightgray;
height: 60px;
width: 70%;
left: 50px;
top: 50px;
}
.green-box {
position: absolute;
z-index: 2;
background: lightgreen;
width: 35%;
left: 270px;
top: -15px;
height: 100px;
}
</style>
</head>
<body>
<div class="container">
<div class="black-box">Black box</div>
<div class="gray-box">Gray box</div>
<div class="green-box">Green box</div>
</div>
</body>
</html>
自己動手試一試 »
不使用 z-index
如果兩個已定位的元素相互重疊,而沒有指定 z-index
,則 **在 HTML 程式碼中最後定義的元素** 將顯示在上面。
示例
與上面相同的示例,但這裡沒有指定 z-index
<html>
<head>
<style>
.container {
position: relative;
}
.black-box {
position: relative;
border: 2px solid black;
height: 100px;
margin: 30px;
}
.gray-box {
position: absolute;
background: lightgray;
height: 60px;
width: 70%;
left: 50px;
top: 50px;
}
.green-box {
position: absolute;
background: lightgreen;
width: 35%;
left: 270px;
top: -15px;
height: 100px;
}
</style>
</head>
<body>
<div class="container">
<div class="black-box">Black box</div>
<div class="gray-box">Gray box</div>
<div class="green-box">Green box</div>
</div>
</body>
</html>
自己動手試一試 »
CSS 屬性
屬性 | 描述 |
---|---|
z-index | 設定元素的堆疊順序 |