Popular Searches
Popular Course Categories
Popular Courses

Flexbox & Grid

32 mins CSS3 & Responsive Design

Flexbox & Grid in React JS

Course: React JS Training

Topic: Flexbox & Grid

Course Link: React JS Training

Demo Link: Register for a Course Demo


1. Why Layout Matters in Modern Web Design

Every web page you have ever used is really a set of boxes sitting beside, above and inside each other: a header, a navigation bar, a row of cards, a sidebar next to an article, a footer. CSS layout is the skill of telling the browser exactly where those boxes go. For many years that skill meant tricks — floating blocks sideways and clearing them, stretching inline-block elements, or positioning everything by hand. Those tricks worked, but they were fragile and hard to read.

Modern CSS gives us two purpose-built layout systems: Flexbox and Grid. They are plain CSS, they work in every browser you will meet in real projects, and they remove most of the old hacks. Once you know them, layouts that used to take an afternoon take a few lines.

For a React learner this page is essential groundwork. React renders components, but components end up as ordinary HTML elements, and their arrangement on screen is decided by CSS. Almost every interface you build in React — a button group, a card list, a full dashboard — will be arranged with Flexbox or Grid. CSS layout questions, including the traps hidden inside simple-looking ones, are also a regular feature of frontend interviews, so a clear understanding here pays off twice.

2. Flexbox and Grid in Simple Words

Flexbox lays out items in one direction at a time — either a single row or a single column. You decide how items spread out, squeeze together, or wrap onto a new line when they run out of room. It is ideal when the important thing is a line of content: a navigation bar, a toolbar, a row of buttons, a list of tags.

Grid divides the space into rows and columns at the same time, like a spreadsheet or a chessboard. You define the tracks (the rows and columns), then place items into the cells, optionally letting an item span several cells. It is ideal when the important thing is the shape of the page: header on top, sidebar at the left, content in the middle, footer at the bottom.

A useful way to remember the difference: Flexbox lets the content drive the layout, because items flow along one axis and adjust to their own sizes. Grid lets the layout drive the content, because you fix the structure first and then pour content into it. Both are standard CSS, and real pages use them together.

If you can describe the layout as "a row or a column of things", use Flexbox. If you can describe it as "a table with named regions", use Grid.

3. Key Terms You Will Meet

Both systems have their own small vocabulary. Learning these words now makes every later explanation shorter.

TermSimple meaning
Flex containerThe parent element with display: flex; its direct children become flex items
Flex itemA direct child of a flex container
Main axisThe direction flex items flow in — a row or a column
Cross axisThe direction at right angles to the main axis
Flex lineOne row (or column) of items after wrapping
Grid containerThe parent element with display: grid
Grid itemA direct child of a grid container
TrackOne row or one column of the grid
Grid lineThe invisible dividing line between and around tracks; lines are numbered
CellThe box where one row track meets one column track
Grid areaA rectangular block made of one or more cells
GapFixed empty space between tracks or between flex items
fr"Fraction" unit — a share of the free space in a grid

4. Getting Started with Flexbox: The Container and the Axes

Flexbox begins with one line of CSS on a parent element. Writing display: flex on the parent turns it into a flex container, and all of its direct children automatically become flex items arranged in a horizontal row.

<div class="toolbar">
  <div class="box">Home</div>
  <div class="box">Courses</div>
  <div class="box">Contact</div>
</div>
.toolbar {
  display: flex;
  gap: 10px;
  background: #eee;
  padding: 10px;
}
.box {
  background: steelblue;
  color: white;
  padding: 10px 20px;
}

Result: the three boxes sit side by side on one line instead of stacking the way block elements normally do, with 10 pixels between them. Notice what you did not do — no floats, no widths, no inline-block. One property on the parent arranged the children.

The two axes

Everything in Flexbox is described relative to two axes:

  • Main axis — the direction the items flow in. By default this is horizontal (a row).
  • Cross axis — the direction at right angles to the main axis. By default this is vertical.

Only the direct children become flex items. A grandchild is laid out normally inside its own parent, which keeps behaviour predictable and lets you nest flex containers freely.

5. Direction and Wrapping: flex-direction and flex-wrap

