使用z-index将div置于另一个div之上

我希望在div1上面div2。我尝试使用,z-index但不起作用。

我已经试过这段代码:

div {

width: 100px;

height: 100px;

}

.div1 {

background: red;

z-index: 1;

}

.div2 {

background: blue;

margin-top: -15vh;

z-index: 2

}

<div class="div1"></div>

<div class="div2"></div>

回答:

您可以同时添加position: relative到div和创建stackingcontext

div {

width:100px;

height: 100px;

}

.div1 {

background: red;

z-index: 2;

position: relative;

}

.div2 {

background: blue;

margin-top: -15vh;

z-index: 1;

position: relative;

}

<div class="div1"></div>

<div class="div2"></div>

或者您可以使用transform-style: preserve-3d;,现在.div1应该将其放置在 而不要在平面中展平。

div {

width:100px;

height: 100px;

}

.div1 {

background: red;

z-index: 2;

transform-style: preserve-3d;

}

.div2 {

background: blue;

margin-top: -15vh;

z-index: 1;

}

<div class="div1"></div>

<div class="div2"></div>

您也可以使用一些随机的transformtranslaterotate

div {

width:100px;

height: 100px;

}

.div1 {

background: red;

z-index: 2;

transform: translate(1px);

}

.div2 {

background: blue;

transform: translate(1px, -15vh);

z-index: 1;

}

<div class="div1"></div>

<div class="div2"></div>

Filters也可以,但是它们不好 Support

div {

width:100px;

height: 100px;

}

.div1 {

background: red;

filter: brightness(0.4);

z-index: 2;

}

.div2 {

background: blue;

margin-top: -15vh;

filter: brightness(0.4);

z-index: 1;

}

<div class="div1"></div>

<div class="div2"></div>

以上是 使用z-index将div置于另一个div之上 的全部内容, 来源链接: utcz.com/qa/419304.html

回到顶部