7

update: I know adding a position: relative; to body will make the element be at body's bottom, I just didn't find the description of when not found the non-static parent, what the position would be related to. So I don't think this question is duplicated to this one. Thanks to @Ben Kolya Mansley

====

I am writing a component, and met a problem. I set an element position absolute and bottom 0, and append it to document.body (the body height is more than a screen's height), but it is not at body's bottom but viewport's bottom. Why is it so wired?

I read the mdn of position and bottom. It says element with position absolute will look for a non-static positioned parent, if not found, it will be relative to body.

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>Page Title</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
  </head>
  <body>
    <style>
      html, body {
        margin: 0;
        padding: 0;
      }
      body {
        height: 1500px;
      }
      .bar {
        position: absolute;
        bottom: 0;
      }
    </style>
    <div class="bar">this is bar</div>
  </body>
</html>
JerryYu
  • 379
  • 3
  • 16
  • you should really place your ` – treyBake Dec 19 '18 at 16:59
  • 1
    Because the body needs `position:relative` as the default is `position:static`. The `body` doesn't count as a parent. – Paulie_D Dec 19 '18 at 17:00

1 Answers1

8

From MDN's documentation on absolute positioning:

The absolutely positioned element is positioned relative to its nearest positioned ancestor (i.e., the nearest ancestor that is not static). If a positioned ancestor doesn't exist, it is positioned relative to the ICB (initial containing block), which the containing block of the document's root element.

This describes that it's not the body that it is positioned to, but the initial containing block, which has the dimensions of the viewport, not the body.

By adding position: relative; to body, the element will be aligned to the bottom.

More info on the Initial Containing Block can be found at the W3 specification

Ben Kolya Mansley
  • 1,768
  • 16
  • 24