flex-direction

flex-direction chooses which way the main axis runs:

  • row — the default; items go left to right.
  • row-reverse — items go right to left.
  • column — items go top to bottom.
  • column-reverse — items go bottom to top.

With column, the main axis becomes vertical, so justify-content, which you will meet next, now controls vertical spacing. This axis-switching causes many "why is it centring sideways?" surprises, so always ask first: which way is my main axis pointing?

flex-wrap

By default flex items try to fit on a single flex line, shrinking if necessary. flex-wrap: wrap lets them move onto a new line when space runs out.

.tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}
.tag {
  background: gold;
  padding: 6px 12px;
}

With many tags and a narrow window, each line fills up and the remaining tags drop to the next line, every line keeping its own even spacing. Remove flex-wrap: wrap and all tags squeeze onto one line instead. The shorthand flex-flow: row wrap sets direction and wrap together in one declaration.

6. justify-content: Spacing Items on the Main Axis

Once items sit along the main axis, justify-content decides how the leftover space on that axis is shared out.

ValueWhat happens to the free space
flex-start (default)All free space goes to the end; items packed at the start
flex-endItems packed at the end
centerItems packed in the middle
space-betweenEqual space between items, none at the outer edges
space-aroundEqual space around each item, but half-size at the two edges
space-evenlyIdentical space between items and at both edges

The difference between the last two is a classic interview trap. With three items, space-around puts a half-unit of space before the first and after the last item, so the edges look thinner than the middle gaps. space-evenly makes the edge gaps exactly the same size as the inner gaps.

A navbar that always splits left and right

.navbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
  background: #222;
}
.brand { color: white; font-weight: bold; }
.nav-links { display: flex; gap: 16px; }

Result: the brand hugs the left edge, the links hug the right edge, at every window width. space-between absorbs all the spare width into the single space between them — a one-line solution to one of the oldest layout tasks.

7. align-items and align-self: The Cross Axis

align-items does the same job on the cross axis. Its default value, stretch, is the quiet reason flex items in a row become equal height — each item stretches to match its tallest sibling. That one default replaces the old "equal-height columns" hack completely.

ValueEffect along the cross axis
stretch (default)Items grow to fill the container's cross size
flex-startItems pack at the start of the cross axis
flex-endItems pack at the end
centerItems sit in the middle
baselineItems line up by their text baselines

The perfect centring recipe

Centring something both ways — historically one of the hardest tasks in CSS — takes two properties with Flexbox:

.hero {
  display: flex;
  justify-content: center; /* main axis: horizontal */
  align-items: center;     /* cross axis: vertical */
  min-height: 100vh;
}

The child of .hero ends up exactly in the middle of the screen. If one item needs different treatment, give it align-self directly: align-self: flex-end on one card pushes only that card down while the rest keep the container's alignment.

8. Sizing Items: flex-grow, flex-shrink and flex-basis

Three properties decide how items share space:

  • flex-grow — when there is spare space, how much of it this item may claim. Default is 0: claim nothing.
  • flex-shrink — when space is short, how willing the item is to shrink. Default is 1.
  • flex-basis — the item's starting size along the main axis before any growing or shrinking. Default is auto: the content's own size.

In practice you almost always write them with the flex shorthand:

  • flex: 1 means grow 1, shrink 1, basis 0 — "share the free space equally, ignore my content size".
  • flex: 2 claims twice as much spare space as a neighbouring flex: 1.
  • flex: auto uses basis auto — size to content first, then share what remains.
  • flex: none means never grow and never shrink — a fixed-size item.

A sidebar and a content panel

.page {
  display: flex;
  min-height: 100vh;
}
.sidebar {
  width: 220px;
  flex: none;      /* stays fixed */
  background: #2c3e50;
}
.content {
  flex: 1;         /* takes all remaining width */
  background: #ecf0f1;
  padding: 20px;
}

The sidebar stays 220 pixels wide at every screen size; the content panel absorbs everything else. If you later add a second flexible panel with flex: 2, the leftover width is split 1 : 2 between the flexible panels automatically — no arithmetic for you to redo whenever the window changes size.

9. Gaps and the order Property

