Chapter 16 of 33

Positioning

So far, every element we styled has been placed by the browser in normal flow: block boxes stack one below the other, inline content flows left to right in lines (you saw this in The Display Property). Normal flow is great for text, but real interfaces need more: a "NEW" badge stuck to the corner of a product card, a header that stays at the top while you scroll, a tooltip floating above a button, a "Back to top" button glued to the bottom-right of the screen.

The position property lets you take control of where a box goes. In this chapter we learn its five values — static, relative, absolute, fixed and sticky — the offset properties top, right, bottom, left and inset, and the single most important idea behind them: the containing block.


What is Positioning?

The position property chooses the positioning scheme for an element: whether it stays in normal flow, is shifted from its normal place, or is removed from the flow and placed relative to some reference box. The offset properties (top, right, bottom, left) then say how far to move it.

Every positioning question really has two parts:

  1. Does the element still take up its space in the flow? (Do other elements act as if it is there?)

  2. What are the offsets measured from? (Its own normal position? A parent? The browser window?)

Keep these two questions in mind — each value of position answers them differently.

ValueKeeps its space in the flow?Offsets measured from
static (default)YesOffsets are ignored
relativeYesIts own normal position
absoluteNoNearest positioned ancestor (its containing block)
fixedNoThe viewport (browser window)
stickyYesActs like relative until a scroll threshold, then "sticks" inside its scroll container

An element whose position is anything other than static is called a positioned element. That term will matter a lot in a moment.


1. position: static (The Default)

Every element starts as position: static. It sits in normal flow, and the offset properties have no effect:

.box {
  position: static;
  top: 50px;   /* ignored! */
  left: 50px;  /* ignored! */
}

You rarely write static yourself. It is mostly used to reset an element that was positioned by another rule, for example inside a media query.

A very common beginner bug is writing top: 20px on an element and wondering why nothing moves. The reason: the element is still static.


2. position: relative

A relatively positioned element is laid out in normal flow first. Then it is shifted visually by the offsets — but the space it originally occupied is kept, as if it had never moved.

<div class="box">Box 1</div>
<div class="box shifted">Box 2</div>
<div class="box">Box 3</div>
.box {
  width: 100px;
  height: 30px;
  background: lightblue;
}

.shifted {
  position: relative;
  top: 20px;   /* move DOWN by 20px (away from the top edge) */
  left: 30px;  /* move RIGHT by 30px (away from the left edge) */
  background: orange;
}

Result:

┌────────┐
│ Box 1  │
└────────┘
┌ ─ ─ ─ ─┐                ← the empty "ghost" space Box 2 still owns
   ┌────────┐
└ ─│ Box 2  │             ← drawn 20px lower and 30px to the right
   └────────┘
┌────────┐                ← Box 3 did NOT move up; it still sees
│ Box 3  │                   Box 2 in its original spot
└────────┘

Notice that Box 2 now overlaps Box 3. Relative positioning never pushes other elements around.

How to read the offsets

This confuses many students: top: 20px does not mean "go up". It means "push the box's top edge 20px away from where its top edge would be" — so the box moves down. Likewise:

OffsetPositive value moves the boxNegative value moves the box
top: 20pxDownUp
bottom: 20pxUpDown
left: 20pxRightLeft
right: 20pxLeftRight

If you set both top and bottom on a relative element, top wins (and left wins over right in a left-to-right page).

Why relative is so useful

Shifting boxes by a few pixels is actually the less common use. The main reason developers write position: relative is to make an element a positioned ancestor — a reference frame for absolutely positioned children. That is the next section.


3. position: absolute

An absolutely positioned element is removed from normal flow. Other elements behave as if it does not exist — no space is reserved for it. Then it is placed using the offsets, measured from its containing block.

The containing block

For an absolutely positioned element, the containing block is formed by the nearest ancestor that is positioned (its position is not static). The offsets are measured from that ancestor's padding box — the area inside its border. If no ancestor is positioned, the initial containing block (a rectangle the size of the viewport, anchored at the top of the document) is used.

In practice, "positioned ancestor" usually means "the parent I gave position: relative". That is the famous relative parent, absolute child pattern.

Worked example: a badge on a card

<div class="card">
  <span class="badge">NEW</span>
  <h3>Wireless Mouse</h3>
  <p>₹799</p>
