Introduction to Web Technologies (HTML, CSS, JS)

Chapter 7
CSS Layout and Visual Design

Diploma in Full Stack Programming
Introduction to Web Technologies (HTML, CSS, JS)   •   Diploma

CSS Layout and Visual Design

Introduction

A web page is not merely a collection of HTML elements. It is a visual system in which content is arranged, separated, aligned, emphasized, and animated. CSS provides the rules that transform a document structure into a usable interface. Layout determines where elements appear; visual design determines how users perceive relationships, hierarchy, focus, and interaction.

This chapter examines the main CSS mechanisms used to construct professional interfaces: normal flow, display modes, positioning, stacking contexts, Flexbox, Grid, spacing, backgrounds, borders, transformations, transitions, and basic animation. The emphasis is on selecting the appropriate layout model rather than memorising isolated properties.

Learning Objectives

By the end of this chapter, you should be able to:

  • explain how normal flow affects element placement;
  • distinguish block, inline, inline-block, and hidden display modes;
  • use relative, absolute, fixed, and sticky positioning appropriately;
  • construct one-dimensional layouts with Flexbox;
  • construct two-dimensional layouts with CSS Grid;
  • control spacing using margin, padding, gaps, and box sizing;
  • create visual hierarchy with backgrounds, borders, shadows, and gradients;
  • apply transformations, transitions, and keyframe animations responsibly;
  • diagnose common layout problems using browser developer tools;
  • design responsive and accessible layouts for practical web applications.

1. The CSS Layout Model

CSS layout is governed by several interacting ideas: the document tree, formatting contexts, the box model, and the order in which elements are painted. An element normally generates a rectangular box consisting of content, padding, border, and margin.

1.1 The box model

The content area contains text or child content. Padding creates space between content and the border. The border surrounds the padding and content. Margin creates space outside the border and separates the element from neighbouring elements.

With the default content-box model, the declared width applies only to the content area. The rendered width is therefore:

Rendered width = content width + left padding + right padding + left border + right border

With box-sizing: border-box, the declared width includes content, padding, and border. For most interface work, the following rule makes dimensions easier to reason about:

*, *::before, *::after {
  box-sizing: border-box;
}

Margins are outside the element and do not form part of its background. Padding is inside the element and receives its background colour or image.

1.2 Normal flow

Normal flow is the default arrangement of elements before special positioning or layout systems are applied. Block-level elements are generally placed one below another. Inline content flows along a line and wraps when necessary.

The height of a normal-flow parent is normally influenced by the height of its in-flow children. An absolutely positioned or fixed element is removed from normal flow, so it does not reserve ordinary space in its parent.

Normal flow should be regarded as a useful layout system, not as an obstacle. It adapts naturally to changing text, screen sizes, and content length. Excessive use of absolute positioning often produces fragile interfaces because coordinates do not respond well to changing content.

1.3 Collapsing margins

In some block formatting situations, the vertical margins of adjacent block elements collapse. Instead of their sum, the resulting separation is commonly the larger of the two adjoining positive margins. Margin collapse has exceptions, including flex and grid items, elements with borders or padding separating them, and many formatting-context boundaries.

A predictable alternative is to use a parent layout with display: flex or display: grid and control separation with gap.

2. Display Modes and Formatting Contexts

The display property determines how an element participates in layout and how its children are laid out.

Display valueMain behaviourTypical use
blockStarts on a new line and can accept width and heightSections, articles, containers
inlineOccupies only its content width and flows within textLinks, emphasis, small text elements
inline-blockFlows inline but accepts dimensionsBadges, compact controls
noneRemoves the element from layout and accessibility tree in normal useConditional interface content
flexEstablishes a one-dimensional flex formatting contextNavigation bars, toolbars, card rows
gridEstablishes a two-dimensional grid formatting contextPage structures and card galleries

An element can have a block outer display and a flex inner display. For example, display: flex causes the element itself to participate as a block-level item by default while laying out its children as flex items.

visibility: hidden differs from display: none: the element is invisible but normally retains its layout space. This distinction matters when preserving alignment or avoiding content movement.

3. Positioning and Stacking