gap works in flexbox as well as in grid, and it is the modern way to space items. It beats margins on every child because margins must be removed from the first and last items, while gap only ever exists between items. row-gap and column-gap set the two directions separately.

order rearranges items visually. Every item defaults to order: 0; lower numbers come first, and items with equal order keep their source order.

.menu { display: flex; gap: 12px; }
.menu .logout { order: -1; } /* jumps to the front visually */

One caution: order changes only the visual order, not the HTML source and not the keyboard tab order, so screen-reader and keyboard users still meet the items in source order. Use order for small visual adjustments, never to scramble meaningful content.

10. Getting Started with Grid: Rows, Columns and Tracks

Grid also starts on the parent, with display: grid. You then describe the structure using grid-template-columns and grid-template-rows. Each value in the list creates one track.

.gallery {
  display: grid;
  grid-template-columns: 200px 1fr 1fr;
  gap: 12px;
}
.gallery img { width: 100%; display: block; }

Result: a three-column strip. The first column is fixed at 200 pixels; the other two share the leftover width equally, because 1fr means "one fraction of the free space". Two 1fr tracks get equal shares; 1fr 2fr would split the free space one-third to two-thirds.

The repeat() helper

grid-template-columns: repeat(3, 1fr);    /* same as 1fr 1fr 1fr */
grid-template-columns: repeat(4, 100px);  /* four fixed columns */

What the browser does with fr, step by step

  1. It lays down the fixed tracks first (for example the 200px column).
  2. It subtracts those fixed sizes and all the gaps from the container's width.
  3. It divides whatever is left — the free space — among the fr tracks in proportion to their numbers.
  4. It repeats the whole calculation every time the window resizes.

So in a 1,000-pixel-wide container, 200px 1fr 1fr with 12-pixel gaps leaves about 776 pixels of free space, giving each 1fr column about 388 pixels. Change the window and the fractions recalculate — that is the whole point of the unit.

11. Placing Items: Grid Lines, Spans and Named Areas

Grid draws invisible numbered lines around the tracks: a grid with 3 columns has 4 vertical lines, numbered 1 to 4 from the start. You can position any item by naming the lines it sits between.

.featured {
  grid-column: 1 / 3;  /* from line 1 to line 3: first two columns */
  grid-row: 1;
}

The span keyword is often clearer to read: grid-column: span 2 means "occupy two columns starting where I would naturally sit".

Named areas: a complete page layout

The most readable way to build a page shell is grid-template-areas. You name the regions and then sketch the layout row by row, exactly as it should look.

.page {
  display: grid;
  grid-template-columns: 220px 1fr;
  grid-template-rows: auto 1fr auto;
  grid-template-areas:
    "header header"
    "sidebar main"
    "footer footer";
  min-height: 100vh;
}
.page header { grid-area: header; }
.page aside  { grid-area: sidebar; }
.page main   { grid-area: main; }
.page footer { grid-area: footer; }

Result: the header spans both columns at the top; the 220-pixel sidebar sits beside the content, and the middle row takes all remaining height thanks to the 1fr row; the footer spans the bottom. Rearranging the page for small screens is a copy-paste of the area sketch, not a rewrite of every element:

@media (max-width: 700px) {
  .page {
    grid-template-columns: 1fr;
    grid-template-areas:
      "header"
      "main"
      "sidebar"
      "footer";
  }
}

The same four elements now stack in a single column with the sidebar sliding below the content — with zero changes to the HTML. Media queries are the next sub-module, so treat this as a preview of what the two lessons can do together.

12. Grid Alignment, Gaps and Responsive Columns

Alignment inside cells

Grid reuses the alignment ideas from Flexbox. justify-items and align-items position each item inside its own cell (start, end, center, stretch). The shorthand place-items: center centres an item in its cell both ways — handy for tiles, icons and loading screens.

A responsive card grid without media queries

The most famous Grid pattern combines repeat(), auto-fit and minmax() so that the columns decide their own count:

.cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}
.card {
  background: white;
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 16px;
}

