Sven
Sven

Reputation: 13296

CSS Positioning: Fixed and relative interchangeable regarding absolute?

With regards to absolute positioning, fixed seems to work like relative.

.fixed, .relative {
  border: 1px solid;
  width: 150px;
  height: 150px;
}

.fixed {
  border-color: red;
  position: fixed;
}

.relative {
  border-color: blue;
  margin-left: 200px;
  position: relative;
}

.absolute {
  background-color: rgba(0, 0, 0, 0.2);
  position: absolute;
}

.a {
  top: 0;
  left: 0;
}

.b {
  bottom: 0;
  right: 0;
}
<div class="fixed">
  <span class="absolute a">Left Top</span>
  <span class="absolute b">Right Bottom</span>
</div>

<div class="relative">
  <span class="absolute a">Left Top</span>
  <span class="absolute b">Right Bottom</span>
</div>

Unfortunately, I don't understand why. I expect this to be defined somewhere, but I was only able to find resources discussing absolute and relative, not absolute and fixed.

This leads the to the question: Is it even true that, in regards to absolute position, I can treat fixed and relative elements the same, being able to use top/left/right/bottom to control offset amount to parent?

Upvotes: 2

Views: 45

Answers (1)

semuzaboi
semuzaboi

Reputation: 5172

I reckon anything other than position:static sets off a new parent context for the positioned children.

This can be verified in the MDN docs for Absolute Positioning

The absolutely positioned element is positioned relative to its nearest positioned ancestor (i.e., the nearest ancestor that is not static).

So setting position:fixed does cause absolute child elements to follow the new context.

This can be seen it the fiddle here . Changing the position of the .rel div moves the set of red divs , but the absolutely positioned blue div moves with it.

Another good source is the w3.org which says

An essential concept when it comes to absolute positioning is the containing block: the block box that the position and dimensions of the absolutely positioned box are relative to. For static boxes and relatively positioned boxes the containing block is the nearest block-level ancestor—the parent element in other words. For absolutely positioned elements however it’s a little more complicated. In this case the containing block is the nearest positioned ancestor. By “positioned” I mean an element whose position property is set to relative, absolute or fixed—in other words, anything except normal static elements.

Sources : MDN Positon , w3org absolute position

Upvotes: 1

Related Questions