2

Is there any documentation that specifies what the default behaviour is for an element with position fixed, inside an element with position relative, absolute or static?

.parent {
  position: relative;  /* or absolute/static */
  height: 200px;
  width: 200px;
  top: 30px;
  left: 50px;
  background-color: red;
}

.child {
  position: fixed;
  height: 100px;
  width: 100px;
  left: 10px;
  top: 20px;
  background-color: blue;
}
<div class='parent'>
  <div class='child'></div>
</div>

My own experiance is that it is positioned relative to the browser viewport (unless transform is used, or left/top is omitted in child), but how can i justify that this should always will be the case? How do i know if any browsers renders this differently? Perhaps positioning the child relative to the parent, or maybe not showing the element at all...

Temani Afif
  • 245,468
  • 26
  • 309
  • 415
johann1301s
  • 343
  • 4
  • 19

1 Answers1

2

The position of the parent element or any ancestor is irrelevant when it comes to position:fixed. From the specification:

Fixed positioning is a subcategory of absolute positioning. The only difference is that for a fixed positioned box, the containing block is established by the viewport.

But there is some special cases where the containing block can change. It happens when using filter like I explained here, transform like explained here and sometimes will-change (explained here)


Concerning the use of top/left/bottom/right you need to consider the static position. If you don't set any of those values the browser will consider the static position to place the element. Still From the specification:

For the purposes of this section and the next, the term "static position" (of an element) refers, roughly, to the position an element would have had in the normal flow. More precisely ...

A position:fixed element always consider the viewport as its containing block (the reference for its placement) unless there is some particular properties used in a upper level (transform, filter, etc). The position of that element is either defined by top/left/right/bottom or by the static position like described in the specification.

Related question to get more details about the static position: Why aren't my absolutely-positioned elements located where I expect?

Temani Afif
  • 245,468
  • 26
  • 309
  • 415