CSS position: playground and demos

Back to the article

Every demo uses plain CSS and a few lines of vanilla JavaScript to switch classes. Open your browser's dev tools on any box to see the computed styles.

1. Playground

The frame below is its own small page, so fixed and sticky behave as they would on a real site. Scroll inside it.


    

2. Which box does absolute use?

The orange box has position: absolute; top: 0; right: 0. It goes to the corner of its nearest positioned ancestor. With none, it uses the page itself and lands in the top-right corner of this document.

.grandparent
.parent
.box

The box is a child of .parent in the HTML in every mode. Only the ancestors' position changes.

.box { position: absolute; top: 0; right: 0; }
.parent { position: relative; }  /* the box's containing block */

3. Why sticky doesn't stick

Scroll the box. The dark header has position: sticky; top: 0 in every case except "No top value".

Section header

Item 1

Item 2

Item 3

Item 4

Item 5

Item 6

Item 7

Item 8

Item 9

Item 10

Item 11

Item 12

Item 13

Item 14

.header { position: sticky; top: 0; }

4. When fixed isn't fixed

The "Chat" button has position: fixed; right: 16px; bottom: 16px and sits inside the card in the HTML. On a plain card it goes to the corner of your browser window. If the card has any of the other properties, the card becomes its containing block and the button gets stuck inside it.

.card
.chat { position: fixed; right: 16px; bottom: 16px; }
.card { transform: translateZ(0); }  /* any transform, filter, will-change: transform or contain: paint traps it */

5. z-index: 9999 that loses to z-index: 1

The menu has z-index: 9999. Card B has position: relative; z-index: 1. Whether the menu covers card B depends on card A, not on the menu.

card A
  • Edit
  • Duplicate
  • Move to folder
  • Delete
card B (position: relative; z-index: 1)
.menu { position: absolute; z-index: 9999; }  /* card A makes no stacking context: 9999 competes with card B's 1 */

6. Four real patterns

Badge on a card

NewStudio plan
Badge: absolute, card: relative

Tooltip

Copies the link

Sticky header

Site header

Scroll this box.

The header stays at the top of it.

It needs top: 0.

And no overflow: hidden between it and the scroller.

More text.

More text.

End.

/* Badge on a card */
.card { position: relative; }
.badge { position: absolute; top: -10px; right: -10px; }

/* Tooltip */
.tip { position: relative; }
.tip [role=tooltip] { position: absolute; bottom: calc(100% + 8px); left: 50%; transform: translateX(-50%); }

/* Sticky header */
header { position: sticky; top: 0; }

/* Modal overlay */
.overlay { position: fixed; inset: 0; }
.modal { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }