Web Technologies

Chapter 4
CSS, Responsive Design and User Experience

Bachelors Program in AI & ML
Web Technologies   •   Bachelor

CSS, Responsive Design and User Experience

Introduction

The visual quality, accessibility, and usability of a web application depend substantially on how its interface is structured and styled. HTML provides semantic structure, while Cascading Style Sheets (CSS) defines presentation, layout, adaptation to different devices, and many aspects of interaction feedback. For modern applications, CSS is not merely a decorative language. It is a design and engineering system that connects content, visual hierarchy, device constraints, accessibility requirements, and user goals.

Responsive design extends this role by enabling an interface to adapt to screen size, input method, orientation, resolution, and user preferences. User experience (UX) design complements responsive implementation by asking whether the resulting interface is understandable, efficient, accessible, and satisfactory. A technically responsive interface can still provide poor UX if controls are difficult to locate, content is badly prioritized, or users cannot recover from errors.

This chapter develops the foundations required to create responsive interfaces using the cascade, selectors, the box model, layout systems, Flexbox, Grid, media queries, design systems, usability principles, and mobile-first methods.

Learning Objectives

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

1. Explain how CSS rules are selected, inherited, cascaded, and resolved.

2. Apply selectors, the box model, sizing rules, spacing, and positioning appropriately.

3. Select and implement Flexbox or Grid for common layout problems.

4. Design interfaces using mobile-first responsive principles and media queries.

5. Apply usability, accessibility, and UX principles to interface decisions.

6. Construct a small, consistent design system using custom properties.

7. Evaluate responsive solutions critically, including their limitations and maintenance implications.

1. CSS as a System of Rules

CSS consists of rules that associate declarations with selected elements. A basic rule has a selector and a declaration block:

```css

p {

color: #222;

line-height: 1.6;

}

```

The selector identifies one or more elements, while declarations specify property-value pairs. The browser converts the document into a rendered result through a process commonly described as style calculation, layout, painting, and compositing. CSS therefore participates in a rendering pipeline rather than simply changing colors.

1.1 Selectors

Important selector categories include:

  • Type selector: `article` selects all `article` elements.
  • Class selector: `.card` selects elements with the class `card`.
  • ID selector: `#main-navigation` selects an element with that ID.
  • Attribute selector: `input[type="email"]` selects email controls.
  • Descendant selector: `.card p` selects paragraphs inside an element with class `card`.
  • Child selector: `.menu > li` selects only direct child list items.
  • Pseudo-class: `button:hover`, `input:focus-visible`, and `:checked` represent states.
  • Pseudo-element: `::before` and `::after` represent generated portions of an element.

Selectors should communicate structure without becoming unnecessarily specific. Classes are generally preferable to IDs for reusable styling because IDs have high specificity and are less flexible.

1.2 The Cascade and Specificity

The word cascading describes how competing declarations are resolved. The result depends principally on origin and importance, specificity, and source order. A declaration with greater specificity generally overrides one with lower specificity; if specificity is equal, the later declaration wins. Inline styles and `!important` alter normal priority and should be used cautiously.

A useful conceptual comparison is:

```css

p { color: black; }

.notice { color: darkblue; }

```

For `<p class="notice">`, the class selector is more specific than the type selector, so `darkblue` is applied. Specificity is not a general numerical score used to justify arbitrary complexity; it is a comparison of selector components. A maintainable stylesheet minimizes specificity conflicts through deliberate naming, component boundaries, and limited nesting.

1.3 Inheritance and Custom Properties

Some properties, such as `color` and `font-family`, commonly inherit from a parent. Others, such as `margin` and `border`, do not inherit by default. The keywords `inherit`, `initial`, `unset`, and `revert` can explicitly control this behavior.

Custom properties provide reusable design values:

```css

:root {

--color-primary: #1456a0;

--space-2: 0.5rem;

--radius-card: 0.75rem;

}

.button {

background: var(--color-primary);

padding: var(--space-2) 1rem;

border-radius: var(--radius-card);

}

```

Custom properties support design consistency, theming, and later maintenance. They can also be changed in a media query or a user-preference query.

