Skip to content

Lesson 18 of 52Layout

Positioning

Move elements out of the normal flow with relative, absolute, fixed and sticky positioning, and control what sits on top with z-index.

17 min read0/4 questions

Flexbox and Grid decide where things go by arranging boxes next to each other. Sometimes you need something to break out of that arrangement: a "New" badge pinned to the corner of a card, a header that stays at the top while you scroll, a dialog that floats above the whole page. That is the job of the position property. It is small, with only five values, but it is behind a huge number of everyday interface details. It is also behind some of the most confusing CSS bugs, usually involving z-index, so this lesson covers how the layering really works.

Normal flow first

By default, every element is laid out in normal flow. Block elements stack top to bottom, inline elements sit side by side in lines of text, and each box takes up space that pushes the next one along. Flexbox and Grid are variations on that idea: the boxes still take up space and still affect each other.

The position property decides whether an element stays in that flow, and whether you can nudge it with the offset properties top, right, bottom and left. There is also a shorthand, inset, that sets all four at once: inset: 0 means top, right, bottom and left are all 0.

ValueStays in flow?Offsets measured fromTypical use
staticYesOffsets ignoredThe default for every element
relativeYesIts own normal positionSmall nudges, anchor for absolute children
absoluteNoNearest positioned ancestorBadges, icons, dropdown menus
fixedNoThe viewport (browser window)Chat buttons, full-screen overlays
stickyYes, until it sticksIts scroll containerHeaders, table headings

static and relative

static is the default. A static element sits in the flow and ignores top, left and friends. You rarely write it, except to undo another rule.

relative keeps the element in the flow, so it still takes up its original space. Offsets then shift it visually from where it would have been. top: 10px moves it down 10px (away from the top), and left: 10px moves it right. The space it left behind stays empty; neighbours do not move to fill it.

Honestly, you will rarely nudge things with relative. Its real job is the next section: being an anchor for absolutely positioned children.

absolute: the badge on a card

An absolute element is taken out of the flow. It no longer takes up space, and the boxes around it act as if it were not there. Its offsets are measured from its containing block: the nearest ancestor that has a position other than static. If no ancestor qualifies, it uses the initial containing block, which is roughly the first screen of the page.

This is why you so often see this pair:

.card  { position: relative; }  /* becomes the anchor */
.badge { position: absolute; top: 8px; right: 8px; }

The card stays exactly where it was, but now any absolute child measures from the card's corners instead of the page's.

