加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 资源网站 > 资源 > 正文

html – 使用z-index将div高于另一个div

发布时间:2020-12-14 18:48:24 所属栏目:资源 来源:网络整理
导读:我希望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"/divdiv class="div2"/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>

解决方法

您可以添加位置:相对于两个div并创建 stacking context
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应该放在3D空间中而不是在平面上展平.

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>

您也可以使用一些随机的transform,如translate或rotate

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>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读