2. The CSS Box Model

Every rendered element is represented conceptually as a rectangular box consisting of content, padding, border, and margin. Padding creates space inside the border; margin creates space outside it. Backgrounds normally extend through the padding area but not the margin area.

The default `content-box` sizing model treats declared `width` as the content width. Thus, if an element has declared width `300px`, horizontal padding of `20px` on each side, and borders of `2px` on each side, its outer width is:

`300px + 20px + 20px + 2px + 2px = 344px`.

With `box-sizing: border-box`, the declared width includes content, padding, and border, so the outer width is `300px` and the content area is reduced accordingly. A common baseline is:

```css

, ::before, *::after {

box-sizing: border-box;

}

```

This makes width calculations more predictable, especially in responsive layouts.

2.1 Width, Height, and Overflow

Absolute lengths such as pixels are useful for borders and controlled dimensions, but responsive interfaces often use relative units. Percentages are relative to a containing block; `rem` is relative to the root font size; `em` is relative to the font size of the relevant element; `vw` and `vh` relate to the viewport.

Fixed heights can cause content clipping when text enlarges or translations expand. `min-height`, intrinsic sizing, and natural content flow are often safer. Overflow should be deliberate: hidden content can create accessibility problems, while horizontal scrolling may be appropriate for wide data tables.

2.2 Margin Collapse and Spacing

Vertical margins between normal-flow block boxes can collapse, meaning the resulting gap is often the larger margin rather than their sum. Flex and Grid containers do not use ordinary margin collapse between their items. Modern layouts frequently use `gap`, which expresses spacing between layout children more predictably:

```css

.stack {

display: flex;

flex-direction: column;

gap: 1rem;

}

```

3. Layout and Positioning

Normal flow places block elements vertically and inline content horizontally according to available space. Normal flow is valuable because it adapts naturally to content and zoom. Layout systems should enhance normal flow rather than replace it unnecessarily.

The `display` property determines an element's outer and inner layout behavior. Common values include `block`, `inline`, `inline-block`, `flex`, `grid`, and `none`. `display: none` removes an element from the layout and accessibility tree in typical browser behavior; it is not equivalent to merely making an element visually transparent.

Positioning modes include:

  • `static`: the normal default positioning.
  • `relative`: remains in normal flow but establishes a positioning context for absolutely positioned descendants.
  • `absolute`: removed from normal flow and positioned relative to a containing block.
  • `fixed`: positioned relative to the viewport or an applicable containing context.
  • `sticky`: behaves relatively until a threshold is reached, then remains fixed within its scrolling context.

Positioning should not be used as the primary layout mechanism for ordinary page structure. Excessive absolute positioning often breaks when content changes or the viewport narrows.

4. Flexbox

Flexbox is a one-dimensional layout model. It distributes items along a main axis and aligns them along a cross axis. The main axis is horizontal when `flex-direction: row` and vertical when it is `column`.

```css

.toolbar {

display: flex;

align-items: center;

justify-content: space-between;

gap: 1rem;

flex-wrap: wrap;

}

```

Important container properties include:

  • `flex-direction`: establishes the main axis.
  • `flex-wrap`: permits items to form multiple lines.
  • `justify-content`: distributes free space along the main axis.
  • `align-items`: aligns items on the cross axis.
  • `align-content`: distributes multiple flex lines.
  • `gap`: sets consistent spacing.

Important item properties include:

  • `flex-grow`: determines how an item may absorb available free space.
  • `flex-shrink`: determines how an item may shrink when space is insufficient.
  • `flex-basis`: establishes the initial main-axis size.
  • `align-self`: overrides cross-axis alignment for one item.

For example, `flex: 1 1 15rem` means an item may grow, may shrink, and begins with a basis of `15rem`. Flexbox is especially appropriate for navigation bars, toolbars, form rows, cards in a row, and alignment of content within a component.

A frequent error is assuming that `align-items` controls horizontal alignment in every situation. Its effect depends on the direction of the main axis; developers must identify the axes before choosing alignment properties.

5. CSS Grid

Grid is a two-dimensional layout model. It defines rows and columns and is useful when relationships in both dimensions matter.

