Episode 1 — Fundamentals / 1.8 — CSS Layout Mastery

1.8 — CSS Layout Mastery: Quick Revision

Compact cheat sheet. Print-friendly.

How to use this material (instructions)

  1. Skim top-to-bottom in one pass before interviews or exams.
  2. If a row feels fuzzy — reopen the matching lesson: README.md1.8.a1.8.g.
  3. Drills1.8-Exercise-Questions.md.
  4. Polished answers1.8-Interview-Questions.md.

1.8.a Flexbox

Axes

flex-direction: row         flex-direction: column

Main axis ───────►          Cross axis ───────►
┌───┐ ┌───┐ ┌───┐          ┌───┐
│ 1 │ │ 2 │ │ 3 │          │ 1 │  Main
└───┘ └───┘ └───┘          ├───┤  axis
      Cross axis │          │ 2 │   │
                 ▼          ├───┤   ▼
                            │ 3 │
                            └───┘

Container Properties

PropertyKey valuesControls
displayflex, inline-flexCreates flex context
flex-directionrow, column, row-reverse, column-reverseMain axis direction
flex-wrapnowrap, wrap, wrap-reverseWhether items wrap
justify-contentflex-start, center, flex-end, space-between, space-around, space-evenlyMain axis distribution
align-itemsstretch, flex-start, center, flex-end, baselineCross axis alignment (all items)
align-contentSame as justify-contentCross axis distribution (wrapped lines only)
gap<row> <col>Space between items

Item Properties

PropertyKey valuesControls
flex1, auto, none, <grow> <shrink> <basis>How item sizes
align-selfSame as align-itemsOverride cross-axis alignment
orderInteger (default 0)Visual order (not DOM order)

Flex Shorthand Decoded

ShorthandgrowshrinkbasisBehavior
flex: 1110%Equal share, ignores content
flex: auto11autoGrows from content size
flex: none00autoFixed at content size
flex: 0 1 auto01autoCSS default — won't grow, can shrink

1.8.b Common Layout Patterns

Navbar

.nav { display: flex; align-items: center; }
.nav .logo { margin-right: auto; }
.nav .actions { margin-left: auto; }

Centering (pick one)

/* Flex */  display: flex; justify-content: center; align-items: center;
/* Grid */  display: grid; place-items: center;
/* Block */ width: 600px; margin: 0 auto;  /* horizontal only */

Sticky Footer

body { display: grid; grid-template-rows: auto 1fr auto; min-height: 100vh; }
/* OR */
body { display: flex; flex-direction: column; min-height: 100vh; }
main { flex: 1; }

Responsive Card Grid (no media queries)

.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 24px; }

Fluid Container

.container { width: min(90%, 1200px); margin: 0 auto; }

1.8.c CSS Grid

Defining Tracks

FunctionExampleMeaning
Fixed200pxExactly 200px
fr1fr 2frFractions of remaining space (1:2)
repeat()repeat(3, 1fr)Three equal columns
minmax()minmax(200px, 1fr)At least 200px, at most 1fr
auto-fillrepeat(auto-fill, minmax(200px, 1fr))As many as fit, keeps empty tracks
auto-fitrepeat(auto-fit, minmax(200px, 1fr))As many as fit, collapses empty tracks

Placement

.item {
  grid-column: 1 / 3;      /* line 1 to line 3 */
  grid-column: 2 / span 3;  /* start at 2, span 3 */
  grid-column: 1 / -1;      /* full width */
  grid-row: 1 / 3;          /* span 2 rows */
}

Named Areas

.page {
  grid-template-areas:
    "header header"
    "sidebar main"
    "footer  footer";
}
.header  { grid-area: header; }
.sidebar { grid-area: sidebar; }

Implicit Grid

PropertyControls
grid-auto-rowsHeight of auto-created rows
grid-auto-columnsWidth of auto-created columns
grid-auto-flowrow (default), column, dense

auto-fill vs auto-fit

Fewer items than columns:
auto-fill: [Item][Item][    ][    ][    ]   ← keeps empty tracks
auto-fit:  [    Item    ][    Item    ]     ← collapses empty tracks

1.8.d Combining Grid and Flex

Decision Model

Page-level (2D)  →  Grid
Component (1D)   →  Flex
Both              →  Grid shell + Flex components

