HTML, CSS, JavaScript Basics

Chapter 5
CSS Fundamentals, Cascade and Box Model

Bachelors Program in Full Stack Development
HTML, CSS, JavaScript Basics   •   Bachelor

CSS Fundamentals, Cascade and Box Model

Introduction and Context

Cascading Style Sheets (CSS) is the language used to describe the visual presentation of structured documents. HTML supplies meaning and structure; CSS controls layout, color, typography, spacing, borders, and responsive presentation. In professional frontend development, CSS is not merely a collection of visual commands. It is a rule system in which multiple declarations compete, inherit, and combine according to defined algorithms.

A developer who understands CSS fundamentals can create interfaces that are consistent, accessible, responsive, and maintainable. A developer who relies only on trial and error often produces fragile stylesheets containing unnecessary overrides, excessive specificity, and unexpected layout behavior. This chapter explains the foundations needed to reason about CSS rather than guess at it.

Learning Objectives

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

  • Write selectors and declarations for common interface requirements.
  • Explain the cascade, inheritance, specificity, and cascade layers.
  • Select suitable CSS units, colors, and typographic properties.
  • Use custom properties to create maintainable design systems.
  • Calculate the dimensions of an element using the CSS box model.
  • Diagnose common conflicts involving specificity, source order, and `box-sizing`.
  • Apply CSS professionally with attention to accessibility, responsive design, and maintainability.

1. CSS Rules and the Basic Vocabulary

A CSS rule normally consists of a selector followed by a declaration block:

```css

.card {

color: #222;

padding: 1rem;

}

```

The selector `.card` identifies one or more elements. A declaration contains a property and a value, separated by a colon. Each declaration ends with a semicolon. The declaration block is enclosed in braces.

Important terms include:

  • Property: The aspect being controlled, such as `color` or `margin`.
  • Value: The setting assigned to a property, such as `blue` or `1rem`.
  • Declaration: A property-value pair.
  • Rule set: A selector and its declaration block.
  • Stylesheet: A collection of CSS rules.
  • User agent stylesheet: Default browser styles.
  • Computed value: The value produced after inheritance, cascading, and resolution of functions and variables.
  • Used value: The value applied during layout after contextual calculations.

CSS can be included in an HTML document using an external file, an internal `<style>` element, or an inline `style` attribute. External stylesheets are generally preferred for maintainability and caching:

```html

<link rel="stylesheet" href="styles.css">

```

Comments use `/ ... /`. Whitespace is generally insignificant, but consistent formatting improves code review and maintenance.

2. Selectors

Selectors determine which elements a rule can affect. Common selector categories are as follows.

2.1 Type, class, and ID selectors

```css

p { line-height: 1.6; }

.notice { border-left: 4px solid orange; }

#main-heading { font-size: 2rem; }

```

A type selector targets element names. A class selector begins with a period and is reusable. An ID selector begins with `#` and should identify a unique element. Classes are normally preferable for styling because they support reusable, low-specificity components.

2.2 Attribute selectors

Attribute selectors target attributes or attribute values:

```css

input[type="email"] { border-color: teal; }

a[href^="https"] { text-decoration-thickness: 2px; }

```

`^=` means “starts with,” `$=` means “ends with,” and `*=` means “contains.”

2.3 Combinators

Combinators express relationships between elements:

```css

nav a { color: navy; } / descendant /

.card > h2 { margin-top: 0; } / direct child /

h2 + p { margin-top: 0; } / adjacent sibling /

h2 ~ p { color: #555; } / later sibling /

```

The descendant selector can affect deeply nested content, so component styles should be scoped carefully.

2.4 Pseudo-classes and pseudo-elements

Pseudo-classes describe a state or structural condition:

```css

button:hover { background: #0645ad; }

input:focus-visible { outline: 3px solid orange; }

li:first-child { font-weight: bold; }

```

Pseudo-elements represent a conceptual part of an element:

```css

.required::after {

content: " *";

color: crimson;

}

```

Interactive states must not be designed solely with `:hover`, because touch devices may not provide hover. Keyboard users require visible focus indicators, especially `:focus-visible`.

2.5 Functional selectors

Selectors such as `:is()`, `:where()`, and `:not()` support expressive styling:

```css

:is(h1, h2, h3) { font-family: Georgia, serif; }

:where(.card h2) { margin-block: 0; }

```

`:where()` deliberately contributes zero specificity, making it useful for defaults that should be easy to override. `:is()` takes the specificity of its most specific argument.

3. Declarations, Values, and Units

CSS values may be keywords, numbers, lengths, percentages, colors, functions, or lists. A property defines which value types are valid. Invalid declarations are ignored rather than partially interpreted.

3.1 Length units

Absolute units include `px`, `pt`, `cm`, `mm`, and `in`. On screens, `px` is a CSS pixel rather than necessarily one physical device pixel. `px` is useful for borders and precise interface details, but excessive fixed sizing can harm responsiveness.

Relative units include:

  • `em`: relative to the computed font size of the relevant element; in some properties it depends on the parent or current element.
  • `rem`: relative to the root element’s font size.
  • `%`: relative to a property-specific containing dimension.
  • `vw` and `vh`: one percent of the viewport width and height respectively.
  • `vmin` and `vmax`: one percent of the smaller or larger viewport dimension.
  • `ch`: approximately the width of the “0” glyph in the current font.

For example, `max-width: 65ch` often produces a readable line length. However, `em` can compound through nesting, whereas `rem` gives a more stable global scale.

Modern functions provide controlled flexibility:

```css

.title { font-size: clamp(1.5rem, 1rem + 2vw, 3rem); }

```

`clamp(minimum, preferred, maximum)` keeps the computed value within stated bounds. The preferred expression is not guaranteed to be used if it falls outside those bounds.

3.2 Percentages and viewport dimensions

Percentages are not universally relative to the viewport. For example, a block’s percentage width is generally calculated from its containing block’s width, while percentage padding has historically been resolved against the containing block’s width even for vertical padding. Developers should consult property-specific definitions rather than assume a universal reference dimension.

3.3 Colors

CSS supports named colors, hexadecimal notation, RGB, HSL, and newer color functions:

```css

.alert { color: rgb(130 20 20); }

.success { color: hsl(140 60% 30%); }

```

Alpha transparency can be expressed using `/`, as in `rgb(0 0 0 / 0.15)`. Color choice must consider contrast, color-vision differences, and meaning conveyed without color. A success state should not be communicated only through green; text or an icon should reinforce it.

4. Typography and Text Presentation

Typography affects readability, hierarchy, identity, and layout. Important properties include `font-family`, `font-size`, `font-weight`, `font-style`, `line-height`, `letter-spacing`, `text-align`, and `text-decoration`.

A font stack supplies fallbacks:

```css

body {

font-family: Inter, Arial, sans-serif;

font-size: 1rem;

line-height: 1.5;

}

```

The browser attempts the first available font and proceeds through the list. Generic families such as `serif`, `sans-serif`, and `monospace` provide a final category fallback.

Unitless line height is often robust because it scales with the element’s font size. For example, `line-height: 1.5` means the line box is approximately 1.5 times the computed font size. Extremely tight line spacing reduces readability, while excessive spacing can weaken visual grouping.

Web fonts may be loaded using `@font-face`, but performance, licensing, privacy, and fallback behavior must be considered. A text font should support the languages and characters required by the audience. The CSS `font-display` descriptor can influence whether text is shown immediately or waits for a web font.

5. The Cascade, Inheritance, and Specificity

The word “cascading” describes how the browser resolves competing declarations. The result is not determined by the last line alone. Broadly, the browser considers origin and importance, cascade layers, specificity, scoping proximity where applicable, and source order. A declaration that does not match the element or is invalid is not a candidate.

5.1 Inheritance

Some properties inherit by default. Text-related properties such as `color` and `font-family` commonly inherit from a parent. Box-model properties such as `margin`, `padding`, and `border` do not normally inherit.

The global keywords clarify behavior:

  • `inherit`: use the parent’s computed value.
  • `initial`: use the property’s initial value.
  • `unset`: inherit if the property naturally inherits; otherwise use its initial value.
  • `revert`: roll back to a previous cascade origin, often restoring browser or user styles.
  • `revert-layer`: roll back within cascade-layer logic.

Inheritance is useful for establishing document-wide defaults, but overly broad rules can create unintended effects. A reset or base stylesheet should be deliberate rather than destructive.

5.2 Specificity

Specificity is a comparison mechanism used when declarations compete within the same relevant cascade conditions. It is commonly represented as four conceptual components: inline styles, ID selectors, class/attribute/pseudo-class selectors, and type/pseudo-element selectors. For example:

```css

#profile .name { color: navy; } / ID + class /

.card p { color: gray; } / class + type /

```