The position property changes how an element is placed.

  • static is the default. Offset properties such as top and left do not normally apply.
  • relative keeps the element in normal flow but permits visual offsetting. It also commonly establishes the containing block for absolutely positioned descendants.
  • absolute removes the element from normal flow and positions it relative to an appropriate positioned ancestor or, if none exists, an initial containing block.
  • fixed removes the element from normal flow and positions it relative to the viewport in common cases. It is useful for persistent controls but can obstruct content.
  • sticky behaves like a relatively positioned element until a scrolling threshold is reached, after which it remains within its scrolling container.

A common overlay pattern is:

.card {
  position: relative;
}

.card__badge {
  position: absolute;
  top: 0.75rem;
  right: 0.75rem;
}

The card remains in normal flow, while the badge is positioned within the card. The parent must normally be positioned so that it becomes the badge’s containing block.

3.1 Stacking and z-index

When boxes overlap, CSS uses painting order and stacking contexts to determine which appears on top. z-index compares positioned elements within the relevant stacking context; it is not a universal global ranking.

A new stacking context can be created by conditions such as a positioned element with a non-auto z-index, certain transformed elements, opacity below 1, and some containment or isolation properties. A child with a very large z-index cannot escape its parent stacking context to appear above a separate sibling context that is painted later.

Use a small, documented layering scale rather than arbitrary values:

:root {
  --layer-base: 0;
  --layer-header: 10;
  --layer-overlay: 100;
  --layer-modal: 1000;
}

4. Flexbox: One-Dimensional Layout

Flexbox is designed for distributing items along one primary axis. The flex container has a main axis and a cross axis. With flex-direction: row, the main axis is horizontal; with column, it is vertical.

.toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 1rem;
}

Important container properties include:

  • flex-direction: selects row or column orientation;
  • flex-wrap: permits items to form additional lines;
  • justify-content: distributes free space along the main axis;
  • align-items: aligns items along the cross axis;
  • align-content: distributes multiple flex lines;
  • gap, row-gap, and column-gap: create space between items.

Important item properties include:

  • flex-grow: controls how an item receives available positive space;
  • flex-shrink: controls how an item gives up space when necessary;
  • flex-basis: supplies the initial main-axis size;
  • flex: shorthand for grow, shrink, and basis;
  • align-self: overrides cross-axis alignment for one item;
  • order: changes visual order, but should be used cautiously for accessibility.

For example:

.main {
  display: flex;
  gap: 2rem;
}

.content {
  flex: 1 1 0;
  min-width: 0;
}

.sidebar {
  flex: 0 1 18rem;
}

min-width: 0 is often important because flex items can otherwise refuse to shrink below their automatic minimum size, causing unexpected horizontal overflow.

Flexbox is best for navigation bars, button groups, toolbars, aligned form controls, and rows or columns in which the relationship is primarily one-dimensional.

5. CSS Grid: Two-Dimensional Layout

Grid is intended for simultaneous control of rows and columns. A grid container defines tracks, lines, and areas. The fr unit represents a fraction of available grid space after fixed-size requirements have been considered.

.dashboard {
  display: grid;
  grid-template-columns: 16rem minmax(0, 1fr);
  grid-template-rows: auto 1fr;
  gap: 1.5rem;
}

minmax(0, 1fr) is a robust pattern for a flexible track because it permits the track to shrink to zero when necessary rather than allowing long unbreakable content to force overflow.

Responsive card layouts can be created with:

.cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr));
  gap: 1.25rem;
}

auto-fit allows available columns to collapse when insufficient space exists. auto-fill preserves empty track opportunities where appropriate. Grid items may be placed explicitly:

.page {
  display: grid;
  grid-template-areas:
    "header header"
    "nav main"
    "footer footer";
  grid-template-columns: 15rem 1fr;
}

header { grid-area: header; }
nav    { grid-area: nav; }
main   { grid-area: main; }
footer { grid-area: footer; }

Grid is generally preferable for page-level structures, dashboards, galleries, and layouts where both row and column alignment matter. Flexbox and Grid are complementary rather than competing systems.

6. Spacing and Sizing

Good visual design depends on consistent spacing. Use a spacing scale based on a root unit or design token rather than unrelated values:

:root {
  --space-1: 0.25rem;
  --space-2: 0.5rem;
  --space-3: 0.75rem;
  --space-4: 1rem;
  --space-6: 1.5rem;
  --space-8: 2rem;
}

padding controls internal space, margin controls external separation, and gap controls separation between flex or grid children. Prefer gap for sibling spacing in modern layout systems because it avoids special rules for the first or last item.

