Learning Objectives
By the end of this module, you will be able to:
fr unit, and named template areas.position value — static, relative, absolute, fixed, or sticky — for a given interface requirement.@keyframes.srcset/sizes, the <picture> element, and object-fit.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-direction | Which axis is the main axis — row (default), column |
|---|---|
justify-content | Alignment along the main axis — flex-start, center, space-between, space-around, space-evenly |
align-items | Alignment along the cross axis — stretch (default), center, flex-start, flex-end |
flex-wrap | Whether items wrap onto new lines — nowrap (default), wrap |
gap | Space between items, e.g. 1rem |
Item properties
These are set on the flex items (the children) rather than the container.
flex-grow | Grows to fill free space, e.g. 1 |
|---|---|
flex-shrink | Shrinks when space is tight, e.g. 1 |
flex-basis | Starting size before grow/shrink, e.g. 200px |
align-self | Overrides align-items, this item only |
order | Visual reorder, no HTML change |
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.
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.
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. |
|---|---|
relative | Stays 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. |
absolute | Removed from normal flow entirely; positioned relative to its nearest positioned ancestor (any ancestor with position other than static), or the viewport if none exists. |
fixed | Removed from normal flow; positioned relative to the viewport and stays in place even while the page scrolls. |
sticky | A 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. |
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.
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.
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
position: sticky:root, use var() throughout@keyframes animation — e.g. a fade/slide-in on the hero contentheader, nav, main, section, footer) with no inline styles| 5 pts | Grid / Flexbox layout — correct, purposeful use of Grid for section layout and Flexbox for component-level arrangement |
|---|---|
| 3 pts | Positioning / sticky nav — header correctly implemented, behaves as expected while scrolling |
| 3 pts | CSS variables — palette and spacing scale defined as custom properties, reused via var() |
| 3 pts | Transitions — smooth, appropriately-timed hover transitions on interactive elements |
| 3 pts | Keyframe animation — at least one working @keyframes animation, sensibly applied |
| 3 pts | Code quality / semantics — semantic HTML5, readable and organized CSS, no inline styles |
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.
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);
}
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.
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 |
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
| Spacing | m-3, p-2, mt-4, px-5 — margin/padding scale, 0–5 |
|---|---|
| Flex utilities | d-flex, justify-content-center — quick Flexbox layout without custom CSS |
| Text | text-center, fw-bold, text-muted — alignment and typography tweaks |
| Responsive display | d-none d-md-block — hidden by default; shown from the md breakpoint up |
Laboratory Activity 2
Make It Responsive, Then Rebuild in Bootstrap 5 · 20 points
Part 1 — Add a mobile-first stylesheet
min-width media queries at, at minimum, the md and lg breakpoints to adapt the grid and navbar layoutsrcset attribute (and sizes, if multiple widths are provided)Part 2 — Rebuild in Bootstrap 5
d-none d-md-block)| 5 pts | Mobile-first structure & breakpoints — base styles are genuinely mobile-first; breakpoints use min-width and are applied sensibly |
|---|---|
| 3 pts | Responsive images — srcset (and sizes, if applicable) implemented correctly |
| 4 pts | Bootstrap grid usage — correct container/row/col structure and responsive column classes |
| 4 pts | Bootstrap components — at least a Navbar and Card component used correctly |
| 2 pts | Utility classes — purposeful use of spacing, text, and responsive-display utilities |
| 2 pts | Comparison reflection — thoughtful, specific reflection on custom CSS vs. Bootstrap trade-offs |
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
- Which
displayvalue creates a one-dimensional Flexbox layout? - Which Flexbox container property controls alignment along the cross axis?
- Which CSS Grid unit represents a fraction of the remaining free space in the grid?
- Which property defines named layout regions in a Grid container?
- Which
positionvalue removes an element from normal flow but keeps it fixed relative to the viewport even while scrolling? - Which
positionvalue behaves likerelativeuntil a scroll threshold is reached, then likefixed? - How is a global CSS custom property declared?
- Which function reads a CSS variable, with an optional fallback value?
- Which at-rule defines an animation's keyframe steps?
- Name the two parts every
transitiondeclaration must include, at minimum. - True or False: mobile-first CSS primarily relies on
max-widthmedia queries. - Which HTML attribute lets the browser automatically choose the best image resolution for the viewport?
- Which Bootstrap 5 class, applied to a column's parent, creates a responsive 12-column grid layout?
- Which Bootstrap utility hides an element by default but displays it from the
mdbreakpoint upward?
Password required.
display: flex;align-items- The
frunit grid-template-areasposition: fixed;position: sticky;- By defining
--name: value;inside a:rootrule var(--name, fallback)@keyframes- A property to animate and a duration
- False — mobile-first primarily uses
min-widthmedia queries srcsetrow(combined withcol-*classes on its children)d-none d-md-block
Key Takeaways
CSS3 Layouts & Responsive Design: Flexbox · Grid · Positioning · Variables · Transitions & Animations · Mobile-First · Fluid Layouts · Responsive Images · Media Queries · Bootstrap 5
- Flexbox handles one-dimensional, component-level layout; CSS Grid handles two-dimensional, page-level layout — most real interfaces use both together.
- Positioning (static, relative, absolute, fixed, sticky) gives fine-grained control for sticky headers, fixed UI elements, and precisely placed overlays or badges.
- CSS custom properties centralize a design's colors, spacing, and other repeated values, making large stylesheets far easier to maintain and theme.
- Transitions and keyframe animations add polish and communicate state changes clearly to users, without requiring JavaScript for simple cases.
- 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.
- 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.
- 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 Docs | CSS Flexible Box Layout, CSS Grid Layout, CSS positioned layout, CSS custom properties — developer.mozilla.org/en-US/docs/Web/CSS |
|---|---|
| CSS-Tricks | A Complete Guide to Flexbox / A Complete Guide to Grid — css-tricks.com |
| Bootstrap | Bootstrap 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. |