The first selector has greater specificity and normally wins if both declarations apply to the same property. Specificity is compared lexicographically, not by simply adding arbitrary points. An ID component outweighs any number of class components in ordinary specificity comparison.

The universal selector `*`, combinators, and `:where()` contribute zero specificity. `:is()`, `:not()`, and `:has()` take the specificity of their most specific argument. Inline styles participate at a high level, but `!important` changes the importance order and should not be used as a routine repair technique.

5.3 Cascade layers

Cascade layers provide an explicit ordering mechanism for groups of rules:

```css

@layer reset, base, components, utilities;

@layer base {

body { margin: 0; color: #222; }

}

@layer components {

.button { padding: .6rem 1rem; }

}

```

For normal declarations, later layers have precedence over earlier layers. This ordering is considered before selector specificity, so a low-specificity rule in a later layer can defeat a highly specific rule in an earlier layer. This helps prevent specificity escalation in large applications. Unlayered normal styles generally have precedence over layered normal styles, so teams must establish conventions deliberately.

6. Custom Properties and Design Tokens

Custom properties, often called CSS variables, store reusable values:

```css

:root {

--color-primary: #155eef;

--space-md: 1rem;

--radius-card: .75rem;

}

.card {

color: var(--color-primary);

padding: var(--space-md);

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

}

```

Unlike preprocessor variables, custom properties participate in the cascade and can be changed at runtime. They inherit by default. A fallback can be supplied:

```css

color: var(--text-color, #222);

```

A custom property is substituted largely at computed-value time. Consequently, a value can be syntactically accepted when declared but become invalid after substitution. This is one reason meaningful naming and testing are important.

Custom properties support themes and component configuration:

```css

.theme-dark {

--surface: #121212;

--text: #f5f5f5;

}

```

They should represent design decisions, not every incidental measurement. A small token system is easier to govern than hundreds of unexplained variables.

7. The CSS Box Model

Every rendered element is represented conceptually by a box consisting of content, padding, border, and margin. The content area contains text or replaced content. Padding creates internal space. The border surrounds padding. Margin creates external space between the element and neighboring boxes.

The default `box-sizing` value is `content-box`. With `content-box`, a declared `width` applies to the content area only. If an element has width `300px`, horizontal padding of `20px` on each side, and borders of `2px` on each side, its outer border-box width is:

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

The general equation for horizontal outer size under `content-box` is:

`outer width = content width + left padding + right padding + left border + right border + left margin + right margin`.

If margin is excluded, the result is the border-box width. This equation assumes ordinary non-replaced box dimensions and does not include transformations, outlines, or effects that do not occupy layout space.

With `border-box`, the declared width includes content and padding and border:

```css

, ::before, *::after {

box-sizing: border-box;

}

```

Under this convention, a `300px` width remains `300px` through the border edge, and the content area becomes smaller as padding and border are added. This convention usually makes responsive layout easier to reason about, although it does not eliminate all sizing complexities.

Margins can collapse in normal block flow. In a common case, the vertical margins of adjacent block elements collapse to the larger margin rather than adding together. Margins between a parent and first or last child can also collapse when no border, padding, inline content, or other separating mechanism prevents it. Margin collapse does not occur in flex or grid containers in the same way. Developers should understand this behavior before adding arbitrary spacing fixes.

`min-width`, `max-width`, `min-height`, and `max-height` constrain used dimensions. A child’s percentage height may require a definite height on its containing block. `overflow` controls content that exceeds the box, but hiding overflow can conceal keyboard focus or essential information and should be used carefully.

8. A Worked Styling Example

Consider:

```html

<article class="card">

<h2>Accessible Design</h2>

<p>Good interfaces communicate clearly with every user.</p>

<a class="button" href="/learn">Learn more</a>

</article>

```

A maintainable stylesheet might be:

```css

:root {

--surface: white;

--text: #1f2937;

--accent: #155eef;

--space: 1rem;

}

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

.card {

max-width: 32rem;

padding: calc(var(--space) * 1.5);

color: var(--text);

background: var(--surface);

border: 1px solid #d0d5dd;

border-radius: .75rem;

}

.card h2 { margin-block-start: 0; }

.button {

display: inline-block;

padding: .6rem 1rem;

color: white;

background: var(--accent);

border-radius: .4rem;

text-decoration: none;

}

.button:focus-visible {

outline: 3px solid #f59e0b;

outline-offset: 3px;

}

```

