Topic 05 / 14

Display & Positioning

~10 min read  //  CSS Series  //  Coding India

display — the Most Important Property

display: block;         /* full width, stacks vertically — div, p, h1 */
display: inline;        /* flows in text, width/height ignored — span, a */
display: inline-block;  /* flows in text BUT accepts width/height */
display: none;          /* gone — removed from layout entirely */
display: flex;          /* flex container (own topic next) */
display: grid;          /* grid container (own topic) */

display: none removes the element; visibility: hidden hides it but keeps its space; opacity: 0 keeps space and clickability. Three different tools.

position

static — the default; the element sits in normal flow, offsets ignored.

relative — stays in flow, but can be nudged; crucially, it becomes the anchor for absolute children:

.card { position: relative; }

absolute — removed from flow, positioned against the nearest non-static ancestor:

.badge {
  position: absolute;
  top: 12px;
  right: 12px;        /* pinned to the card's corner */
}

This relative-parent / absolute-child pair is the pattern: badges on cards, icons inside inputs, close buttons on modals.

fixed — pinned to the viewport; ignores scrolling:

.navbar {
  position: fixed;
  top: 0; left: 0; right: 0;
}
/* remember to offset page content by the navbar height! */

sticky — the hybrid: scrolls normally until it hits the offset, then sticks:

.section-header {
  position: sticky;
  top: 0;             /* sticks when it reaches the viewport top */
}

Sticky fails silently if any ancestor has overflow: hidden — the #1 sticky bug.

Centering an Absolute Element

.modal {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);   /* classic perfect centering */
}

(For normal flow, flexbox centering is simpler — next topic.)

z-index & Stacking

Positioned elements can overlap; z-index decides who’s on top:

.dropdown { z-index: 10; }
.modal    { z-index: 100; }
.toast    { z-index: 1000; }

Two rules save hours of debugging: z-index only works on positioned (non-static) elements, and a child can never escape its parent’s stacking context — if a parent has z-index: 1 and an opacity or transform, children compete inside it no matter how high their z-index. Keep a documented scale (10/100/1000) instead of z-index: 999999 wars.