Useful sizing functions include:

  • min(): selects the smaller of supplied values;
  • max(): selects the larger value;
  • clamp(min, preferred, max): creates a bounded fluid value;
  • minmax(min, max): defines a grid track range.

For example:

h1 {
  font-size: clamp(1.8rem, 4vw, 3.5rem);
}

The preferred value responds to viewport width, but the minimum and maximum prevent extreme results. Relative units such as rem, em, %, vw, and vh support adaptable interfaces. Fixed pixels remain useful for borders, icons, and carefully controlled dimensions, but should not be used for every measurement.

7. Backgrounds, Borders, and Visual Hierarchy

Background properties include colour, image, position, size, repeat, and attachment. Multiple backgrounds are painted in listed order, with the first listed image generally appearing closest to the user.

.hero {
  background:
    linear-gradient(135deg, rgb(10 35 70 / 0.9), rgb(10 35 70 / 0.45)),
    url("hero.jpg") center / cover no-repeat;
  color: white;
}

A text-reading layer over an image improves contrast, but colour alone must not be the only means of communicating information. Borders can separate regions, define controls, or indicate focus. Use border-radius to soften corners, but preserve sufficient contrast and consistent geometry.

Box shadows can express elevation:

.panel {
  border: 1px solid #d9e0e8;
  border-radius: 0.75rem;
  box-shadow: 0 0.5rem 1.5rem rgb(20 40 70 / 0.12);
}

Do not use shadows or colour contrast as substitutes for semantic structure. Users of screen readers rely on HTML semantics, while users with low vision may require strong contrast and visible focus indicators.

8. Transformations, Transitions, and Animation

A transform changes an element’s visual coordinate system without normally changing the layout space occupied by that element. Common functions include translate, scale, rotate, and skew.

.icon:hover {
  transform: translateY(-0.15rem) scale(1.04);
}

Because transforms can create stacking contexts, they may affect overlap behaviour. Transform origins can be controlled with transform-origin.

Transitions interpolate property values when a state changes:

.button {
  background: #155eef;
  transition: background-color 160ms ease, transform 160ms ease;
}

.button:hover {
  background: #0045c7;
  transform: translateY(-2px);
}

A transition should be short enough to feel responsive and should generally animate properties that browsers can handle efficiently, such as transform and opacity. Avoid transitioning layout-heavy properties unnecessarily.

Keyframe animation describes multiple stages:

@keyframes pulse {
  0%, 100% { transform: scale(1); opacity: 1; }
  50%      { transform: scale(1.04); opacity: 0.8; }
}

.status {
  animation: pulse 2s ease-in-out infinite;
}

Animation must communicate state or provide feedback rather than distract users. Respect the user preference for reduced motion:

@media (prefers-reduced-motion: reduce) {
  *, *::before, *::after {
    animation-duration: 0.01ms !important;
    animation-iteration-count: 1 !important;
    transition-duration: 0.01ms !important;
    scroll-behavior: auto !important;
  }
}

9. Responsive and Accessible Layout

Responsive design is not simply shrinking a desktop page. It involves changing structure, density, and interaction according to available space and user needs. Use fluid tracks, flexible images, wrapping, and media or container queries where appropriate.

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

@media (max-width: 48rem) {
  .page {
    grid-template-areas:
      "header"
      "main"
      "nav"
      "footer";
    grid-template-columns: 1fr;
  }
}

Accessibility requirements include visible keyboard focus, sufficient colour contrast, readable line lengths, logical source order, and controls large enough to operate. Do not use CSS positioning to create a visual order that conflicts with the meaningful HTML order. Test zoom, keyboard navigation, high contrast conditions, and narrow screens.

10. Worked Application: A Responsive Course Dashboard

Consider an illustrative case in which a training provider needs a course dashboard. The desktop design contains a header, navigation sidebar, main course cards, and a footer. On mobile, the sidebar should move below the main content and cards should become a single column.

A suitable structure is:

<div class="dashboard">
  <header class="dashboard__header">Course Portal</header>
  <aside class="dashboard__nav">Navigation</aside>
  <main class="dashboard__main">
    <section class="cards">
      <article class="card">HTML Foundations</article>
      <article class="card">CSS Layout</article>
      <article class="card">JavaScript Basics</article>
    </section>
  </main>
  <footer class="dashboard__footer">Support</footer>
</div>