The universal `box-sizing` rule makes the card’s maximum width include its padding and border. The custom properties centralize the color and spacing decisions. The heading’s top margin is removed to avoid unwanted space at the card’s edge. The link is styled as an interactive control while retaining semantic HTML. The focus rule supports keyboard navigation and does not remove the browser’s focus indication without replacement.

9. Illustrative Case: Styling a University Course Portal

Background

A fictional university course portal contains cards for modules, announcements, and assessments. Initially, each feature team writes its own CSS. The result includes repeated colors, inconsistent spacing, rules such as `#portal .module h2`, and frequent uses of `!important`.

Problem

A redesign requires a dark theme, mobile-friendly cards, readable text, and a consistent visual identity. Existing overrides make changes unpredictable. Some cards exceed the viewport because their declared widths exclude padding.

Analysis

The principal causes are uncontrolled specificity, no documented design tokens, inconsistent box sizing, and insufficient attention to inheritance. The team maps styles into reset, base, components, and utilities layers. It also identifies which values represent decisions: brand color, surface colors, spacing scale, border radius, and type scale.

Approach and Solution

The team defines layer order and custom properties:

```css

@layer reset, base, components, utilities;

@layer reset {

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

}

@layer base {

:root {

--space-1: .5rem;

--space-2: 1rem;

--surface: #fff;

--text: #172033;

}

body { margin: 0; color: var(--text); background: var(--surface); }

}

```

Components use classes rather than IDs. Responsive rules use flexible widths, `max-width`, and wrapping rather than fixed viewport assumptions. Focus states remain visible, and color contrast is tested with an automated tool and manual keyboard review. The team replaces most `!important` declarations by correcting layer order and selector design.

Outcome

The redesign produces predictable overrides, consistent spacing, and cards that fit their containers. Theme changes require updating a small set of tokens. The stylesheet becomes easier to review because component rules have limited specificity and each layer has a defined purpose.

Learning Points

CSS architecture is an engineering concern. Cascade layers do not replace good naming, but they make intended precedence explicit. Custom properties support shared decisions, while `box-sizing` and flexible constraints reduce layout surprises. Accessibility testing must accompany visual refinement.

10. Challenges, Limitations, and Professional Practice

CSS is powerful but context-dependent. A value that works in one writing direction or language may not work in another. Logical properties such as `margin-inline`, `padding-block`, and `border-inline-start` support internationalization better than assuming left and right. Dynamic viewport sizes on mobile devices complicate `vh`; newer viewport units such as `svh`, `lvh`, and `dvh` address different viewport states, but browser support and design intent must still be considered.

Use semantic HTML before styling. Avoid using CSS to disguise incorrect structure, such as making a non-button element behave as a button without keyboard and accessibility semantics. Do not remove outlines merely to achieve a visual effect. Test zoom, high contrast settings, reduced motion preferences, keyboard navigation, touch interaction, and narrow screens.

A maintainable stylesheet generally has low or moderate specificity, predictable layers, meaningful class names, grouped tokens, limited nesting, and comments explaining decisions rather than obvious syntax. Browser developer tools should be used to inspect matched rules, computed values, box dimensions, and layout overlays. Automated linting and visual regression testing can detect errors, but neither replaces human accessibility and usability evaluation.

AI-assisted coding can generate plausible CSS, but generated rules may contain excessive specificity, inaccessible colors, obsolete hacks, or assumptions about browser behavior. Developers remain responsible for testing, licensing of supplied assets, privacy implications of external fonts, and the correctness of the final implementation.

Chapter Summary

CSS styles structured documents through selectors, declarations, values, and rule sets. Selectors range from simple type and class selectors to combinators, attribute selectors, pseudo-classes, and functional selectors. Units should be chosen according to context: `rem` supports consistent scales, percentages depend on the relevant containing dimension, and viewport units support fluid layouts with limitations.

The cascade resolves competing declarations through origin and importance, layers, specificity, and source order. Inheritance supplies values from ancestors for selected properties. Custom properties provide cascade-aware design tokens and enable themes. The box model explains how content, padding, border, and margin determine layout dimensions; `border-box` is a useful convention for predictable sizing. Professional CSS also requires accessibility, responsive behavior, internationalization, testing, and disciplined architecture.

Key Terms

CSS: Language for describing the presentation of structured documents.

Selector: Pattern identifying elements to which declarations may apply.

