首页 > 解决方案 > 为什么 z-index 被忽略?

问题描述

为什么 z-index 被忽略?我希望红色背景的 div 覆盖整个窗口。

.nav-bar {
  background: #673ab7;
  height: 4rem;
  width: 100%;
  position: relative;
  z-index: -100;
}

.nav-bar div {
  display: inline-block;
  top: 1em;
  position: absolute;
}

.nav-bar__section {
  display: inline-block;
  color: rgb(255, 255, 255, 0.87);
  font-size: 1.4rem;
  position: absolute;
  left: 2.5rem;
}

.title-bar {
  height: 5rem;
  width: 100%;
  background-color: white;
  text-align: center;
  vertical-align: middle;
  line-height: 90px;
  font-family: 'Roboto', sans-serif;
  font-size: 24px;
  font-weight: 200;
}

.side-bar {
  position: fixed;
  height: 100%;
  width: 30%;
  background-color: red;
  z-index: 3;
}
<html>

<head>
  <link rel="stylesheet" href="styles.css">
  <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
</head>

<body>
  <div class="nav-bar">
    <div class="nav-bar__section">
      Book Collection
    </div>
  </div>
  <div class="side-bar">

  </div>
  <div class="title-bar">
    My Collection
  </div>
</body>

</html>

生成的 HTML

在此处输入图像描述

标签: htmlcss

解决方案


您应该在 上定义顶部位置.side-bar

.nav-bar {
  background: #673ab7;
  height: 4rem;
  width: 100%;
  position: relative;
  z-index: -100;
}

.nav-bar div {
  display: inline-block;
  top: 1em;
  position: absolute;
}

.nav-bar__section {
  display: inline-block;
  color: rgb(255, 255, 255, 0.87);
  font-size: 1.4rem;
  position: absolute;
  left: 2.5rem;
}

.title-bar {
  height: 5rem;
  width: 100%;
  background-color: white;
  text-align: center;
  vertical-align: middle;
  line-height: 90px;
  font-family: 'Roboto', sans-serif;
  font-size: 24px;
  font-weight: 200;
}

.side-bar {
  position: fixed;
  height: 100%;
  width: 30%;
  background-color: red;
  z-index: 3;
  top: 0;
}
<div class="nav-bar">
  <div class="nav-bar__section">
    Book Collection
  </div>
</div>
<div class="side-bar">

</div>
<div class="title-bar">
  My Collection
</div>


推荐阅读