I had an interesting problem where I set an image's CSS rules to display:fixed
and it still scrolled with the page. Here's what I discovered:
In CSS, display:fixed
means fixed with regard to the nearest ancestor stacking context, not necessarily to the page coordinates. You can reset the stacking context by adding a transform, will-change, or other attributes (list provided below) to an element. If an ancestor element resets the stacking context, any descendant of it with display:fixed
will stay fixed with regard to it, but if it scrolls with the page, will scroll too.
Ditto for the CSS attribute z-index
. A higher z-index
is only in front of objects in its stacking context. A new stacking context, lower down on the page, can contain elements with a lower z-index
but that nonetheless appear in front of it visually, because they're not in the same stacking context.
Josh Comeau's site has a good article on this at https://www.joshwcomeau.com/css/stacking-contexts/. MDN also has a comprehensive article at https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_positioned_layout/Stacking_context#the_stacking_context which gives the following as list of ways the CSS stacking context can be reset:
- Root element of the document (
<html>
). - Element with a
position
valueabsolute
orrelative
andz-index
value other thanauto
. - Element with a
position
valuefixed
orsticky
. - Element with a
container-type
valuesize
orinline-size
set (See container queries). - Element that is a flex item with a
z-index
value other thanauto
. - Element that is a grid item with
z-index
value other thanauto
. - Element with an
opacity
value less than1
. - Element with a
mix-blend-mode
value other thannormal
. - Element with any of the following properties with a value other than
none
: - Element with the
isolation
valueisolate
. - Element with a
will-change
value specifying any property that would create a stacking context on non-initial value. - Element with a
contain
value oflayout
orpaint
, or a composite value that includes either of these values (i.e.,contain: strict
,contain: content
). - Element placed into the top layer and its corresponding
::backdrop
. Examples include fullscreen and popover elements. - Element that has had stacking context-creating properties (such as
opacity
) animated using@keyframes
, withanimation-fill-mode
set toforwards
.