</div>
.card {
  position: relative;      /* becomes the containing block */
  width: 220px;
  padding: 16px;
  border: 1px solid #ccc;
  border-radius: 8px;
}

.badge {
  position: absolute;
  top: -10px;              /* 10px above the card's inner top edge */
  right: -10px;            /* 10px past the card's inner right edge */
  background: crimson;
  color: white;
  padding: 2px 8px;
  border-radius: 999px;
  font-size: 12px;
}

The red "NEW" pill sits on the card's top-right corner, half hanging outside it. The heading and price are not pushed down at all, because the badge takes up no space in the flow.

Now delete position: relative from .card. The badge flies away to the top-right corner of the page, because there is no positioned ancestor left and the initial containing block is used. If your absolutely positioned element appears in a strange place, the first thing to check is: which ancestor is positioned?

Exact measurement: padding edge, not border edge

Let's prove where top: 0; left: 0 lands.

.parent {
  position: relative;
  border: 5px solid black;
  padding: 20px;
  width: 300px;
  height: 100px;
  margin: 10px;
}

.child {
  position: absolute;
  top: 0;
  left: 0;
  width: 50px;
  height: 50px;
  background: red;
}

Measured in Chrome (with body { margin: 0 }):

parent's outer border edge starts at  x = 10,  y = 10
child starts at                       x = 15,  y = 15

The child is 5px inside the parent — exactly the border width. So the offsets are measured from the padding edge (the inner edge of the border). The parent's 20px padding does not push the child in. If you want the child to respect the padding, use top: 20px; left: 20px.

Absolute elements size themselves differently

Two things change when an element becomes absolute:

  • It becomes block-level. A <span> with position: absolute computes to display: block, so width, height and vertical margins now work on it.

  • Its width shrinks to fit its content (instead of filling the whole line like a normal block). In our test, an absolute <span> containing "Hi there" was only about 52px wide (default 16px serif font).

You can make it stretch by giving both opposite offsets:

.overlay {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;            /* stretches to cover the whole containing block */
  background: rgb(0 0 0 / 0.5);
}

With left: 0; right: 0 and no width, the element is exactly as wide as the containing block's padding box (400px inside a 400px-wide parent in our test).

Percentages in offsets

top and bottom percentages refer to the containing block's height; left and right percentages refer to its width. Inside a 400px × 200px positioned parent, top: 50%; left: 25% places the child's top-left corner 100px from the left and 100px from the top.


The inset Shorthand

Writing four offsets is tedious, so modern CSS has inset, a shorthand that works like margin (top, right, bottom, left):

.overlay {
  position: absolute;
  inset: 0;                 /* same as top: 0; right: 0; bottom: 0; left: 0 */
}

.panel {
  position: absolute;
  inset: 10px 20px;         /* top/bottom 10px, left/right 20px */
}

inset is supported in all modern browsers. There are also logical versions such as inset-inline-start and inset-block, which we will meet in Modern CSS: :has(), Nesting, clamp() & Logical Properties.


Centering with Absolute Positioning

Two classic techniques for centering a box inside a positioned parent. Both are popular interview questions.

Technique 1: 50% + translate

.parent {
  position: relative;
  height: 300px;
}

.centered {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

Why it works: top: 50%; left: 50% puts the box's top-left corner at the centre of the parent, so the box hangs down and to the right. translate(-50%, -50%) then moves it back by half of its own width and height (percentages in translate refer to the element itself). The result is perfectly centred, even if you don't know the box's size. (Transforms are covered fully in Transforms.)

After top/left 50%:              After translate(-50%, -50%):
┌─────────────────────┐          ┌─────────────────────┐
│                     │          │                     │
│          ●──────┐   │          │      ┌──────┐       │
│          │ box  │   │          │      │ box● │       │
│          └──────┘   │          │      └──────┘       │
│                     │          │                     │
└─────────────────────┘          └─────────────────────┘
 ● = parent's centre

Technique 2: inset: 0 + margin: auto

.centered {
  position: absolute;
  inset: 0;
  width: 200px;
  height: 100px;
  margin: auto;
}

The box is told to stretch to all four edges, but it also has a fixed width and height. The leftover space is shared by the auto margins equally on all sides, so it lands in the middle. This one needs a known size (or a size that is smaller than the parent).

For everyday layout, Flexbox and Grid centre things more simply — see Flexbox — but these techniques are still the right tool for overlays, modals and icons on top of images.


4. position: fixed

A fixed element is removed from the flow like an absolute one, but its offsets are measured from the viewport (the visible browser window). It does not move when the page scrolls.

.back-to-top {
  position: fixed;
  right: 20px;
  bottom: 20px;
  padding: 10px 14px;
  background: #222;
  color: white;
  border-radius: 50%;
}

The button stays 20px from the bottom-right corner of the screen no matter how far you scroll. Typical uses: chat widgets, cookie banners, "Back to top" buttons, fixed navigation bars.

The fixed header problem

.site-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;           /* full width */
  height: 60px;
  background: white;
}

