html - 当元素的位置是绝对的/固定的时,为什么元素不在 body 内部?

标签 html css css-position

<分区>

我将 body 位置设置为 relative,然后尝试定位 #first#second 元素相对于它们的父元素,即 body

我的问题是,当 #first 元素的位置是绝对/固定时,为什么它们不在 body 内?

body {
  margin: 0;
  padding: 0;
  border: solid red;
  position: relative;
}

#first {
  position: fixed;
  left: 0;
  top: 200px;
  border: solid green;
}

#second {
  border: solid blue;
  height: 200px;
  padding: 100px;
  position: absolute;
}
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title></title>
</head>

<body>
  <section id="first"></section>
  <section id="second"> </section>
</body>

</html>

最佳答案

我想我明白问题是什么了。上面的评论是正确的,因为如果添加高度和宽度,则更容易看到元素。

另一件需要考虑的事情是设置元素位置时创建的 z-index 上下文。

在不设置 z-index 的情况下,第一个元素在主体内部,但在第二个元素之后。查看下面的链接。

https://jsfiddle.net/rollinglex/s1Ltf93n/2/

body {
  margin: 0;
  padding: 0;
  border: 1px solid red;
  position: relative;
  height: 80%;
  background-color: yellow;
  z-index: 1;
  }

          #first {
            position: absolute;
            left: 0;
            top: 200px;
            height: 50px;
            width: 50px;
            border: 1px solid green;
            background-color: green;
            z-index: 100;
          }

          #second {
            background-color: blue;
            border: 1px solid blue;
            height: 200px;
            padding: 100px;
            position: absolute;
            z-index: 10;
          }

希望这对您有所帮助!

关于html - 当元素的位置是绝对的/固定的时,为什么元素不在 body 内部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52595669/

上一篇:javascript - 页面重新加载后固定导航的问题

下一篇:javascript - 使用 jquery 切换 CSS 属性并为其设置动画

相关文章:

python - Django 如何在 Amazon S3 中存储 HTML 文件

html - 无法使滚动条消失 - 不知道如何正确使用 CSS

css - 在不同分辨率下保持绝对定位元素在相同位置

html - html 旁边不需要的白色区域

html - 覆盖内联样式

图像中的 CSS 不透明度

html - Css 内容被截断

html - 缩放期间在背景图像之后保留文本

html - 仅当元素包含剪辑文本时才设置样式

php - 如何中心对齐来自数据库的 'n' 图像数量