How it works, step by step:

  1. The browser fits as many 200-pixel-wide columns as the container allows.
  2. Leftover width is shared equally (1fr), so every column grows a little wider than 200 pixels.
  3. When the window shrinks and a column can no longer keep 200 pixels, that column disappears and the cards reflow.
  4. Wide screens show four or five cards per row; phones show one — without a single media query.

auto-fill behaves almost the same but keeps empty tracks in place, which is useful when you want items to hold a fixed width instead of stretching to fill the row. For most card layouts, auto-fit is the choice.

13. Flexbox or Grid: Choosing the Right Tool

QuestionFlexboxGrid
Dimensions handledOne at a time (row or column)Rows and columns together
Best forComponents, toolbars, nav bars, content-driven rowsPage shells, galleries, dashboards, layout-driven designs
Sizing modelItems flex around their contentStructure declared first, items placed into it
Placement freedomItems flow in orderItems can span, overlap and sit on any lines
WrappingThrough flex-wrapThrough auto-fill/auto-fit patterns

The honest answer experienced developers give: it is rarely either-or. A typical page uses Grid for the overall skeleton and Flexbox inside each region. In the layout below, Grid arranges the three regions, Flexbox spaces the top bar, and Flexbox lines up the content inside each stat card.

.dashboard {
  display: grid;
  grid-template-columns: 240px 1fr;
  gap: 16px;
}
.topbar {
  grid-column: 1 / 3;         /* spans both grid columns */
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.stat-row { display: flex; gap: 16px; }
.stat {
  flex: 1;                    /* equal-width cards */
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

Read it layer by layer: the outer .dashboard is a grid with a fixed sidebar and a flexible main area; .topbar stretches across both columns using grid lines, and inside itself it is a flex row with the title on the left and controls on the right; .stat-row is a flex row of cards, and each card is a small vertical flexbox so its number and its label sit at opposite ends. This layered pattern — grid outside, flex inside — is the one you will reach for in most real projects.

14. Real-World Flexbox Patterns

Part 1 covered the building blocks. Now let us look at the small, reusable arrangements that professional interfaces are made of. Each pattern below is a recipe you will use again and again, in plain websites and inside React components alike.

The sticky footer

Problem: on pages with little content, the footer floats up halfway and leaves an ugly empty area below it. Solution: turn the page wrapper into a column flex container that is at least as tall as the screen, and let the main content absorb all leftover height.

body {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}
main {
  flex: 1;   /* grows to fill the space above the footer */
}

Because main has flex: 1, it stretches on short pages and simply takes its natural height on long ones. The footer always ends at the bottom of the viewport or lower — never in the middle.

The perfectly centred modal overlay

A dialog that floats above the page is usually a fixed-position wrapper with one centred child:

.overlay {
  position: fixed;
  inset: 0;                 /* covers the whole viewport */
  display: flex;
  justify-content: center;  /* horizontal centring */
  align-items: center;      /* vertical centring */
  background: rgba(0, 0, 0, 0.5);
}

Whatever you place inside .overlay — a dialog box, a spinner, a confirmation card — lands exactly in the middle of the screen, regardless of its own size.

The media object: avatar beside text

A comment, message or product row is almost always "a fixed image on the left, text that fills the rest":

.row {
  display: flex;
  gap: 12px;
}
.row .avatar {
  flex: none;      /* image keeps its natural size */
}
.row .body {
  flex: 1;         /* text takes the remaining width */
  min-width: 0;    /* allows the text block to shrink */
}

The min-width: 0 line is the quiet hero here. Without it, a very long unbroken word (a URL, for example) forces the text block to stay as wide as its content and pushes the layout apart. The next-but-one section explains why.

The stretching search bar

.search-bar {
  display: flex;
  gap: 8px;
}
.search-bar input { flex: 1; }   /* input grows, button keeps its size */

The input absorbs every spare pixel while the button stays comfortably sized at its content width. The same "one flexible item plus fixed items" recipe works for toolbars, table rows and list items.

15. Real-World Grid Patterns

The twelve-column layout

Design tools work on a twelve-column grid, and you can reproduce it exactly in CSS. Items then occupy any run of columns you like:

.layout {
  display: grid;
  grid-template-columns: repeat(12, 1fr);
  gap: 16px;
}
.article { grid-column: 1 / 9; }   /* first eight columns */
.aside   { grid-column: 9 / 13; }  /* last four columns */

Changing the article to grid-column: 2 / 12 indents it on both sides with one declaration. This is why Grid feels natural to anyone who has used a design tool: you think in columns, not in pixel arithmetic.

A dashboard with spanning cards

.dashboard {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 16px;
}
.stat       { grid-column: span 1; }
.wide-chart { grid-column: span 2; }
.full-alert { grid-column: span 4; }

Four stat tiles fill one row, the chart takes half the width of the next row, and the alert stretches across the full width. Mixed-size cards fall out of the structure without any per-item widths.

Text over an image with overlapping areas

Grid items placed on the same area stack on top of each other. That gives a clean way to overlay a caption on a photo:

.hero {
  display: grid;
}
.hero img,
.hero .caption {
  grid-area: 1 / 1;   /* both occupy the first row and column */
}
.hero .caption {
  align-self: end;     /* push the caption to the bottom of the cell */
  padding: 16px;
  color: white;
}

No absolute positioning, no negative margins — the image and the caption simply share one grid area, and the caption aligns itself to the bottom edge.

16. Debugging Layouts in the Browser

Every modern browser's developer tools understand Flexbox and Grid. When you select an element in the inspector, containers show a small flex or grid badge; clicking it draws a coloured overlay on the page that marks the axes, the numbered grid lines, the track sizes and the gaps. This turns invisible structure into something you can see, which is the fastest way to answer "why is this box over there?"

Before opening the tools, it helps to recognise the classic symptoms and their usual causes:

SymptomLikely causeFix
Items squeeze onto one line instead of wrappingWrapping not enabledAdd flex-wrap: wrap
justify-content: center seems to do nothingMain axis points the other way, or the container has no spare spaceCheck flex-direction; give the container a real width or height
A flex item refuses to shrink below its contentThe default min-width: autoSet min-width: 0 on the item
A grid column is wider than its fr shareContent's minimum size forces the track openUse minmax(0, 1fr) for the track
Spacing looks uneven at the edgesMargins fighting with gapRemove the margins and rely on gap alone
Footer will not sit at the bottomPage wrapper is not a flex or grid containerUse the sticky footer pattern from above

17. Common Mistakes and the Correct Way

Mistake: putting display: flex on the children

Beginners often write display: flex on each item, hoping the items will line up. Layout properties on a parent control its children, so the declaration belongs on the container:

/* Wrong */
.item { display: flex; }

/* Correct */
.container { display: flex; }

Mistake: centring on the wrong axis in a column

With flex-direction: column, the main axis runs vertically, so justify-content now moves items up and down, and align-items moves them sideways. If centring "stopped working" after switching to a column, the axes swapped — exchange the two properties:

.stack {
  display: flex;
  flex-direction: column;
  justify-content: center;  /* vertical centring now */
  align-items: center;      /* horizontal centring now */
}

Mistake: items squashed instead of wrapped

A flex row with many items shrinks them into thin slivers by default. If the items should keep a usable size and flow onto new lines, wrapping must be switched on:

/* Wrong: items shrink forever */
.tags { display: flex; }

/* Correct: items wrap when space runs out */
.tags { display: flex; flex-wrap: wrap; }

Mistake: a flex item that will not shrink

Flex items have an implicit min-width: auto, meaning "never smaller than my content". One long word can then blow the whole row open. The fix is to allow the item to shrink below its content size:

/* Wrong: the long URL stretches the panel */
.panel { flex: 1; }

/* Correct: the panel may shrink; the text can wrap or be cut */
.panel { flex: 1; min-width: 0; }

Mistake: fr tracks pushed open by content

The same minimum-size rule applies in Grid. A track declared 1fr still will not go below its content's minimum width. Wrap the fraction in minmax() with an explicit floor of zero:

/* Wrong: wide table content widens the column */
grid-template-columns: 1fr 1fr;

/* Correct: columns obey the fr split strictly */
grid-template-columns: minmax(0, 1fr) minmax(0, 1fr);

Mistake: margin juggling instead of gap

Adding margin-right to every item puts an unwanted space after the last one, which then needs a :last-child cleanup rule. gap exists only between items, so there is nothing to clean up:

/* Wrong */
.menu a { margin-right: 16px; }
.menu a:last-child { margin-right: 0; }

/* Correct */
.menu { display: flex; gap: 16px; }

18. Best Practices for Flexbox and Grid

  • Space with gap, not margins. It is declarative, symmetrical and needs no edge-case rules.
  • Build mobile-first. Let content stack naturally by default, then introduce columns with grid-template-columns or flex-direction: row as the screen grows. The next sub-module, media queries, formalises this.
  • Prefer minmax() and auto-fit over fixed column counts. The layout then adapts itself and needs fewer breakpoints.
  • Keep layout rules on containers, content rules on items. A card's padding belongs to the card; the spacing between cards belongs to the grid or flex container around them.
  • Use named grid areas for page-level layouts. A sketch like "header header" reads like a drawing of the page and makes responsive rearrangement trivial.
  • Keep nesting shallow. If you are four flex containers deep, ask whether one grid could express the same structure more directly.
  • Test with extreme content. Very long words, empty lists, one item and fifty items — resilient layouts survive all of them.
  • Choose one system per problem and stay consistent. Reaching for Flexbox for rows and Grid for structure, as in Part 1's dashboard, keeps code predictable for the whole team.

19. Accessibility: Layout and Reading Order

Layout and meaning are separate concerns, and confusing them creates real problems for users who navigate by keyboard or with a screen reader.

  • Visual order is not source order. order and grid placement change where elements appear, but a screen reader and the Tab key still follow the HTML sequence. Write the HTML in a logical reading order first, and only then adjust positions visually.
  • Do not clip focus outlines. A container with overflow: hidden and tight padding can cut off the visible focus ring around a button, leaving keyboard users lost. Give interactive items breathing room.
  • Avoid fixed heights on text containers. height: 40px on a card clips enlarged text when a user increases the font size. Prefer min-height, or let content size the box.
  • Check the reflow. Zoom the page to a large magnification: a good Flexbox or Grid layout reflows into a single readable column instead of forcing horizontal scrolling.

20. Practical Project: A Responsive Course Dashboard

Let us combine everything into one complete, working page: a top bar, a sidebar, a stats strip, course cards and a footer — arranged with Grid on the outside and Flexbox on the inside, and collapsing gracefully on small screens.

Step 1: Write the HTML skeleton

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Course Dashboard</title>
  <link rel="stylesheet" href="style.css">
</head>
<body class="page">
  <header class="topbar">
    <strong>JustAcademy</strong>
    <nav class="menu">
      <a href="#">Courses</a>
      <a href="#">Progress</a>
      <a href="#">Profile</a>
    </nav>
  </header>
  <aside class="sidebar">
    <a href="#">HTML</a>
    <a href="#">CSS</a>
    <a href="#">JavaScript</a>
  </aside>
  <main class="main">
    <section class="stats">
      <div class="stat"><span>12</span>Lessons done</div>
      <div class="stat"><span>3</span>Courses active</div>
      <div class="stat"><span>87%</span>Average score</div>
    </section>
    <section class="cards">
      <article class="card">
        <h3>Flexbox Basics</h3>
        <p>Containers, axes and alignment.</p>
        <button>Continue</button>
      </article>
      <article class="card">
        <h3>Grid Layout</h3>
        <p>Tracks, areas and gaps.</p>
        <button>Continue</button>
      </article>
    </section>
  </main>
  <footer class="footer">Web Foundations notes</footer>
</body>
</html>

Step 2: Draw the page skeleton with grid areas

* { box-sizing: border-box; margin: 0; }
body { font-family: system-ui, sans-serif; }

.page {
  display: grid;
  grid-template-columns: 200px 1fr;
  grid-template-rows: auto 1fr auto;
  grid-template-areas:
    "topbar  topbar"
    "sidebar main"
    "footer  footer";
  min-height: 100vh;
}
.topbar  { grid-area: topbar; }
.sidebar { grid-area: sidebar; }
.main    { grid-area: main; }
.footer  { grid-area: footer; }

The header and footer span both columns; the sidebar is a fixed 200 pixels; the 1fr middle row gives the content all remaining height, which is what keeps the footer pinned to the bottom.

Step 3: Lay out the top bar with Flexbox

.topbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
  background: #1f2937;
  color: #fff;
}
.menu { display: flex; gap: 16px; }
.menu a { color: #fff; text-decoration: none; }

Brand on the left, links on the right, vertically centred — space-between does the splitting.

Step 4: Style the sidebar and the main column

.sidebar {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 16px;
  background: #e5e7eb;
}
.main {
  padding: 20px;
  display: grid;
  gap: 20px;
  align-content: start;  /* sections stack from the top */
}

The sidebar is itself a small vertical flexbox, and the main area is a single-column grid that spaces its sections with gap.

Step 5: Make the stats and cards responsive without media queries

.stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
  gap: 12px;
}
.stat {
  display: flex;
  flex-direction: column;
  gap: 4px;
  padding: 12px;
  background: #f3f4f6;
  border-radius: 8px;
}
.cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
  gap: 16px;
}

