【问题标题】:z-index not working with position relativez-index 不适用于相对位置
【发布时间】:2022-10-17 13:17:14
【问题描述】:

我写的css编码是以下几行。但不工作z-index

我想知道如何使z-index 工作,同时将position 的值保持为relative

      #foo {
        position: relative;
        z-index: -1;
        width: 100%;
        height: 30%;
        background-color: lightblue;
      }

      #bar {
        width: 50%;
        height: 30%;
        background-color: lightpink;
      }

据我所知,如果您将position 的值设置为非静态值,z-index 应该可以工作。是否还有其他因素会影响z-index

此外,如果我将 position 的值更改为 absolute 它工作正常。

positionrelative

positionabsolute

【问题讨论】:

  • 当使用相对位置时,该元素将保持在页面的自然流动中。它还使元素定位。它将充当子元素的锚点。你可以在这里阅读更多:cssreference.io/positioning
  • 实际目标是什么?如何它不适合你吗?

标签: html css


【解决方案1】:
  • 一切都按您的需要运行,您可以看到我已将margin-bottom:-20px; 添加到.foo,这样您就可以确定.foo.bar 后面。
  • 了解该位置不会使项目脱离流程,这会将其保持在其位置。要真正看到这一点,两个元素之间必须有一些重叠,而不是您可以看到z-index 的效果。

html,
body {
  width: 100%;
  height: 100%;
}

#foo {
  position: relative;
  z-index: -1;
  width: 100%;
  height: 30%;
  background-color: lightblue;
  margin-bottom: -20px;
}

#bar {
  width: 50%;
  height: 30%;
  background-color: lightpink;
}
<div id="foo">Foo</div>
<div id="bar">Bar</div>

【讨论】:

    猜你喜欢
    • 2013-01-07
    • 1970-01-01
    • 1970-01-01
    • 2016-02-22
    • 2014-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多