更改子元素的z-index顺序

时间:2017-01-19 23:02:29

标签: html css z-index

我在子元素中的z-index值有问题。 结构看起来像这样:

#header {
  position: relative;
  z-index: 2;
  width: 100%;
  height: 15vh;
  display: block;
  margin: 0 auto;
  background-color: white;
  color: #44a9ff;
  padding: 0;
  overflow: hidden;
  border-bottom: 3px solid #44a9ff;
  -webkit-box-shadow: 8px 1px 41px 0px rgba(0, 0, 0, 0.75);
  -moz-box-shadow: 8px 1px 41px 0px rgba(0, 0, 0, 0.75);
  box-shadow: 8px 1px 41px 0px rgba(0, 0, 0, 0.75);
}
#main {
  position: relative;
  z-index: 1;
  width: 100%;
  height: 75vh;
  display: block;
  margin: 0 auto;
  overflow: hidden;
  padding: 0;
  background: url('img/main_bg.jpg') no-repeat center center;
  background-size: cover;
  border-bottom: 3px solid #44a9ff;
}
#box {
  position: relative;
  z-index: 10;
  width: 40%;
  height: 38vh;
  background-color: #44a9ff;
  float: right;
  color: white;
  display: block;
  overflow: hidden;
}
<div id="nav">
  <ul>
    <li><a href="#">..</a></li>
    <li><a href="#">..</a></li>
  </ul>
</div>
<div id="main">
  <div id="box">
  </div>
</div>

元素#nav具有z-index 2,因为底部有框阴影。 #main具有z-index 1,因为当更高时,阴影不可见。并且有#box,其中z索引为3,因为我需要它来覆盖#nav的阴影。但它可能具有#main的z-index值,因此它不包括它。我该怎么办呢?

2 个答案:

答案 0 :(得分:1)

尝试将#box移出#main并为其提供自定义css代码以使其位于正确的位置

    <div id="nav">
      <ul>
        <li><a href="#">..</a></li>
        <li><a href="#">..</a></li>
      </ul>
    </div>

  <div id="box">
  </div>

<div id="main">

</div>

答案 1 :(得分:1)

尝试从#box中取出#main并将absolute设置为right&amp; top坐标:

&#13;
&#13;
#header {
  position: relative;
  z-index: 2;
  width: 100%;
  height: 15vh;
  display: block;
  margin: 0 auto;
  background-color: white;
  color: #44a9ff;
  padding: 0;
  overflow: hidden;
  border-bottom: 3px solid #44a9ff;
  -webkit-box-shadow: 8px 1px 41px 0px rgba(0, 0, 0, 0.75);
  -moz-box-shadow: 8px 1px 41px 0px rgba(0, 0, 0, 0.75);
  box-shadow: 8px 1px 41px 0px rgba(0, 0, 0, 0.75);
}
#main {
  position: relative;
  z-index: 1;
  width: 100%;
  height: 75vh;
  display: block;
  margin: 0 auto;
  overflow: hidden;
  padding: 0;
  background: url('img/main_bg.jpg') no-repeat center center;
  background-size: cover;
  border-bottom: 3px solid #44a9ff;
  background: green;
}
#box {
  /* set it absolute */
  position: absolute;
  /* tweak coordinates to your benefit */
  right: 8px;
  top: 19vh;
  z-index: 3;
  width: 40%;
  height: 38vh;
  background-color: #44a9ff;
  color: white;
  display: block;
  overflow: hidden;
}
&#13;
<div id="header">
  <div id="nav">
    <ul>
      <li><a href="#">..</a>
      </li>
      <li><a href="#">..</a>
      </li>
    </ul>
  </div>
</div>
<div id="main"></div>
<div id="box"></div>
&#13;
&#13;
&#13;