CSS 中 z-index 屬性的最大值和最小值是多少?


在 CSS 中,z-index 屬性用於將一個元素放在另一個元素之上。例如,我們可以使用 CSS 建立多個 HTML 元素的堆疊效果。

如果您曾經使用過 z-index 屬性,您一定見過它的值,例如 9、99、999、0、-9、-99999 等。您是否曾經想過 z-index 的最大值是多少,並在網際網路上搜索過相關資訊?如果沒有,請閱讀本指南。

z-index 屬性的最大值為 2147483647,最小值為 -2147483647。數字 2147483647 等於 232,這是 32 位二進位制數的最大值。

注意 - z-index 屬性不適用於 `static` 定位。因此,使用者需要更改元素的定位。

在這裡,我們將學習如何透過各種示例使用 z-index 屬性。

語法

使用者可以按照以下語法使用 z-index 屬性建立元素堆疊效果。

.class_name {
   z-index: -9;
}

在上面的語法中,我們使用了 -9 作為 z-index 的值,這將應用於包含類 `class_name` 的 HTML 元素。

示例 1

在下面的示例中,我們建立了三個不同的 div 元素。我們使用 CSS 來設定 div 元素的樣式。我們為 div 元素設定了不同的高度和寬度。此外,我們還為每個 div 元素設定了背景顏色。

我們為第一個 div 設定了 -9 的 z-index 值,為第二個 div 設定了 2,為第三個 div 設定了 10。在輸出中,使用者可以看到第三個 div 位於所有 div 元素的頂部,第二個 div 位於第一個和第三個 div 元素之間。

<html>
<head>
   <style>
      .div1 {
         position: absolute;
         width: 500px;
         height: 350px;
         background-color: aqua;
         z-index: -9;
      }
      .div2 {
         position: absolute;
         width: 300px;
         height: 300px;
         background-color: pink;
         z-index: 2;
         left: 50px;
         top: 50px;
      }
      .div3 {
         position: absolute;
         width: 200px;
         height: 200px;
         left: 200px;
         top: 200px;
         background-color: black;
         z-index: 10;
         color: white;
      }
   </style>
</head>
<body>
   <h2>Using the <i> Z-index property of CSS </i> to create a stack of elements</h2>
   <div class = "div1">
      <p> This is a first div. </p>
   </div>
   <div class = "div2">
      <p> This is a second div. </p>
   </div>
   <div class = "div3">
      <p> This is a third div. </p>
   </div>
</body>
</html>

示例 2

在下面的示例中,我們建立了兩個巢狀的 div 元素,併為這兩個 div 元素賦予了不同的類名。此外,我們還為第一個 div 元素設定了 `relative` 定位,為第二個 div 元素設定了 `absolute` 定位。

我們將 -2147483647 作為第一個 div 元素的 z-index 值,將 2147483647 作為第二個 div 元素的 z-index 值。這意味著我們將 z-index 的最小值和最大值分配給了 div 元素。

在輸出中,div 元素根據 z-index 值以相同的順序顯示。

<html>
<head>
   <style>
      .div1 {
         z-index: -2147483648;
         background-color: blue;
         width: 500px;
         height: 400px;
         position: relative;
      }
      .div2 {
         z-index: 2147483647;
         background-color: grey;
         width: 300px;
         height: 300px;
         position: absolute;
         top: 50px;
         left: 50px;
         font-size: 1rem;
      }
   </style>
</head>
<body>
   <h3>Using the <i> maximum value of Z-index property of CSS </i> to create a stack of elements</h3>
   <div class = "div1">
      <div class = "div2">
         <h3>This is the top most element</h3>
      </div>
   </div>
</body>
</html>

在本教程中,使用者學習瞭如何在 HTML 元素中使用 z-index 屬性。此外,使用者還了解了 z-index 的最小值和最大值,它們等於 32 位二進位制數的最小值和最大值。此外,每當我們將 z-index 屬性與任何元素一起使用時,都應將其位置更改為 `fixed`、`relative` 或 `absolute`。否則,它將不起作用。

更新於:2023年4月11日

2K+ 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.