Rumah > Artikel > hujung hadapan web > 详解css z-index的权重问题

本篇文章给大家分享一下css的z-index权重问题。到底怎么样才能让我们想要排在上面的元素能在上面,想在下面的元素就老老实实的在下面。
一个定义了定位,一个没定义定位,谁在上面?
一个父级盒子定位,一个不定位,不定位的子级设置定位,谁在上面?
一个父级盒子定位,一个不定位,不定位的子级设置定位,并给定位的子级元素加z-index,谁在上面?
俩个都定位,但是都不设置z-index,谁在上面?
俩个都定位,一个设置z-index为1,谁在上面?
定义一下基本的dom结构:

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
* {margin: 0;padding: 0;}
.box1, .box2 {
width: 500px;
height: 200px;
border: 2px solid;
margin: 10px;
}
.box1 {
background: yellow;
}
.box2 {
background: aqua;
}
.redDiv, .blueDiv {
width: 150px;
height: 150px;
}
.redDiv {
background: red;
}
.blueDiv {
background: blue;
}
</style>
</head>
<body>
<div>
<div></div>
</div>
<div>
<div></div>
</div>
</body>
</html>一个定义了定位,一个没定义定位,谁在上面?
我们给box2设置定位并改变它的位置
.box2 {
background: aqua;
position: fixed;
left: 100px;
top: 30px;
}效果:
box2跑到了box1的上面。

一个父级盒子定位,一个不定位,不定位的子级设置定位,谁在上面?
我们给box1盒子里的redp设置定位
.redp {
background: red;
position: fixed;
}
效果:
box2还是在box1的上面。也在box1的定位子元素上面。

一个父级盒子定位,一个不定位,不定位的子级设置定位,并给定位的子级元素加z-index,谁在上面?
我们给box1盒子里的redp追加z-index
.redp {
background: red;
position: fixed;
z-index: 1;
}
效果:
redp在最上面,box2在中间,box1在最下面。

俩个都定位,但是都不设置z-index,谁在上面?
我们首先恢复我们初始的样式代码然后重新改。
在初始的代码里更改box1与box2的样式
.box1 {
background: yellow;
position: fixed;}.box2 {
background: aqua;
position: fixed;
left: 100px;
top: 30px;}
效果:
box2在box1的上面
俩个都定位,一个设置z-index为1,谁在上面?
我们吧box1的z-index设置为1:
.box1 {
background: yellow;
position: fixed;
z-index: 1;}
效果:
box1跑到了box2的上面
更多编程相关知识,请访问:编程教学!!
Atas ialah kandungan terperinci 详解css z-index的权重问题. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!