Because the header is out of the flow, the page content slides up underneath it and the first 60px of your content is hidden. The usual fix is to give the body (or main content) a padding-top: 60px equal to the header's height — or use sticky instead (next section).

A surprising trap: transform on an ancestor

If any ancestor has a transform (or filter, perspective, contain: paint, will-change: transform and a few similar properties), that ancestor becomes the containing block for its fixed descendants. The "fixed" element then behaves like an absolute one inside that ancestor and scrolls with it. In our Chrome test, a fixed child with top: 0; left: 0 inside a parent with transform: translateX(0) landed at the parent's corner, not the window's. This is why modals are often placed directly under <body>.


5. position: sticky

Sticky is a hybrid. The element stays in normal flow (keeping its space) like a relative element, until scrolling would move it past a threshold you set. Then it sticks at that threshold — like fixed — but only while its parent is still on screen.

.section-title {
  position: sticky;
  top: 0;               /* REQUIRED: the threshold to stick at */
  background: teal;     /* so content scrolling under it is hidden */
  color: white;
}
Before scrolling:            After scrolling down a bit:
┌───────────────────┐        ┌───────────────────┐
│ Intro text        │        │▓ Section title ▓▓▓│ ← stuck at top: 0
│▓ Section title ▓▓▓│        │ line 3            │
│ line 1            │        │ line 4            │
│ line 2            │        │ line 5            │
└───────────────────┘        └───────────────────┘

When the end of the parent element scrolls up, the sticky element is carried away with it. That is how alphabet headings in a contact list ("A", "B", "C"…) push each other off the top.

Why sticky "doesn't work" — the checklist

  1. No threshold. You must set at least one of top, bottom, left, right. Without it, sticky behaves like relative.

  2. An ancestor has overflow: hidden, auto or scroll. The element sticks inside the nearest scrolling ancestor. If a wrapper has overflow: hidden, that wrapper becomes the scroll container — and since it doesn't actually scroll, nothing appears to stick.

  3. The parent is too short. The element can only stick within its parent's box. If the parent is just as tall as the sticky element, there is no room to stick.

  4. In a flex or grid container, a sticky item may be stretched to the full height of the container, leaving no room to move. Add align-self: flex-start (or start) to it.


A Complete Example