HTML & CSS
<style> .card { position: relative; width: 220px; padding: 16px; margin: 24px; border: 2px solid #222; border-radius: 10px; background: #fffaf0; } .badge { position: absolute; top: -10px; right: -10px; padding: 4px 10px; background: #d62828; color: white; font-size: 13px; font-weight: bold; border-radius: 999px; }</style><div class="card"> <span class="badge">New</span> <h3>Garden planner</h3> <p>Plan your beds and get reminders.</p></div>

Preview

Try deleting position: relative; from .card. The badge jumps to the top right corner of the whole preview, because it now measures from the page. Put it back, then change right: -10px to left: -10px to move the badge to the other corner.

Quick check
A span has position: absolute; top: 0; left: 0;. Its parent is static, but its grandparent has position: relative. Where does the span end up?
Need a nudge? A hint rules out a wrong answer.

You can also size an absolute element with its offsets. position: absolute; inset: 0; stretches it to cover its containing block exactly, which is perfect for a dark overlay on top of an image.

fixed: pinned to the screen

fixed is like absolute, but the containing block is the viewport: the visible area of the browser window. A fixed element stays in the same place on the screen while the page scrolls underneath. Chat buttons in the bottom right corner and cookie banners are usually fixed.

One trap: if any ancestor has a transform, filter or perspective, that ancestor becomes the containing block instead, and your "fixed" element scrolls with it. If a fixed element mysteriously moves, check its ancestors for a transform.

sticky: in flow until it sticks

sticky is a hybrid. The element behaves like a normal element in the flow until you scroll it to a threshold you set, then it sticks there like a fixed element, but only while its parent is still on screen. You must give it a threshold, usually top: 0. Without one, sticky does nothing.

HTML & CSS
<style> .scroller { height: 240px; overflow: auto; border: 2px solid #333; } .scroller h4 { position: sticky; top: 0; margin: 0; padding: 6px 10px; background: #1d3557; color: white; } .scroller p { margin: 0; padding: 6px 10px; border-bottom: 1px solid #ddd; }</style><div class="scroller"> <h4>A</h4> <p>Aisha</p><p>Alex</p><p>Amira</p><p>Anton</p> <h4>B</h4> <p>Bea</p><p>Ben</p><p>Bilal</p><p>Bruno</p> <h4>C</h4> <p>Cara</p><p>Chen</p><p>Chloe</p><p>Cyrus</p></div>

Preview

Scroll the contact list. Each letter sticks to the top until the next letter pushes it away. Change top: 0 to top: 20px and see where they stick now. Then delete the top line completely and notice the headings scroll away like normal text.

Sticky sticks within its scroll container: the nearest ancestor that scrolls. A frequent bug is a parent with overflow: hidden, which quietly becomes the scroll container, so the sticky element never has anything to stick to. If sticky does not work, look for overflow on the ancestors first.

Match the pairs0/5 matched

Match each interface detail to the position value you would usually use.

Choose an item, then its match on the other side.

z-index: who sits on top

When positioned boxes overlap, the browser has to decide which one is drawn in front. By default, later elements in the HTML paint over earlier ones. z-index overrides that. Higher numbers come forward, lower numbers go back, and negative numbers are allowed.

Two rules catch almost everyone:

  1. z-index only works on positioned elements (anything but static) and on flex or grid items. On a plain static block it does nothing.
  2. z-index values are only compared within the same stacking context.

Stacking contexts

A stacking context is a group of elements that are layered together as one unit. Inside the group, children are ordered by their own z-index. But the whole group is then placed in its parent's stack as a single layer. A child can never escape its group, however large its z-index.

Things that create a new stacking context include:

  • position: relative or absolute with a z-index other than auto
  • position: fixed or sticky (always)
  • opacity less than 1
  • transform, filter and a few other visual effects
  • isolation: isolate, which exists purely to create one
One page, layered front to back
  1. Modal dialoginside the overlay context
  2. Overlayposition: fixed; z-index: 100
  3. Sticky headerposition: sticky; z-index: 10
  4. Card with badgebadge is absolute inside the card
  5. Page contentnormal flow, z-index: auto

Normal flow content is painted first, at the back.

1/5

Here is the classic bug. The dropdown has z-index: 999, yet it hides behind the banner, because its parent created a stacking context at level 1.

HTML & CSS
<style> .nav { position: relative; z-index: 1; background: #e9ecef; padding: 10px; } .menu { position: absolute; top: 30px; left: 10px; z-index: 999; width: 160px; padding: 10px; background: #ffd166; border: 2px solid #333; } .banner { position: relative; z-index: 2; margin-top: 10px; padding: 30px 10px; background: #118ab2; color: white; }</style><div class="nav"> Menu <div class="menu">Profile<br>Settings<br>Log out</div></div><div class="banner">Spring sale banner</div>

Preview

Fix it in one of two ways. Change the .nav z-index to 3 so the whole nav group sits above the banner. Or delete z-index: 1 from .nav; it then no longer forms a stacking context, and the menu's 999 is compared against the banner directly.

Quick check
An element has z-index: 50 but still appears behind a sibling with no z-index. The element is position: static. What is the fix?
Need a nudge? A hint rules out a wrong answer.

A modal overlay

A modal combines everything: a fixed overlay covering the screen with inset: 0, a high z-index, and the dialog centred inside it. For a real site, the HTML dialog element with showModal() handles focus and the Escape key for you and draws in the browser's top layer, above every z-index. Still, knowing how to build the overlay explains what it is doing.

HTML & CSS
<style> .overlay { position: fixed; inset: 0; z-index: 100; display: grid; place-items: center; background: rgb(0 0 0 / 0.5); } .overlay[hidden] { display: none; } .dialog { background: white; padding: 20px; border-radius: 10px; width: 220px; }</style><p>Some page content behind the overlay.</p><button id="open">Open dialog</button><div class="overlay" id="overlay" hidden> <div class="dialog"> <p>Delete this photo?</p> <button id="close">Cancel</button> </div></div><script> const overlay = document.getElementById("overlay"); document.getElementById("open").onclick = () => (overlay.hidden = false); document.getElementById("close").onclick = () => (overlay.hidden = true);</script>

Preview

Open the dialog, then change inset: 0 to inset: 40px to see the overlay shrink away from the edges. Change the last number in the background colour from 0.5 to 0.9 to make it darker.

Put it in order4 steps

Put the steps for adding a corner badge to a card in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Key terms
normal flow
The default layout where boxes take up space and push each other along.
offset properties
top, right, bottom, left and the inset shorthand, used to move positioned elements.
containing block
The box an absolute or fixed element measures its offsets from.
viewport
The visible area of the browser window.
z-index
A number that orders overlapping positioned elements within one stacking context.
stacking context
A group of elements layered together as a single unit in its parent's stack.