为什么???父元素position: fixed的子元素也position: fixed覆盖不了transform的元素?

如下代码:为什么 shade 层不能 覆盖在 content 层上?

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>test</title>
  <style>
     html, body{
      width: 100%;
      height: 100%;
      padding: 0;
      margin: 0;
    }
    .header{
      height: 30px;
      background: yellow;
      position: fixed;
      width: 100%;
      top: 0;
    }
    .content{
      height: calc(100% - 30px);
      width: 100%;
      background: rgba(204,0,255, 0.5);
      transform: translateY(30px);
    }
    .header .shade{
      height: calc(100% - 30px);
      width: 200px;
      background: tomato;
      position: fixed;
      left: 0;
      top: 30px;
    }
  </style>
</head>
<body>
  <div class="header">
    <div class="shade"></div>
  </div>
  <div class="content"></div>
</body>
</html>

image.png

阅读 4.3k
2 个回答

两种方法:

<body>
  <div class="content"></div>
  <div class="header">
    <div class="shade"></div>
  </div>
</body>

当然这从语义上是有毛病的,所以推荐:

.header{
    z-index: 2;
}

如果不加z-index,正常shade不应该作为content的子节点吗?无法理解是放在header中。

如果你坚持shade节点在header中,就下面这样子咯

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>test</title>
  <style>
     html, body{
      width: 100%;
      height: 100%;
      padding: 0;
      margin: 0;
    }
    .header{
      height: 30px;
      background: yellow;
      width: 100%;
      top: 0;
    }
    .content{
      height: calc(100% - 30px);
      width: 100%;
      background: rgba(204,0,255, 0.5);
    }
    .header .shade{
      height: calc(100% - 30px);
      width: 200px;
      background: tomato;
      position: fixed;
      left: 0;
      top: 30px;
    }
  </style>
</head>
<body>
  <div class="header">
    <div class="shade"></div>
  </div>
  <div class="content"></div>
</body>
</html>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题