Both strips choose their own column count: three stat tiles side by side on a desktop, stacked on a phone, with nothing to maintain.

Step 6: Build the card as a mini flex column

.card {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 16px;
  border: 1px solid #d1d5db;
  border-radius: 8px;
}
.card button {
  margin-top: auto;   /* pushes the button to the card's bottom */
  padding: 8px;
  background: #2563eb;
  color: #fff;
  border: 0;
  border-radius: 6px;
}

The trick in margin-top: auto is worth remembering: inside a flex column, an automatic margin swallows all free space above the item, so the button hugs the bottom edge even when the card texts have different lengths.

Step 7: Collapse the layout for small screens

.footer {
  padding: 12px 20px;
  background: #1f2937;
  color: #fff;
}
@media (max-width: 640px) {
  .page {
    grid-template-columns: 1fr;
    grid-template-areas:
      "topbar"
      "main"
      "sidebar"
      "footer";
  }
  .topbar { flex-wrap: wrap; gap: 8px; }
}

Only the area sketch changes — the sidebar slides below the content, and the top bar wraps if the links no longer fit. Save the two files, open the page, and drag the window narrow and wide to watch every part reflow.

21. Practice Exercises

  1. Weighted row: build a pricing strip of three cards where the middle card is exactly twice as wide as the outer two, using flex values only — no percentage widths.
  2. Collapsing navigation: create a navbar that is a horizontal space-between row on wide screens and a centred vertical column on narrow ones, changing only flex-direction and justify-content.
  3. Self-managing gallery: lay out eight images with repeat(auto-fit, minmax(180px, 1fr)) and record how many columns appear at full width, tablet width and phone width.
  4. Area rearrangement: take the dashboard project and, using only the grid-template-areas sketch inside a media query, move the sidebar above the content on small screens.
  5. Overlay caption: reproduce the overlapping-areas hero so the caption sits at the bottom-left of the image, then move it to the top-right by changing alignment properties only.
  6. Bug hunt: a teammate's chat panel is stretched wide by a single long URL. Diagnose the cause and fix it with the smallest possible change.

