CSS定位绝对需要兄弟元素的相对位置

标签 css css-position

我有一个简单的设置,我有一个汉堡包样式的菜单,它启用了一个将主要内容向右滑动的非 Canvas 菜单 ( something like this )。

<div class="layout-wrapper" >
    <div class="layout-menu"></div>

    <header class="layout-header"></header>

    <div class="layout-content"></div>
</div>

所以我有一个容器 div:layout-wrapper

我有菜单:layout-menu,具有绝对定位,因此我可以将主要内容放在上面。

我有标题:layout-header,具有固定的定位,因此当我滚动内容时它始终保持在顶部

我有内容:layout-content

我的问题是 layout-content 不可见,除非我向它添加 position: relative。为什么我必须这样做?我犯了一个愚蠢的错误吗?

这是一个plunker显示问题。启用 CSS 中的注释行以查看它应该的样子。

最佳答案

问题是 .layout-menu 是一个定位元素:

.layout-menu {
    position: absolute;
}

但是 .layout-content 不是:

.layout-content {
    position: static; /* default value */
}

根据 CSS 2.1 spec ,

Each box belongs to one stacking context. Each box in a given stacking context has an integer stack level, which is its position on the z-axis relative to other boxes in the same stacking context. Boxes with greater stack levels are always formatted in front of boxes with lower stack levels. [...]

Each stacking context consists of the following stacking levels (from back to front):

  1. the background and borders of the element forming the stacking context.
  2. the stacking contexts of descendants with negative stack levels.
  3. a stacking level containing in-flow non-inline-level descendants.
  4. a stacking level for floats and their contents.
  5. a stacking level for in-flow inline-level descendants.
  6. a stacking level for positioned descendants with 'z-index: auto', and any descendant stacking contexts with 'z-index: 0'.
  7. the stacking contexts of descendants with positive stack levels.

也就是说.layout-menu,属于stacking level 6,会显示在.layout-content,属于stacking level的前面3.

但是,如果你使用

.layout-content {
    position: relative;
}

现在 .layout-content 也将落入堆叠级别 6。

然后,

Boxes with the same stack level in a stacking context are stacked back-to-front according to document tree order.

因此,由于 .layout-content 在文档树中位于 .layout-menu 之后,因此 .layout-content 将显示在.layout-menu 的前面。

关于CSS定位绝对需要兄弟元素的相对位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27771033/

相关文章:

jquery - 使用 jQuery 获取位置 :absolute content is running twice, 的高度第二次返回不正确的值

html - 垂直居中,高度可变

html - CSS:具有顶部和中心对齐的 div 的 flexbox 容器

html - 如何在可滚动的 div 元素内使用 CSS 绝对位置

html - 具有动态内容的内部 div 的 CSS 宽度规则

css - 样式表 : 1 big one or a few bigones or several smaller ones?

javascript - 单击一定数量后更改 div 背景

html - flexbox 元素内的固定元素

javascript - 固定位置不适用于 ios 设备

html - 在保持响应式列布局的同时使用 Bootstrap 词缀