当元素的位置绝对/固定时,为什么元素不在体内?

时间:2018-10-01 17:01:48

标签: html css css-position

我将body的位置设置为relative,然后我尝试相对于其父元素#first定位#secondbody元素。

我的问题是,当#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>
{{1}}

1 个答案:

答案 0 :(得分:-1)

我想我明白了问题所在。上面的注释是正确的,因为如果添加高度和宽度,则更容易查看元素。

要考虑的另一件事是设置元素位置时创建的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;
          }

希望这会有所帮助!