The layout can be implemented as follows:

.dashboard {
  min-height: 100vh;
  display: grid;
  grid-template:
    "header header" auto
    "nav main" 1fr
    "footer footer" auto / 15rem minmax(0, 1fr);
}

.dashboard__header { grid-area: header; }
.dashboard__nav    { grid-area: nav; }
.dashboard__main   { grid-area: main; padding: 1.5rem; }
.dashboard__footer { grid-area: footer; }

.cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(15rem, 1fr));
  gap: 1rem;
}

.card {
  padding: 1.25rem;
  border: 1px solid #d9e0e8;
  border-radius: 0.75rem;
  transition: transform 160ms ease, box-shadow 160ms ease;
}

.card:hover,
.card:focus-within {
  transform: translateY(-0.2rem);
  box-shadow: 0 0.6rem 1.2rem rgb(20 40 70 / 0.14);
}

@media (max-width: 48rem) {
  .dashboard {
    grid-template:
      "header" auto
      "main" 1fr
      "nav" auto
      "footer" auto / 1fr;
  }
}

Analysis

Grid is used for the page shell because both rows and columns matter. A nested grid is used for cards because cards must align into responsive columns. The minmax(0, 1fr) track prevents long content from forcing the main region beyond the viewport. The mobile media query changes the named areas without requiring a second HTML structure. The hover effect is supplemented by :focus-within, ensuring that keyboard users receive comparable feedback.

Outcome and learning points

The solution remains readable, adapts to content, and maintains a logical document structure. It avoids absolute coordinates for primary layout, uses a consistent spacing system, and limits animation to a meaningful interaction response. In a production system, the implementation would also require real focus styles, tested colour contrast, semantic navigation, and testing with zoom and assistive technology.

11. Troubleshooting and Professional Practice

Common layout failures have identifiable causes:

  • Unexpected horizontal scrolling: inspect fixed widths, long words, flex automatic minimum sizes, and grid tracks; try min-width: 0 and minmax(0, 1fr).
  • An absolutely positioned element appears in the wrong place: check which ancestor establishes its containing block.
  • z-index appears ineffective: inspect stacking contexts rather than merely increasing the number.
  • Flex items do not shrink: examine flex-basis, automatic minimum sizes, and unbreakable content.
  • A child escapes a rounded panel: use appropriate overflow handling, while considering whether clipped content is accessible.
  • Spacing is inconsistent: replace scattered margins with design tokens and gap.
  • Content is hidden under a fixed header: provide equivalent layout space and verify scrolling behaviour.

Use browser developer tools to inspect computed styles, box dimensions, grid overlays, flex overlays, containing blocks, and media-query states. Validate with multiple browsers and realistic content, not only short placeholder text.

12. Contemporary Considerations

Modern CSS supports increasingly expressive responsive systems. Container queries allow a component to respond to the size of its own container rather than the viewport. Logical properties such as margin-inline, padding-block, and inset-inline-start support writing modes and internationalisation. CSS custom properties enable design tokens and theme changes. Subgrid can allow nested components to participate in an ancestor grid’s track structure where browser support and project requirements permit.

These features should be adopted according to project support requirements and progressive-enhancement principles. CSS should remain understandable, testable, and maintainable. A visually impressive layout is unsuccessful if it is unusable with a keyboard, unreadable at increased zoom, or unstable when content changes.

Chapter Summary

CSS layout begins with normal flow and the box model. Display modes determine how elements participate in formatting contexts. Positioning is appropriate for overlays and persistent interface elements, but primary structure should usually rely on normal flow, Flexbox, or Grid. Flexbox manages one-dimensional relationships, whereas Grid manages rows and columns simultaneously. Consistent spacing, responsive sizing, backgrounds, borders, and controlled layering create visual hierarchy. Transforms, transitions, and animations add feedback when used purposefully and with reduced-motion support. Professional CSS combines visual quality with semantic HTML, responsive behaviour, keyboard access, readable code, and testing against realistic content.

Key Terms

Box model: The content, padding, border, and margin areas of an element.

Normal flow: The default arrangement of elements in document order.

Formatting context: A layout environment that determines how boxes interact.

Block: A display mode that normally starts on a new line.

Inline: A display mode that participates within a line of text.

Containing block: The reference rectangle used to position an element.

Relative positioning: Positioning that retains the element’s normal-flow space.