Paste this into an HTML file and scroll to see all five values together.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Positioning Demo</title>
  <style>
    body {
      margin: 0;
      font-family: sans-serif;
    }

    header {
      position: sticky;
      top: 0;
      background: #1e3a8a;
      color: white;
      padding: 12px 16px;
    }

    .gallery {
      display: flex;
      gap: 16px;
      padding: 16px;
    }

    .photo {
      position: relative;          /* containing block for the caption */
      width: 200px;
      height: 140px;
      background: linear-gradient(135deg, #93c5fd, #1d4ed8);
    }

    .caption {
      position: absolute;
      left: 0;
      right: 0;
      bottom: 0;
      background: rgb(0 0 0 / 0.6);
      color: white;
      padding: 4px 8px;
    }

    .nudge {
      position: relative;
      top: -4px;                   /* small visual tweak */
    }

    .long {
      height: 1500px;
      padding: 16px;
    }

    .back-to-top {
      position: fixed;
      right: 20px;
      bottom: 20px;
      background: crimson;
      color: white;
      padding: 10px 14px;
      border-radius: 8px;
      text-decoration: none;
    }
  </style>
</head>
<body>
  <header>My Photos <span class="nudge">📷</span></header>

  <div class="gallery">
    <div class="photo"><div class="caption">Goa beach</div></div>
    <div class="photo"><div class="caption">Manali snow</div></div>
  </div>

  <div class="long">Scroll down… the header sticks and the button stays put.</div>

  <a class="back-to-top" href="#">↑ Top</a>
</body>
</html>

What you will see:

  • The dark blue header stays glued to the top of the window as you scroll (sticky, with body as its parent, so it sticks for the whole page).

  • Each caption bar sits across the bottom of its photo (absolute inside a relative parent, stretched by left: 0; right: 0).

  • The red "↑ Top" button never moves from the bottom-right corner (fixed).

When boxes overlap like this, which one is drawn on top? That is controlled by z-index, the subject of the next chapter, z-index & Stacking Context.


Comparison Table

Featurestaticrelativeabsolutefixedsticky
In normal flow?YesYesNoNoYes
Offsets work?NoYesYesYesYes (as thresholds)
Reference box—Own normal positionNearest positioned ancestorViewportNearest scrolling ancestor
Scrolls with page?YesYesYes (with its container)NoUntil it sticks
Becomes containing block for absolute children?NoYesYesYesYes
Typical useDefaultParent for absolute children, small nudgesBadges, tooltips, overlays, dropdownsChat buttons, fixed navbars, bannersSticky headers, table headings, sidebars

Common Mistakes

  • Using offsets on a static element. top: 10px does nothing until position is changed.

  • Forgetting position: relative on the parent. The absolute child then positions itself relative to some far-away ancestor or the page.

  • Using absolute positioning for whole page layouts. Absolute elements don't take up space, so content overlaps as soon as text length or screen size changes. Use Flexbox or Grid for layout and positioning for small decorations.

  • Thinking top moves an element up. A positive top moves it down.

  • Content hidden under a fixed header. Add padding equal to the header's height, or use sticky.

  • Sticky with no top, or inside an overflow: hidden wrapper.

  • Expecting the parent's padding to push an absolute child inward. Offsets start at the padding edge, so top: 0 touches the inside of the border.


Interview / Exam Questions

1. What is the difference between position: relative and position: absolute?

A relative element stays in normal flow and keeps its original space; offsets shift it visually from that original position. An absolute element is removed from the flow (no space is reserved) and is placed using offsets measured from its containing block — the padding box of the nearest positioned ancestor, or the initial containing block if there is none.

2. Why do we set position: relative on a parent when the child is absolute?

To make the parent a positioned element, so it becomes the containing block for the absolute child. Then the child's top/left etc. are measured from the parent instead of from the page.

3. What is the difference between fixed and sticky?

Fixed is removed from the flow and always positioned relative to the viewport, so it never scrolls. Sticky stays in the flow and scrolls normally until it reaches its threshold (for example top: 0) in its nearest scrolling ancestor; it then sticks, but only while its parent element is still visible.

4. A box has position: relative; top: 20px; left: -10px. Where does it go, and do its neighbours move?

It is drawn 20px lower and 10px to the left of its normal position. The neighbours do not move, because the element's original space in the flow is preserved; it may overlap them.

5. A parent is 400px wide and 200px tall with position: relative. Where is a child with position: absolute; top: 50%; left: 25%?

top percentages use the containing block's height and left percentages use its width, so the child's top-left corner is 100px from the top (50% of 200) and 100px from the left (25% of 400), measured from the parent's padding edge.

6. How do you centre an element of unknown size with absolute positioning?

position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); inside a positioned parent. The offsets put its top-left corner at the centre, and the translate moves it back by half of its own width and height.

7. A position: fixed element is scrolling with the page instead of staying put. What could cause this?

An ancestor has a property such as transform, filter, perspective, will-change: transform or contain: paint. Such an ancestor becomes the containing block for fixed descendants, so the element is positioned relative to that ancestor and scrolls with it.


Summary

  • position decides whether an element stays in the flow and what its offsets are measured from.

  • static is the default; offsets are ignored.

  • relative shifts the element visually but keeps its original space; it is mainly used to create a reference frame for absolute children.

  • absolute removes the element from the flow and positions it inside its containing block — the padding box of the nearest positioned ancestor.

  • fixed positions relative to the viewport and ignores scrolling (unless a transformed ancestor captures it).

  • sticky acts relative until a threshold, then sticks within its scroll container; it needs an offset and no clipping overflow ancestor.

  • inset is the shorthand for all four offsets; inset: 0 makes an overlay.

Positioned elements can overlap, so the next question is which one appears on top. That is answered in z-index & Stacking Context.