Declaration: A property-value pair in a CSS rule.

Property: Named aspect of presentation being controlled.

Cascade: Algorithm for resolving competing applicable declarations.

Inheritance: Transfer of selected computed values from parent to descendant.

Specificity: Selector comparison mechanism used in conflicts.

Cascade layer: Explicit group that controls precedence among rule groups.

Custom property: Cascade-aware property beginning with `--` and read using `var()`.

Computed value: Value produced after cascading and value resolution.

Box model: Content, padding, border, and margin structure of an element.

Content box: Area containing an element’s content.

Border box: Area extending through content, padding, and border.

`box-sizing`: Property defining how declared dimensions are interpreted.

Margin collapse: Combining of certain adjoining vertical margins in normal flow.

Specificity escalation: Increasing selector complexity to force precedence.

Design token: Named reusable value representing a design decision.

Pseudo-class: Selector describing a state or structural condition.

Pseudo-element: Selector representing a conceptual part of an element.

Containing block: Reference box used to calculate dimensions and positions.

Review Questions

Short Answer Questions

1. What are the two principal parts of a CSS rule set?

2. Distinguish `em` from `rem`.

3. Which parts of the box model normally contribute to an element’s outer width?

4. What is the purpose of a custom property fallback in `var()`?

5. Why are visible focus indicators important?

Long Answer Questions

1. Explain how inheritance, specificity, cascade layers, and source order interact when resolving competing declarations.

2. Compare `content-box` and `border-box`, including a numerical example of the resulting dimensions.

3. Discuss how custom properties can support a maintainable design-token system and theme switching.

4. Explain the advantages and risks of using classes, IDs, attribute selectors, and combinators in a large application.

5. Describe a professional process for making a CSS component responsive and accessible.

Analytical / Application Questions

1. An element has `width: 280px`, horizontal padding of `16px` on each side, and a `1px` border on each side under `content-box`. Calculate its border-box width and explain how the result changes under `border-box`.

2. A low-specificity rule in a later cascade layer conflicts with a highly specific rule in an earlier layer. Predict which normal declaration wins and justify the answer using cascade order.

3. Design a small CSS architecture for a course portal containing a reset, base typography, cards, buttons, and utilities. Specify layer order, token examples, and two accessibility checks.

Multiple Choice Questions with Answers

Question 1

Which selector targets elements with the class name `notice`?

A. #notice

B. .notice

C. notice

D. *notice

Correct Answer: B. .notice

Question 2

What does `rem` normally measure relative to?

A. The viewport width

B. The parent element's width

C. The root element's font size

D. The current element's border width

Correct Answer: C. The root element's font size

Question 3

Which property normally inherits by default?

A. margin

B. padding

C. border

D. font-family

Correct Answer: D. font-family

Question 4

What is the main purpose of a cascade layer?

A. To compress CSS files

B. To define precedence among groups of rules

C. To create HTML elements

D. To convert pixels to percentages

Correct Answer: B. To define precedence among groups of rules

Question 5

Under the default `content-box` model, an element has a content width of 300px, 20px horizontal padding on each side, and 2px borders on each side. What is its border-box width?

A. 300px

B. 340px

C. 344px

D. 384px

Correct Answer: C. 344px

Question 6

Which syntax correctly reads a custom property named `--accent`?

A. value(--accent)

B. var(--accent)

C. custom(--accent)

D. use(--accent)

Correct Answer: B. var(--accent)

Question 7

Which selector contributes zero specificity by design?

A. :is(.card)

B. :where(.card)

C. .card

D. #card

Correct Answer: B. :where(.card)

Question 8

What is a primary accessibility reason for using `:focus-visible` styles?

A. They make images load faster

B. They provide keyboard users with a visible focus indication

C. They remove all browser defaults

D. They prevent inheritance

Correct Answer: B. They provide keyboard users with a visible focus indication

Question 9

Which declaration makes a declared width include content, padding, and border?

A. box-sizing: content-box

B. width-model: border-box

C. box-sizing: border-box

D. display: border-box

Correct Answer: C. box-sizing: border-box

Question 10

Which statement about CSS percentages is correct?

A. Every percentage is relative to the viewport

B. Every percentage is relative to the root font size

C. Their reference dimension depends on the property and layout context

D. Percentages can only be used for colors

Correct Answer: C. Their reference dimension depends on the property and layout context

HTML, CSS, JavaScript Basics
Chapter 5 of 15