```css

.product-list {

display: grid;

grid-template-columns: repeat(auto-fit, minmax(15rem, 1fr));

gap: 1.25rem;

}

```

Here, `repeat()` avoids repeating track definitions, `minmax()` specifies a lower and upper track size, and `1fr` distributes available space among flexible tracks. `auto-fit` allows empty tracks to collapse, enabling items to expand; `auto-fill` preserves the conceptual empty tracks and can produce different behavior when there are few items.

Grid supports explicit placement, named areas, alignment, and implicit tracks. A named-area example is:

```css

.page {

display: grid;

grid-template-areas:

"header header"

"sidebar content";

grid-template-columns: 16rem 1fr;

}

.header { grid-area: header; }

.sidebar { grid-area: sidebar; }

.content { grid-area: content; }

```

Grid should not be judged as universally superior to Flexbox. Flexbox is generally simpler for one-dimensional alignment, while Grid is more expressive for two-dimensional page and component structure. They can be combined: Grid can define a page, and Flexbox can align the controls within a page region.

6. Responsive and Mobile-First Design

Responsive design is an approach in which layout and content adapt to the characteristics of the viewing environment. It is not simply a collection of device-specific versions. A responsive interface should accommodate intermediate widths, zoom, text enlargement, different input methods, and changing content.

Mobile-first design begins with a narrow layout and progressively adds enhancements for larger available spaces. This approach encourages prioritization because small screens expose unnecessary complexity. It can also produce a simpler base stylesheet and targeted enhancements.

```css

.dashboard {

display: grid;

gap: 1rem;

}

@media (min-width: 48rem) {

.dashboard {

grid-template-columns: 16rem 1fr;

}

}

```

The breakpoint above is not a universal device classification. It is a design threshold at which the content needs another arrangement. Breakpoints should therefore be content-driven rather than copied mechanically from a list of phone, tablet, and desktop sizes.

6.1 Media Queries

Media queries conditionally apply styles based on features such as viewport width, orientation, resolution, and user preferences:

```css

@media (prefers-reduced-motion: reduce) {

, ::before, *::after {

animation-duration: 0.01ms;

animation-iteration-count: 1;

scroll-behavior: auto;

}

}

```

Other useful features include `prefers-color-scheme`, `forced-colors`, and pointer or hover capability. A responsive design should avoid assuming that a small viewport always means touch input or that a large viewport always means a mouse.

The viewport declaration in HTML is also essential for mobile rendering:

```html

<meta name="viewport" content="width=device-width, initial-scale=1">

```

6.2 Fluid Design

Fluid dimensions can reduce abrupt changes between breakpoints. Functions such as `clamp()` define a minimum, preferred, and maximum value:

```css

h1 {

font-size: clamp(2rem, 5vw, 4rem);

}

```

The browser chooses a value that responds to viewport width while respecting the stated bounds. Fluid type and spacing must still be tested for readability, line length, and localization.

7. User Experience and Usability

UX concerns the total quality of a person's interaction with a product, including usefulness, learnability, efficiency, accessibility, trust, and satisfaction. Usability is a related concept focused particularly on whether intended users can accomplish goals effectively, efficiently, and satisfactorily in a specified context.

Several principles are especially relevant to CSS and responsive interfaces:

1. Visibility of system status: show loading, validation, and completion states.

2. Match between system and the real world: use familiar language and meaningful grouping.

3. User control and freedom: provide cancellation, undo, and predictable navigation.

4. Consistency and standards: maintain consistent controls, spacing, labels, and interaction states.

5. Error prevention and recovery: constrain invalid input and explain how to correct it.

6. Recognition rather than recall: expose available actions and preserve context.

7. Flexibility and efficiency: support both novice discovery and experienced shortcuts.

8. Minimalist design: remove irrelevant visual competition without hiding necessary information.

9. Helpful error messages: state the problem and the corrective action.

10. Documentation when necessary: provide concise, contextual assistance.

These principles are not a substitute for user research. They are heuristics that guide evaluation and design decisions.

7.1 Information Architecture and Visual Hierarchy