22. Interview Questions and Answers

What is the difference between Flexbox and Grid?

Flexbox lays out items along one axis at a time — a row or a column — and is content-driven, so it suits components like navbars and button groups. Grid defines rows and columns together and is layout-driven, so it suits page structures, galleries and dashboards. In real projects they are combined: Grid for the skeleton, Flexbox inside each region.

What do justify-content and align-items actually control?

justify-content distributes free space along the main axis; align-items positions items along the cross axis. When flex-direction: column is set, the main axis becomes vertical, so the two properties effectively swap their visual effects — a very common interview trap.

What does the shorthand flex: 1 mean?

It expands to flex-grow: 1; flex-shrink: 1; flex-basis: 0%. The item ignores its content size as a starting point and shares the free space equally with other flexible items. flex: 2 claims twice the share of a neighbouring flex: 1.

What is the difference between auto-fit and auto-fill?

Both create as many minmax() tracks as fit in the container. auto-fill keeps empty tracks in place when items run out, while auto-fit collapses them so the existing items stretch to fill the row. For card grids that should stretch, auto-fit is the usual choice.

Explain the fr unit.

fr stands for fraction. The browser first sizes the fixed tracks and subtracts the gaps, then divides the remaining free space among the fr tracks in proportion to their values. 1fr 2fr gives one third of the free space to the first track and two thirds to the second, recalculated on every resize.