Absolute positioning: Positioning that removes an element from normal flow.

Sticky positioning: Positioning that becomes fixed relative to a scrolling area at a threshold.

Stacking context: An independent painting and layering context.

Flexbox: A one-dimensional CSS layout system.

Main axis: The primary axis of a flex container.

Cross axis: The axis perpendicular to a flex container’s main axis.

CSS Grid: A two-dimensional row-and-column layout system.

Grid track: A row or column in a grid.

Gap: Space between flex or grid items.

Transform: A visual change to an element’s coordinate system.

Transition: Interpolation between property states.

Keyframe animation: An animation defined by named intermediate stages.

Responsive design: Design that adapts to available space and user conditions.

Review Questions

Short Answer Questions

  1. What four areas make up the CSS box model?
  2. How does display: none differ from visibility: hidden?
  3. What is the main difference between Flexbox and CSS Grid?
  4. Why is min-width: 0 sometimes needed on a flex item?
  5. What is the purpose of prefers-reduced-motion?

Long Answer Questions

  1. Explain normal flow, margin behaviour, and the circumstances in which positioning removes an element from normal flow.
  2. Compare relative, absolute, fixed, and sticky positioning, including an appropriate use case for each.
  3. Explain the roles of justify-content, align-items, flex-grow, flex-shrink, and flex-basis.
  4. Design a responsive page layout using Grid and explain why named grid areas may improve maintainability.
  5. Discuss how visual hierarchy, spacing, contrast, borders, and animation contribute to usability and accessibility.

Analytical / Application Questions

  1. A dashboard overflows horizontally only when a long course title is displayed. Identify likely causes and propose CSS changes to correct the problem.
  2. A modal appears behind a header even though its z-index is larger. Explain how stacking contexts could cause this result and describe a systematic solution.
  3. Create a layout strategy for a product-card gallery that displays several columns on wide screens and one column on narrow screens. Justify your choice of Grid or Flexbox, sizing functions, spacing method, and accessibility considerations.

Multiple Choice Questions with Answers

Question 1

Which layout system is primarily designed for one-dimensional relationships?

A. CSS Grid

B. Flexbox

C. Absolute positioning

D. The table layout algorithm

Correct Answer: B. Flexbox

Question 2

What does box-sizing: border-box cause the declared width to include?

A. Only the content area

B. Only the margin area

C. Content, padding, and border

D. Content and margin but not padding

Correct Answer: C. Content, padding, and border

Question 3

Which property creates space between flex or grid children without adding margins to individual children?

A. gap

B. outline

C. z-index

D. transform

Correct Answer: A. gap

Question 4

An absolutely positioned badge is intended to be placed inside a card. Which parent rule most commonly establishes the required positioning reference?

A. position: relative

B. display: inline

C. visibility: hidden

D. float: left

Correct Answer: A. position: relative

Question 5

What does minmax(0, 1fr) commonly help prevent in a grid layout?

A. Text colour changes

B. A flexible track being forced wider by content

C. All grid items becoming absolutely positioned

D. Borders being painted

Correct Answer: B. A flexible track being forced wider by content

Question 6

Which property controls distribution along the main axis of a flex container?

A. align-items

B. justify-content

C. align-content

D. transform-origin

Correct Answer: B. justify-content

Question 7

Which statement about a CSS transform is generally correct?

A. It always changes the element’s layout dimensions

B. It normally changes visual appearance without changing normal-flow space

C. It removes the element from the DOM

D. It can only rotate text

Correct Answer: B. It normally changes visual appearance without changing normal-flow space

Question 8

Which media feature allows a site to reduce or disable nonessential motion for users who request it?

A. prefers-contrast

B. resolution

C. prefers-reduced-motion

D. orientation

Correct Answer: C. prefers-reduced-motion

Question 9

What is a likely reason to use display: grid for a dashboard page shell?

A. It controls rows and columns together

B. It prevents all responsive changes

C. It only works for inline text

D. It automatically supplies semantic HTML

Correct Answer: A. It controls rows and columns together

Question 10

Why can increasing a child element’s z-index fail to place it above another element?

A. z-index only applies to images

B. The child may be constrained within its parent stacking context

C. z-index changes font size instead

D. z-index works only on static elements

Correct Answer: B. The child may be constrained within its parent stacking context

Introduction to Web Technologies (HTML, CSS, JS)
Chapter 7 of 15