Responsive design begins with content priorities. A page should communicate what it is, what users can do, and what information matters most. Hierarchy is established through semantic headings, spacing, contrast, typography, grouping, and progressive disclosure. CSS can create visual order, but visual order should not contradict the logical order of the HTML and keyboard focus sequence.

A narrow layout may stack a sidebar below the primary content, but merely moving it visually does not necessarily change reading order. CSS `order` should therefore be used carefully. A visually attractive reordering can confuse screen-reader users or keyboard users if the DOM order remains semantically different.

7.2 Accessibility

Accessibility means that people with diverse sensory, motor, cognitive, and technological conditions can perceive, operate, understand, and use the interface. Important practices include:

  • Use semantic HTML before adding ARIA.
  • Preserve visible keyboard focus, preferably with `:focus-visible`.
  • Do not communicate information by color alone.
  • Maintain sufficient text and control contrast.
  • Provide labels and instructions for form controls.
  • Ensure controls have usable target areas and clear states.
  • Support zoom, text enlargement, reduced motion, and high-contrast preferences.
  • Test with keyboard navigation, screen readers, automated tools, and real users.

Accessibility is both an ethical and professional responsibility. In many jurisdictions, legal and procurement requirements also apply, commonly drawing on standards such as the Web Content Accessibility Guidelines (WCAG). Compliance should not be treated as a one-time certification; content, components, and browser behavior change over time.

8. Design Systems and Maintainable CSS

A design system combines design principles, tokens, reusable components, usage guidance, and governance. It reduces inconsistent decisions across products and teams.

A basic token layer might define color, spacing, type, and shape:

```css

:root {

--font-body: system-ui, sans-serif;

--color-text: #1f2937;

--color-surface: #ffffff;

--color-action: #075985;

--space-1: 0.25rem;

--space-2: 0.5rem;

--space-4: 1rem;

}

```

Components should have clear responsibilities and predictable states such as default, hover, focus, disabled, loading, success, and error. Naming conventions such as Block-Element-Modifier, utility classes, or component-scoped styles can all work when applied consistently. The important principles are low accidental coupling, understandable ownership, and controlled variation.

Design systems also require governance. Teams must decide who approves new tokens, how components are documented, how breaking changes are communicated, and how accessibility is tested. A large component library can become counterproductive if it prevents legitimate content-specific solutions or conceals poor underlying semantics.

9. Worked Example: A Responsive Course Catalogue

Assume a university wants a course catalogue showing course cards, filters, and enrolment actions. The desktop mock-up has a sidebar of filters and a three-column card grid. On mobile, filters should be accessible without consuming the entire initial viewport, course cards should become a single column, and the enrolment button should remain obvious.

Analysis

The primary user goal is discovering and selecting a course. Therefore, course title, level, schedule, and enrolment action have higher priority than decorative imagery. The layout must handle long course titles, localization, keyboard navigation, and narrow screens. A three-column fixed-width design would fail when the viewport is intermediate or when text increases.

Implementation Strategy

The base layout uses normal flow and one column:

```css

.catalogue {

display: grid;

gap: 1rem;

}

.course-grid {

display: grid;

grid-template-columns: 1fr;

gap: 1rem;

}

.course-card {

display: flex;

flex-direction: column;

gap: 0.75rem;

padding: 1rem;

border: 1px solid #cbd5e1;

border-radius: 0.75rem;

}

.course-card .enrol {

margin-top: auto;

}

@media (min-width: 48rem) {

.catalogue {

grid-template-columns: minmax(13rem, 16rem) 1fr;

align-items: start;

}

.course-grid {

grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr));

}

}

```

The card uses Flexbox so the action can be aligned toward the bottom even when descriptions differ in length. The catalogue uses Grid because it relates a filter region and a content region in two dimensions. The card grid uses `auto-fit` and `minmax()` so it adapts to intermediate widths.

Evaluation

The implementation should be tested at narrow, intermediate, and wide widths, with browser zoom increased, with long translated strings, and using only a keyboard. Testers should verify that focus indicators are visible, filters are labelled, the card heading hierarchy is logical, and the enrolment action remains reachable. Automated testing can identify some issues, but it cannot determine whether users understand the filter terminology or whether the visual hierarchy supports their goals.