Why does a flex item refuse to shrink below its content, and how do you fix it?

Flex items default to min-width: auto, which sets their minimum size to their content's minimum size. A long unbroken word therefore forces the item wide. Setting min-width: 0 (or overflow: hidden) on the item allows it to shrink, after which the text can wrap or truncate.

What is the difference between space-around and space-evenly?

space-around places equal space around each item, but the two outer gaps are only half the size of the inner ones. space-evenly makes every gap — including the two at the edges — exactly the same width.

How do you centre an element both horizontally and vertically?

With Flexbox: display: flex; justify-content: center; align-items: center; on the parent. With Grid, a single declaration does it: place-items: center;. Both approaches work regardless of the child's size.

What are grid lines and how do you place an item between them?

Grid draws numbered lines around the tracks; three columns produce four vertical lines. grid-column: 1 / 3 places an item from line 1 to line 3, covering the first two columns. The span keyword, as in grid-column: span 2, sizes an item by track count instead of line numbers.

Why is gap preferred over margins for spacing?

gap applies only between items, so there is no stray space at the edges and no need for :last-child cleanup rules. It also works identically in Flexbox and Grid and supports separate row-gap and column-gap values.

Does the order property change the reading order for screen readers?

No. order and grid placement are purely visual; keyboard focus and screen readers follow the HTML source order. Keep the source meaningful and use order only for small visual adjustments.

