Rustem Kakimov
Rustem Kakimov

Reputation: 2671

Unexpected behaviour of position relative on body

So, let's say we have the following code:

body {
    margin: 0;
    /* position: relative; */
}

.container {
    width: 300px;
    height: 300px;
    margin: 100px;
    background: gray;
}

.absolute {
    width: 100px;
    height: 100px;
    background: red;
    position: absolute;
    top: 10px;
}
<div class="container">
    <div class="absolute"></div>
</div>

In this case the .absolute element is positioned relative to the body, as expected.

Not let's add position: relative to the body. The element is now positioned relative to the .container. Which doesn't make sense, as absolutely positioned element is positioned relative to nearest positioned ancestor (non-static) which is body in this case.

Is body positioning treated differently from other elements?

CODEPEN

Upvotes: 1

Views: 296

Answers (2)

sergdenisov
sergdenisov

Reputation: 8572

From the specification about absolute positioning:

The containing block for a positioned box is established by the nearest positioned ancestor (or, if none exists, the initial containing block, as in our example).

Ok, you have none nearest positioned ancestors, move along to the initial containing block:

The position and size of an element's box(es) are sometimes calculated relative to a certain rectangle, called the containing block of the element. The containing block of an element is defined as follows:

  1. The containing block in which the root element lives is a rectangle called the initial containing block. For continuous media, it has the dimensions of the viewport and is anchored at the canvas origin; it is the page area for paged media.

Good, and what is the root element in your case:

The html element represents the root of an HTML document.

It means that by default your the .absolute element is positioned not relative to the <body>, but to the <html>.

Upvotes: 1

Manuel Cheța
Manuel Cheța

Reputation: 500

In fact, if you do not specify the position: relative, then the elements will have a position of :static ( https://www.w3schools.com/cssref/pr_class_position.asp ). You actually need to insert position relative to the .container element if you want to place .absolute depending on the container element. This is why you have the strange behavior.

Upvotes: 0

Related Questions