Learning Points

The appropriate layout method depends on the relationship being expressed. Mobile-first CSS reduces unnecessary assumptions, while intrinsic sizing handles content variation. UX evaluation must include accessibility and realistic content rather than relying only on a polished visual screenshot.

10. Performance, Security, and Professional Practice

CSS affects performance through stylesheet size, selector matching, layout complexity, and visual effects. Excessive animation, large dependency libraries, and deeply coupled styles can increase maintenance and rendering costs. Prefer efficient transitions, avoid animating layout-heavy properties when a transform or opacity transition is suitable, and respect reduced-motion preferences.

CSS itself is not a complete security boundary. Sensitive data must not be hidden merely with CSS, since hidden content may remain in the document or be exposed through other mechanisms. Content security policies, safe templating, and input handling belong to the broader application security architecture.

Professional development includes design review, browser testing, accessibility testing, responsive regression testing, and documentation. Developers should inspect real devices where possible, but emulators and responsive browser tools remain useful for systematic testing. Performance and accessibility should be treated as acceptance criteria rather than late-stage polish.

11. Contemporary Developments and Limitations

Modern CSS includes container queries, cascade layers, logical properties, subgrid, nesting in supported environments, and increasingly capable color and typography systems. Container queries allow a component to adapt to the size of its containing region rather than the viewport, which is valuable for reusable components:

```css

.card-list {

container-type: inline-size;

}

@container (min-width: 40rem) {

.course-card {

grid-template-columns: 1fr 1fr;

}

}

```

Logical properties such as `margin-inline` and `padding-block` better support right-to-left languages and different writing modes. However, browser support, project requirements, testing capacity, and progressive-enhancement strategies must be considered. New syntax does not automatically produce better UX.

CSS also has inherent limitations. It cannot determine users' goals, replace content strategy, or guarantee accessibility. Responsive layouts can expose contradictions in information architecture, and design tokens can create false consistency when distinct contexts genuinely require different treatment. Good engineering combines CSS knowledge with semantic HTML, interaction design, research, testing, and product judgment.

Chapter Summary

CSS is a rule-based system in which selectors, inheritance, specificity, source order, and custom properties determine presentation. The box model explains the relationship among content, padding, border, and margin, while `box-sizing: border-box` provides predictable sizing. Normal flow should remain the foundation of robust layouts.

Flexbox is primarily a one-dimensional system for distributing and aligning items along axes. Grid is a two-dimensional system for rows, columns, and page structures. Responsive design adapts content and layout to available space and user preferences; mobile-first design begins with essential content and progressively enhances the experience. Media queries should be based on content needs rather than assumed device categories.

UX requires more than visual responsiveness. Usable interfaces communicate status, maintain consistency, prevent errors, support recovery, and respect users' goals. Accessibility requires semantic structure, keyboard support, visible focus, adequate contrast, preference support, and testing with diverse users. Design systems improve consistency when supported by tokens, reusable components, documentation, and governance. Contemporary CSS features such as container queries and logical properties expand responsive possibilities, but sound judgment and evaluation remain essential.

Key Terms

CSS: A stylesheet language used to describe the presentation and layout of structured documents.

Cascade: The process by which competing CSS declarations are resolved.

Specificity: The selector-comparison mechanism used when multiple declarations target the same property.

Inheritance: The transfer of selected property values from an ancestor to a descendant.

Custom property: A CSS variable defined with a double-hyphen name and read with `var()`.

Box model: The model describing content, padding, border, and margin around an element.

Normal flow: The browser's default layout behavior for arranging document content.

Flexbox: A one-dimensional CSS layout model.

Grid: A two-dimensional CSS layout model based on rows and columns.

Main axis: The primary axis along which Flexbox items are arranged.

Breakpoint: A condition at which a layout or style changes, usually based on content needs.

Media query: A conditional CSS rule based on viewport, device, or user-preference features.

Mobile-first design: A strategy that begins with a constrained layout and enhances it for larger contexts.

Responsive design: Design that adapts presentation and interaction to different environments.

