html - 在 Chrome 中使用 `z-index` 的固定父元素下的元素

标签 html css google-chrome webkit z-index

我想要一个元素 (div) 在其固定父元素 (header) 下分层:

header {
  position: fixed;
  width: 100%;
  height: 100px;
  
  background-color: #ccc;
}
header > div {
  position: absolute;
  height: 100%;
  width: 100px;
  z-index: -1;
  
  transform: translateY(50%);
  background-color: #aaa;
}
<header>
  <div>
  </div>
</header>

这在 Firefox 中有效,但在 Chrome 中无效。要修复它,您需要这样做:

header {
  position: fixed;
  width: 100%;
  height: 100px;
}
header > div {
  position: relative;
  width: 100%;
  height: 100%;
  
  background-color: #ccc;
}
header > div > div {
  position: absolute;
  height: 100%;
  width: 100px;
  z-index: -1;

  transform: translateY(50%);
  background-color: #aaa;
}
<header>
  <div>
    <div>
    </div>
  </div>
</header>

但这很糟糕! 根据规范,Firefox 或 Chrome 谁错了?是否有更好的方法来跨浏览器完成这项工作?

最佳答案

试试这个,

header {
  position: fixed;
  width: 100%;
  height: 100px;
  background-color: #ccc;
  overflow: hidden;
}
header > div {
  height: 100%;
  z-index: -1;
  transform: translateY(50%);
  background-color: #aaa;
  overflow: hidden;
}
<header>
   <div></div>
</header>

看来我误解了你的问题。无论如何,答案是 chrome 是正确的。我认为更好的解决方案是使用相同级别的两个 DIV(如果可能)。

header {
  position: fixed;
  width: 100%;
  overflow: hidden;
  
}
header .header-inner {
  position: relative;
  height: 100px;
  width: 100%;
  z-index: 1;
  background-color: #ccc;
}

header .under-layer {
  position: absolute;
  height: 100%;
  z-index: -1;
  transform: translateY(50%);
  background-color: #aaa;
  overflow: hidden;
  top: 0px;
  width: 100%;
}
<header>
  <div class="header-inner"></div>
  <div class="under-layer"></div>
</header>

关于html - 在 Chrome 中使用 `z-index` 的固定父元素下的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31415727/

相关文章:

php - 重复内容 - PHP 包括? [搜索引擎优化]

javascript - 如何设置动态定位的div的正确position()

asp.net - 如何使用 Reimer ASP.NET 控件更新 div?

css - 我想用 CSS3 做曲线

css - 带有垂直中间字符/图标的 Bootstrap 面板标题

javascript - 将对象插入数组 CSS 的问题 | JS | HTML

html - 试图在缩略图悬停时显示大图像

javascript - 无响应 header 时允许 CORS Access-Control-Allow-Origin

java - 在 Linux 上点击 chrome headless 按钮时弹出窗口未打开

javascript - 使用网站冲浪时停止事件监听器操作