Typical Architecture

RegionLayout EngineWhy
Page shellGridRows + columns (header, sidebar, main, footer)
Header / navbarFlexSingle row of items
Card gridGrid2D responsive columns
Card internalsFlex (column)Stack content, push button to bottom
Footer columnsFlex (wrap) or GridMultiple columns of links

1.8.e Positioning

Comparison Table

ValueIn flow?Relative toStacking context?
staticYesN/ANo
relativeYesOwn positionWith z-index
absoluteNoPositioned ancestorWith z-index
fixedNoViewportAlways
stickyYesScroll thresholdAlways

Containing Block Lookup

Absolutely positioned → walk up DOM → first ancestor with position ≠ static (or transform/filter/perspective).

inset Shorthand

inset: 0;                /* top:0 right:0 bottom:0 left:0 — full cover */
inset: 10px 20px;        /* top/bottom: 10px, left/right: 20px */

Sticky Gotchas

  • Must set a threshold (top, bottom, etc.)
  • overflow: hidden/auto on ancestor breaks it
  • Unsticks at parent boundary

1.8.f Stacking Context

What Creates One

position + z-index · fixed / sticky · opacity < 1 · transform · filter · isolation: isolate · will-change · mix-blend-mode · flex/grid child + z-index

Paint Order (back → front)

  1. Background/borders of context root
  2. Negative z-index children
  3. Block-level elements
  4. Floated elements
  5. Inline elements
  6. z-index: 0 / auto positioned elements
  7. Positive z-index children (ascending)

Token-Based Z-Index System

:root {
  --z-base:     0;      --z-dropdown: 100;
  --z-sticky:   200;    --z-overlay:  300;
  --z-modal:    400;    --z-toast:    500;
  --z-tooltip:  600;
}

Key Rule

z-index only competes within the same stacking context — it is not global.


1.8.g Container Queries

Syntax

/* 1. Define container */
.wrapper { container-type: inline-size; container-name: card; }

/* 2. Query container */
@container card (min-width: 500px) {
  .content { flex-direction: row; }
}

Container Types

TypeQueriesUse
inline-sizeWidth onlyMost common
sizeWidth and heightRare
normalNoneDefault

Container Units

UnitRelative to
cqw1% container width
cqh1% container height
cqi1% inline size
cqb1% block size

Media Queries vs Container Queries

@media@container
Responds toViewportContainer element
Best forPage-level layoutReusable components
ScopeGlobalComponent-local

One-liner Definitions

TermOne-liner
Main axisThe primary direction of flex layout (row = horizontal, column = vertical).
Cross axisPerpendicular to the main axis — where align-items operates.
frFraction of remaining space in a grid after fixed tracks and gaps.
minmax()Grid function setting minimum and maximum track sizes.
auto-fillCreates as many tracks as fit; keeps empty tracks.
auto-fitCreates as many tracks as fit; collapses empty tracks to zero.
Grid areaNamed rectangular region in a grid defined by grid-template-areas.
Implicit gridTracks auto-created when items are placed beyond the explicit grid.
SubgridGrid item whose children align to the parent grid's tracks.
Containing blockThe ancestor an absolutely positioned element is positioned relative to.
Stacking contextBoundary for z-index competition; created by many CSS properties.
isolation: isolateCreates a stacking context without side effects.
Container queryCSS rule that responds to a container's size instead of the viewport.
cqi1% of the query container's inline size.
place-itemsGrid shorthand for align-items + justify-items.
insetShorthand for top + right + bottom + left.

Master Workflow — The Layout Stack

  1. Page shell → CSS Grid (grid-template-areas or grid-template-columns).
  2. Header / navbar → Flexbox (row, justify-content: space-between).
  3. Sidebar + main → Grid columns (250px 1fr).
  4. Card grid → Grid repeat(auto-fill, minmax(280px, 1fr)).
  5. Card internals → Flex column, flex: 1 on body, actions at bottom.
  6. Sticky headerposition: sticky; top: 0.
  7. Overlays / modalsposition: fixed; inset: 0 + portal for z-index.
  8. Z-index → token-based system with isolation: isolate on components.
  9. Component responsivenesscontainer-type: inline-size + @container.
  10. Page responsiveness@media for global breakpoints (if intrinsic isn't enough).

End of 1.8 quick revision.