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`。否则,它将不起作用。
数据结构
网络
关系型数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP