Learning Objectives

By the end of this module, you will be able to:

LO1Build layouts with Flexbox, correctly distinguishing container properties from item properties and the main axis from the cross axis.
LO2Build two-dimensional layouts with CSS Grid, including tracks, gap, the fr unit, and named template areas.
LO3Choose the appropriate CSS position value — static, relative, absolute, fixed, or sticky — for a given interface requirement.
LO4Define and reuse CSS custom properties (variables) for theming and maintainable stylesheets.
LO5Animate UI state changes with transitions and build custom motion sequences with @keyframes.
LO6Explain and apply the mobile-first responsive design philosophy, contrasting it with a desktop-first approach.
LO7Build fluid layouts that adapt smoothly across viewport sizes using relative units and modern sizing functions.
LO8Serve responsive images using srcset/sizes, the <picture> element, and object-fit.
LO9Write media queries that adapt layout and typography at defined breakpoints.
LO10Use Bootstrap 5's grid system, common components, and utility classes to scaffold a responsive page quickly.
LO11Integrate Flexbox, Grid, positioning, variables, transitions, and responsive techniques into a single, fully responsive, animated multi-section web page.

Aligned to: CO2 — Design and develop well-structured, standards-compliant web pages using HTML5 and CSS3.  ·  CO5 — Build responsive, accessible user interfaces that adapt across devices and screen sizes. Builds directly on CSS3 Fundamentals (selectors, cascade, box model, color, typography).

Part A · CSS3 Layouts

Flexbox, Grid, Positioning, Variables, Transitions & Animations

2.1 Flexbox

A one-dimensional layout system — arranges items along a single row or column. The go-to tool for laying out the contents of a component: a navbar, a row of cards, a set of buttons, or centering content.

Container properties

Turning on Flexbox is a single declaration on the parent element; every property below is then set on that same parent to control how its children are arranged.

flex-directionWhich axis is the main axis — row (default), column
justify-contentAlignment along the main axis — flex-start, center, space-between, space-around, space-evenly
align-itemsAlignment along the cross axis — stretch (default), center, flex-start, flex-end
flex-wrapWhether items wrap onto new lines — nowrap (default), wrap
gapSpace between items, e.g. 1rem

Item properties

These are set on the flex items (the children) rather than the container.

flex-growGrows to fill free space, e.g. 1
flex-shrinkShrinks when space is tight, e.g. 1
flex-basisStarting size before grow/shrink, e.g. 200px
align-selfOverrides align-items, this item only
orderVisual reorder, no HTML change
Try it Yourself »
Result
💡 The Flexbox centering trick: display: flex; justify-content: center; align-items: center; on a container is the standard, reliable way to center a single child both horizontally and vertically — one of the most common Flexbox use cases in real projects.

2.2 CSS Grid

A two-dimensional layout system — lays items out along rows and columns at the same time. The natural choice for page-level and section-level layout, while Flexbox remains the natural choice for arranging items within a single component.

Defining tracks

.page {
  display: grid;
  grid-template-columns: repeat(3, 1fr); /* 3 equal columns */
  grid-template-rows: auto 1fr auto;
  gap: 1.5rem;                            /* row + column gap */
}

The fr unit represents a fraction of the remaining free space in the grid container — trivial to write flexible, equal-width (or proportionally weighted) columns. minmax(150px, 1fr) lets a track grow but never shrink below a floor size — a common technique for responsive card grids without a single media query.

Try it » Grid Tracks
Result

Placing items with named areas

Instead of positioning items by row/column line numbers, a grid can be given named regions on the container, and each child is simply assigned to a region name — a visual, ASCII-art-like syntax that makes the overall page structure easy to read directly from the CSS.

Try it » Named Grid Areas
Result

Flexbox vs. Grid — choosing the right tool

Use Flexbox when…Arranging items along one axis — a navbar, a button group, a card's internal content
Use Grid when…Laying out an entire page or section in two dimensions — header/sidebar/main/footer

In practice, most real pages use both together: Grid for the overall page skeleton, and Flexbox inside individual components placed within that grid.

2.3 Positioning

The position property controls how an element is placed relative to the normal document flow, its ancestors, or the viewport.

static (default)Normal document flow; top/right/bottom/left and z-index have no effect.
relativeStays in normal flow, but can be nudged with top/left/etc. relative to its own default position. Also establishes a positioning context for any absolutely positioned descendants.
absoluteRemoved from normal flow entirely; positioned relative to its nearest positioned ancestor (any ancestor with position other than static), or the viewport if none exists.
fixedRemoved from normal flow; positioned relative to the viewport and stays in place even while the page scrolls.
stickyA hybrid: behaves like relative until the element crosses a defined scroll threshold, then behaves like fixed — the classic technique behind sticky headers and navigation bars.
Try it Yourself »
Result
z-index controls stacking order among positioned elements that overlap — a higher z-index renders on top of a lower one. It only has an effect on elements whose position is not static, and only compares elements within the same stacking context.

2.4 CSS Variables (Custom Properties)

Let a value be defined once and reused throughout a stylesheet. Declared with a double-hyphen prefix, typically on :root so they're available globally.

:root {
  --primary-color: #1572B6;
  --text-color: #0A1B2E;
  --spacing-md: 1rem;
  --radius: 8px;
}

.card {
  color: var(--text-color);
  border-radius: var(--radius, 4px); /* 4px fallback if undefined */
  padding: var(--spacing-md);
}

Unlike Sass or LESS variables, CSS custom properties are a genuine part of the CSS language: resolved live in the browser, readable/updatable from JavaScript, and can be re-declared at a narrower scope — inside a class, a component, or a media query — to override the global value only where needed. This makes them the standard technique for theming, including light/dark mode.

Try it » Theming with Variables
Result

2.5 CSS Transitions and Animations

transition animates a property smoothly between two values whenever that value changes — most commonly on :hover or :focus. @keyframes go further: a multi-step sequence that can run independently of user interaction, loop, and reverse.

Try it » Transition + Keyframe Animation
Result
💡 A transition declaration needs, at minimum, a property to animate and a duration. Use transition for a simple state-to-state change (hover, focus, open/closed); use @keyframes/animation when the motion needs multiple steps, needs to run on page load, or needs to loop.

Laboratory Activity 1

Responsive Landing Page: Layout & Motion  ·  index.html + styles.css  ·  20 points

🖥️ Task: Build a single-page site section — a sticky navigation bar, a hero area, and a row of feature cards — using only hand-written, custom CSS.
✓Use CSS Grid for the overall page-section layout (hero region, feature-card region, footer)
✓Use Flexbox to arrange items inside the navbar and inside the row of feature cards
✓Implement a sticky header using position: sticky
✓Define a color palette and spacing scale as CSS custom properties on :root, use var() throughout
✓Apply a hover transition to at least the buttons and feature cards
✓Add at least one @keyframes animation — e.g. a fade/slide-in on the hero content
✓Write semantic HTML5 (header, nav, main, section, footer) with no inline styles
5 ptsGrid / Flexbox layout — correct, purposeful use of Grid for section layout and Flexbox for component-level arrangement
3 ptsPositioning / sticky nav — header correctly implemented, behaves as expected while scrolling
3 ptsCSS variables — palette and spacing scale defined as custom properties, reused via var()
3 ptsTransitions — smooth, appropriately-timed hover transitions on interactive elements
3 ptsKeyframe animation — at least one working @keyframes animation, sensibly applied
3 ptsCode quality / semantics — semantic HTML5, readable and organized CSS, no inline styles
💡 Submit index.html and styles.css  ·  Keep a working copy of both — this is the starting point for Lab 2  ·  Total: 20 points

Part B · Responsive Web Design

Mobile-First, Fluid Layouts, Responsive Images, Media Queries, Bootstrap 5

2.6 Mobile-First Approach

Write the base CSS for the smallest, simplest screen first, then progressively layer on enhancements for larger screens using min-width media queries.

Try it Yourself »
Result
Mobile-first is the inverse of a desktop-first approach (which starts from a full desktop layout and uses max-width queries to strip features away). Mobile-first is generally preferred: it forces prioritizing essential content, and typically produces leaner CSS since base styles are simple and only larger screens receive overrides.

2.7 Fluid Layouts

Avoid fixed pixel widths for major containers — size them with percentages, max-width, and modern CSS functions so the layout reflows naturally.

.container {
  width: 100%;
  max-width: 1200px;
  margin-inline: auto;
  padding-inline: clamp(1rem, 4vw, 3rem);
}
Try it » clamp() in Action
Result
💡 clamp(min, preferred, max) is especially useful for fluid typography and spacing — a value scales smoothly with the viewport while guaranteeing it never becomes unreadably small or excessively large. Combined with Flexbox or Grid, most of a layout adapts automatically, and media queries are reserved for genuine structural changes.

2.8 Responsive Images

The baseline rule for any image in a fluid layout: prevent it from overflowing its container.

img {
  max-width: 100%;
  height: auto;
}

srcset and sizes

srcset lets the browser choose the best-resolution image file for the user's screen size and pixel density; sizes tells the browser how wide the image will actually be displayed at different viewport widths.

Try it » Responsive Image
Result

The <picture> element and object-fit

<picture> goes further than srcset: it can swap in an entirely different image file for art direction (a tighter crop on mobile) or serve a modern format like WebP with a fallback.

<picture>
  <source media="(min-width: 768px)" srcset="hero-wide.webp">
  <source srcset="hero-tall.webp">
  <img src="hero-tall.jpg" alt="Product hero shot">
</picture>
object-fit controls how an image fills a box whose dimensions are fixed independently of the image's own aspect ratio — object-fit: cover crops the image to fill the box, while object-fit: contain scales it down to fit entirely within the box without cropping.

2.9 Media Queries

A media query applies a block of CSS only when a condition about the viewport (or device) is true.

@media (min-width: 768px) {
  .sidebar { display: block; }
}

While not a strict standard, most teams converge on a similar set of reference breakpoints:

sm≥ 576px — Large phones (landscape)
md≥ 768px — Tablets
lg≥ 992px — Small laptops
xl≥ 1200px — Desktops and large monitors
Try it Yourself » Breakpoints
Result
Media queries can also test features beyond width, such as orientation: landscape/portrait or prefers-color-scheme: dark, which lets a stylesheet automatically respect the user's system-level dark-mode preference.

2.10 Introduction to Bootstrap 5

A free, open-source CSS framework: a responsive grid system, prebuilt components, and utility classes — assemble a consistent, responsive interface quickly without writing custom CSS from scratch.

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>

The grid system

Bootstrap's grid follows a consistent container → row → column nesting pattern, built on a 12-column system. .container centers content with a responsive max-width, while .container-fluid spans the full viewport width. Responsive column classes like col-md-6 change a column's width at each breakpoint — e.g. stacking full-width on mobile, side-by-side from md up — without a single custom media query.

Components & utility classes

Spacingm-3, p-2, mt-4, px-5 — margin/padding scale, 0–5
Flex utilitiesd-flex, justify-content-center — quick Flexbox layout without custom CSS
Texttext-center, fw-bold, text-muted — alignment and typography tweaks
Responsive displayd-none d-md-block — hidden by default; shown from the md breakpoint up
Try it Yourself » Bootstrap Grid + Card
Result
Framework vs. hand-rolled CSS: Bootstrap trades some fine-grained design control and a larger CSS payload for speed, consistency, and built-in accessibility and responsiveness. Excellent for prototypes, internal tools, and tight timelines; a custom design system is usually better when a highly distinctive visual identity or a minimal file size is the priority.

Laboratory Activity 2

Make It Responsive, Then Rebuild in Bootstrap 5  ·  20 points

🖥️ Task: Directly extends Lab 1's page. Two parts, designed to let you directly compare a hand-rolled responsive approach against a framework-based one.

Part 1 — Add a mobile-first stylesheet

✓Starting from Lab 1's page, write the base (unqueried) CSS to look correct on a small mobile screen first
✓Add min-width media queries at, at minimum, the md and lg breakpoints to adapt the grid and navbar layout
✓Make the hero image responsive using the srcset attribute (and sizes, if multiple widths are provided)
✓Verify the page using DevTools' device toolbar across at least three screen widths (e.g. 375px, 768px, 1280px)

Part 2 — Rebuild in Bootstrap 5

✓Recreate the same page structure (navbar, hero, feature cards, footer) using Bootstrap's container/row/col grid system
✓Use Bootstrap components where appropriate — at minimum, Navbar and Card
✓Use Bootstrap utility classes for spacing, text alignment, and at least one responsive-display class (e.g. d-none d-md-block)
✓Add a short written comparison (3–5 sentences) reflecting on the trade-offs between the hand-rolled version and the Bootstrap version
5 ptsMobile-first structure & breakpoints — base styles are genuinely mobile-first; breakpoints use min-width and are applied sensibly
3 ptsResponsive images — srcset (and sizes, if applicable) implemented correctly
4 ptsBootstrap grid usage — correct container/row/col structure and responsive column classes
4 ptsBootstrap components — at least a Navbar and Card component used correctly
2 ptsUtility classes — purposeful use of spacing, text, and responsive-display utilities
2 ptsComparison reflection — thoughtful, specific reflection on custom CSS vs. Bootstrap trade-offs
💡 Submit responsive-custom.html + responsive-custom.css (Part 1) plus responsive-bootstrap.html (Part 2)  ·  Total: 20 points

Formative Assessment

14 quick recall & application questions covering both parts of this module

  1. Which display value creates a one-dimensional Flexbox layout?
  2. Which Flexbox container property controls alignment along the cross axis?
  3. Which CSS Grid unit represents a fraction of the remaining free space in the grid?
  4. Which property defines named layout regions in a Grid container?
  5. Which position value removes an element from normal flow but keeps it fixed relative to the viewport even while scrolling?
  6. Which position value behaves like relative until a scroll threshold is reached, then like fixed?
  7. How is a global CSS custom property declared?
  8. Which function reads a CSS variable, with an optional fallback value?
  9. Which at-rule defines an animation's keyframe steps?
  10. Name the two parts every transition declaration must include, at minimum.
  11. True or False: mobile-first CSS primarily relies on max-width media queries.
  12. Which HTML attribute lets the browser automatically choose the best image resolution for the viewport?
  13. Which Bootstrap 5 class, applied to a column's parent, creates a responsive 12-column grid layout?
  14. Which Bootstrap utility hides an element by default but displays it from the md breakpoint upward?

Password required.

Key Takeaways

CSS3 Layouts & Responsive Design: Flexbox · Grid · Positioning · Variables · Transitions & Animations · Mobile-First · Fluid Layouts · Responsive Images · Media Queries · Bootstrap 5

  1. Flexbox handles one-dimensional, component-level layout; CSS Grid handles two-dimensional, page-level layout — most real interfaces use both together.
  2. Positioning (static, relative, absolute, fixed, sticky) gives fine-grained control for sticky headers, fixed UI elements, and precisely placed overlays or badges.
  3. CSS custom properties centralize a design's colors, spacing, and other repeated values, making large stylesheets far easier to maintain and theme.
  4. Transitions and keyframe animations add polish and communicate state changes clearly to users, without requiring JavaScript for simple cases.
  5. Mobile-first design, fluid layouts, responsive images, and media queries combine to produce a page that works well on any device, from a small phone to a large desktop monitor.
  6. Bootstrap 5 trades a degree of fine-grained design control for speed and consistency — a strong choice for prototypes and time-boxed projects, while a hand-rolled system offers more control over a unique visual identity.
  7. Together, this module completes the core front-end layout toolkit and sets up the next lesson's introduction to JavaScript, which adds interactivity on top of these layouts.

References

Course resources for this topic

MDN Web DocsCSS Flexible Box Layout, CSS Grid Layout, CSS positioned layout, CSS custom properties — developer.mozilla.org/en-US/docs/Web/CSS
CSS-TricksA Complete Guide to Flexbox / A Complete Guide to Grid — css-tricks.com
BootstrapBootstrap 5 Documentation — getbootstrap.com/docs
Duckett, J. (2014)HTML & CSS: Design and Build Websites. Wiley.
Freeman & Robson (2020)Head First HTML and CSS (2nd ed.). O'Reilly.
Robbins, J. N. (2018)Learning Web Design (5th ed.). O'Reilly.

▶ Next

JavaScript Fundamentals

Adding interactivity on top of the layout & responsive design toolkit