0

I set the body position to relative, then I'm trying to position #first and #second elements relative to their parents, i.e. the body.

My question is why the #first element is not inside of the body when their positions are absolute/fixed?

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>
Alireza
  • 2,319
  • 2
  • 23
  • 35

1 Answers1

-1

I think I see what the issue is. The above comment is correct in that it is easier to see the elements if you add a height and width.

Another thing to consider is the z-index context that is created when you set element positions.

Without setting the z-index, the first element is inside the body, but is behind the second element. Check out the link below.

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;
          }

Hope this helps!

Meeses
  • 144
  • 1
  • 1
  • 6
  • The question has nothing to do with `z-index`, it just works as it is suppose to, so this answer doesn't add or help in any way. – Asons Oct 01 '18 at 17:49
  • Sorry, I had posted the wrong jsfiddle link. In the question, the asker is wondering why the first element is not inside the body element. Obviously, it is. But when the first element is given height and width, it is hidden behind the second element. That may be why the element is not being seen by the asker. So increasing the z-index value of the first element will clearly show that it is in the body. Checkout the fiddle I updated and remove the z-index of the first element to see it disappear. – Meeses Oct 03 '18 at 14:20