User experience: The overall quality of a user's interaction with a product or service.

Usability: The extent to which intended users can achieve goals effectively, efficiently, and satisfactorily.

Accessibility: The practice of making products usable by people with diverse abilities and technologies.

Design system: A governed collection of design principles, tokens, components, and guidance.

Container query: A conditional rule based on the size of a containing element rather than the viewport.

Progressive enhancement: Building a functional baseline and adding capabilities when the environment supports them.

Review Questions

Short Answer Questions

1. What is the purpose of the CSS cascade?

2. Distinguish padding from margin in the box model.

3. When is Flexbox generally more appropriate than Grid?

4. What does mobile-first design mean?

5. Name two accessibility practices relevant to responsive interfaces.

Long Answer Questions

1. Explain how specificity, inheritance, and source order cooperate to determine the final style of an element.

2. Compare Flexbox and Grid, including their axes, typical uses, and ability to work together.

3. Describe a process for selecting responsive breakpoints based on content rather than device labels.

4. Explain how a design system can improve consistency while introducing governance and maintenance challenges.

5. Discuss why visual responsiveness alone does not guarantee good user experience or accessibility.

Analytical / Application Questions

1. A two-column desktop layout causes long headings and buttons to overflow at medium widths. Propose a mobile-first CSS strategy and justify your breakpoint and layout choices.

2. A team uses `position: absolute` for every page section because it matches a desktop mock-up. Analyze the likely failures under zoom, translation, and mobile widths, and recommend a more robust layout approach.

3. Design an evaluation plan for a responsive university form that includes keyboard testing, screen-reader considerations, reduced-motion preferences, realistic content, and usability observation.

Multiple Choice Questions with Answers

Question 1

Which selector has greater specificity than a type selector such as `p`?

A. `p`

B. `.notice`

C. `*`

D. `::before`

Correct Answer: B. `.notice`

Question 2

With `box-sizing: border-box`, what does a declared width normally include?

A. Only the content

B. Only the margin

C. Content, padding, and border

D. Content and margin but not padding

Correct Answer: C. Content, padding, and border

Question 3

Which layout model is primarily one-dimensional?

A. Flexbox

B. Grid

C. Table layout

D. Multi-column layout

Correct Answer: A. Flexbox

Question 4

What is the main purpose of `minmax(15rem, 1fr)` in a Grid track definition?

A. To force a fixed 15rem track

B. To specify minimum and flexible maximum sizing

C. To hide tracks below 15rem

D. To create a Flexbox axis

Correct Answer: B. To specify minimum and flexible maximum sizing

Question 5

Which approach best describes mobile-first responsive design?

A. Designing only for mobile devices

B. Starting with a constrained layout and enhancing it for larger contexts

C. Using only pixel units

D. Using a separate website for every device

Correct Answer: B. Starting with a constrained layout and enhancing it for larger contexts

Question 6

Which media feature allows an interface to respond to a user's reduced-motion preference?

A. `orientation`

B. `resolution`

C. `prefers-reduced-motion`

D. `aspect-ratio`

Correct Answer: C. `prefers-reduced-motion`

Question 7

Which property distributes free space along the Flexbox main axis?

A. `align-items`

B. `justify-content`

C. `align-content`

D. `place-self`

Correct Answer: B. `justify-content`

Question 8

Why should CSS `order` be used cautiously for responsive reordering?

A. It always disables Grid

B. It changes the HTML source order automatically

C. It can create a mismatch between visual order and semantic or keyboard order

D. It prevents all responsive styling

Correct Answer: C. It can create a mismatch between visual order and semantic or keyboard order

Question 9

What is a principal benefit of CSS custom properties?

A. They replace semantic HTML

B. They provide reusable values for consistency and theming

C. They guarantee faster rendering

D. They remove the need for media queries

Correct Answer: B. They provide reusable values for consistency and theming

Question 10

What distinguishes a container query from a typical viewport media query?

A. It responds to the size of a containing element

B. It applies only to images

C. It cannot contain conditions

D. It changes HTML semantics

Correct Answer: A. It responds to the size of a containing element

Web Technologies
Chapter 4 of 14