【问题标题】:Positioning a child element above an element having z-index greater than it's parent将子元素定位在 z-index 大于其父元素的元素上方
【发布时间】:2014-10-18 16:48:06
【问题描述】:

正如标题所说,我正在尝试将一个元素定位在 z-index 大于其父元素的元素上方。

例如,我有以下 HTML:

HTML:

<div class="line">
    <div class="info"></div>
</div>
<div class="box"></div>

和 CSS:

body {
    margin: 50px;
}

.box {
    background: grey;
    width: 500px;
    height: 40px;
    z-index: 10;
    position: relative;
}

.line {
    background: blue;
    width: 500px;
    height: 5px;
    z-index: 9;
    position: relative;
    top: 0;
    overflow: visible;
}

.line .info {
    width: 50px;
    height: 25px;
    background: red;
}

正如你在jsfiddle 中看到的那样,红线 (.info) 实际上应该是一个更大的矩形,但你看不到它的原因是因为它隐藏在灰色 @ 后面987654326@.

如何更改z-index 的周围,使红色框显示在灰色框上方,而蓝色.line 留在灰色框后面?

【问题讨论】:

标签: html css


【解决方案1】:

如果您将 .line 的 z-index 设置为高于 .box 的 z-index,这将导致红色框显示在灰色框之上:

.box{
    z-index: 1
}
.line {
    z-index: 2
}

这应该可以解决问题。

编辑: 将 .info div 移到 .line 之外,例如

HTML:

<div class="line"></div>
<div class="info"></div>
<div class="box"></div>

CSS:

.box {
    z-index:10;
}
.line {
    z-index:9;
}
.box {
    z-index:11;
}

【讨论】:

  • .line 需要在.box 后面。
  • 好吧,问题出在你的 html 代码的结构上,因为 redbox(.info) 位于 .line 元素内,它有一个相对于这个容器的 z-index。因此,您需要做的是将 .info 移到 .line 元素之外,这样它将与 .box 元素处于同一级别,并且能够将其 z-index 与其他元素进行比较。
【解决方案2】:

来自CSSTricks z-index

还要注意嵌套起着重要作用。如果元素 B 位于元素 A 之上,则元素 A 的子元素永远不会高于元素 B。

这正是您想要做的。如果你想让.line.box 后面,它的子.info 永远不能出现在.box 的顶部,因为它的父本身在它后面。

为了实现你想要的,你应该改变你的HTML结构,使.info.line之外。

例如:

.box {
  position: relative;
  z-index: 1;
  width: 500px;
  height: 40px;
  background: grey;
}
.box .info {
  width: 50px;
  height: 25px;
  background: red;
}
.line {
  position: relative;
  top: 45px;
  width: 500px;
  height: 50px;
  background: blue;
}
<div class="line"></div>
<div class="box">
  <div class="info"></div>
</div>

【讨论】:

  • .line 需要在 .box 后面。
  • 使用您当前的标记,我认为不可能使用 z-index 将 .line 放在 .box 后面和 .info 同时放在 .box 前面,因为 .info 是.line,为此将 .info 设置在当前标记之外并将其放置在 .box 后面,然后应用比 .box 更低的 z-index。
猜你喜欢
  • 2023-02-24
  • 2020-10-06
  • 2011-01-31
  • 2013-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-17
相关资源
最近更新 更多