What is grid-template-areas and why is it useful?

It lets you name regions and sketch the layout row by row, such as "header header" "sidebar main". Each item is then assigned with grid-area. Rearranging the whole page for a different screen size becomes a matter of redrawing the sketch, with no changes to the HTML.

23. Quick Revision Checklist

  • display: flex on the parent creates flex items out of its direct children; the default direction is a row.
  • Main axis follows flex-direction; the cross axis is always at right angles to it.
  • justify-content works on the main axis, align-items on the cross axis; they swap roles in a column.
  • flex: 1 means grow 1, shrink 1, basis 0; flex: none fixes an item's size.
  • flex-wrap: wrap lets items flow onto new lines; flex-flow combines direction and wrap.
  • space-around has half-size edge gaps; space-evenly has equal gaps everywhere.
  • gap is the modern spacing tool in both Flexbox and Grid.
  • display: grid plus grid-template-columns defines tracks; repeat() shortens the lists.
  • 1fr is a share of the free space after fixed tracks and gaps are subtracted.
  • Grid lines are numbered; place items with grid-column: 1 / 3 or span 2.
  • grid-template-areas sketches named layouts; grid-area assigns each item.
  • repeat(auto-fit, minmax(200px, 1fr)) builds responsive columns without media queries.
  • place-items: center centres an item inside its grid cell.
  • min-width: 0 on flex items and minmax(0, 1fr) in Grid defeat the content minimum size.
  • order and placement are visual only — source order still drives reading and keyboard order.
  • Sticky footer: column flex wrapper with min-height: 100vh and a growing main.

Conclusion

Flexbox and Grid replace the old layout hacks with two clear mental models: one-dimensional flow and two-dimensional structure. You now know the axes, the sizing properties, the placement tools, the classic patterns and the traps that catch most beginners — from axis confusion to the invisible min-width: auto. More importantly, you know how the two systems cooperate: Grid draws the skeleton of a page, Flexbox arranges the content inside each region, and gap keeps the spacing honest in both.

These skills carry directly into the rest of the course. The next sub-module, media queries, adds the official switch that lets you change Flexbox and Grid behaviour per screen size — you have already previewed it with the dashboard project. Later, when you style React components, you will reach for exactly these properties, because every component tree eventually renders down to boxes that must sit somewhere on the page. Master the containers, the axes and the tracks now, and layout will stop being a battle and become a decision.

Learn more in the React JS Training course, or register for a course demo.

Previous Next
whatsapp