CSS Foundations and the CascadeIntroductionCascading Style Sheets (CSS) is the language used to control the presentation of HTML documents. HTML describes structure and meaning; CSS describes appearance, spatial arrangement, typography, colour, and responsive presentation. Separating structure from presentation makes websites easier to maintain, reuse, test, and adapt to different devices. CSS is not simply a collection of visual commands. It is a rule system. A browser must determine which declarations apply to an element, which declarations take priority when rules conflict, how values are inherited, and how the resulting values affect layout. Understanding this process is essential for writing predictable stylesheets rather than solving problems through repeated overrides. This chapter develops the foundations required to style web documents systematically. It explains selectors, declarations, units, colour, typography, inheritance, specificity, cascade layers, custom properties, and the CSS box model. It also considers maintainability, accessibility, responsive design, and professional debugging practice. Learning ObjectivesBy the end of this chapter, you should be able to: - construct CSS rules using selectors, properties, and values;
- select elements by type, class, ID, attribute, relationship, and state;
- distinguish inheritance, specificity, source order, and cascade layers;
- choose suitable units, colours, and typographic values;
- explain how the CSS box model determines rendered size;
- use custom properties to create maintainable design systems;
- diagnose conflicting declarations using browser developer tools; and
- apply CSS foundations to a realistic, accessible web interface.
1. The CSS Rule ModelA CSS rule consists of a selector and a declaration block. A declaration is a property followed by a value and terminated by a semicolon. p {
color: #263238;
line-height: 1.6;
}Here, p is the selector. The declarations are color: #263238 and line-height: 1.6. The selector identifies the elements to which the declarations may apply. A stylesheet may be included in three ways: - External stylesheet:
<link rel="stylesheet" href="styles.css">. This is generally preferred because one file can serve multiple pages. - Embedded stylesheet: a
<style> element in the document head. This is useful for page-specific styles. - Inline style: a
style attribute on an element. This has high precedence and is difficult to maintain, so it should be used sparingly.
CSS comments use / comment /. Whitespace is usually insignificant, but consistent formatting improves review and maintenance. 2. SelectorsSelectors form the targeting system of CSS. A selector can identify elements directly or describe relationships and conditions. | Selector | Example | Meaning |
|---|
| Type | h2 | Every h2 element | | Class | .notice | Elements whose class includes notice | | ID | #main-nav | The element with the specified ID | | Universal | * | Every element | | Attribute | input[type="email"] | Email input elements | | Descendant | article p | Paragraphs inside an article at any depth | | Child | nav > a | Links that are direct children of nav | | Adjacent sibling | h2 + p | A paragraph immediately following an h2 | | General sibling | h2 ~ p | Paragraphs following an h2 with the same parent | | Grouped | h1, h2, h3 | All three heading types | | Pseudo-class | a:hover | Links while being pointed at | | Pseudo-element | p::first-letter | The first letter of a paragraph |
Classes are normally the most reusable choice for visual components. IDs are useful for unique document targets and scripting, but styling with IDs can create unnecessarily high specificity. A selector such as .card .title is more specific and less reusable than a component class such as .card-title. Pseudo-classes and pseudo-elementsA pseudo-class describes a state or structural condition: button:hover {
background-color: #155eef;
}
input:focus-visible {
outline: 3px solid #ffbf47;
outline-offset: 2px;
}
li:nth-child(even) {
background-color: #f5f7fa;
}A pseudo-element represents a conceptual part of an element: article p::first-line {
font-weight: 600;
}
.external-link::after {
content: " ↗";
}Interactive states must not be designed only for a mouse. :focus-visible helps keyboard users identify the active control, and colour should not be the sole method of communicating meaning. 3. Declarations, Values, and UnitsCSS properties accept specific value types. A browser generally ignores an invalid declaration rather than guessing the intended meaning. This makes accurate spelling, syntax, and units important. Length unitsCommon absolute and relative units include: | Unit | Category | Typical use |
|---|
px | CSS pixel | Borders, small interface details | % | Relative | Widths or values relative to a containing context | em | Relative | Relative to the element’s inherited font size for many properties | rem | Relative | Relative to the root element’s font size | vw, vh | Viewport-relative | Large-scale responsive dimensions | ch | Character-relative | Text measure, approximately the width of the 0 glyph | fr | Grid fraction | Sharing available grid space |
A CSS pixel is a logical unit, not necessarily one physical screen pixel. Relative units are valuable because they respond to user settings and viewport size. For example: html {
font-size: 100%;
}
.page {
width: min(92%, 70rem);
margin-inline: auto;
padding: 1rem;
}The min() function selects the smaller of its arguments. In this example, the page is 92% of its containing width until that would exceed 70 rem. The margin-inline: auto declaration centres a block when the available layout permits it. Use px when a physically consistent small dimension is useful, such as a border. Use rem for scalable spacing and typography, percentages for fluid relationships, and viewport units carefully because extreme viewport sizes can produce unreadable results. ColoursCSS supports named colours, hexadecimal notation, RGB, HSL, and newer colour functions. Examples include: :root {
--brand: #155eef;
--ink: rgb(31 41 55);
--warning: hsl(38 92% 50%);
}Hexadecimal notation commonly uses six hexadecimal digits for red, green, and blue channels. HSL expresses hue, saturation, and lightness, which can be convenient when developing related colour variations. Colour contrast must be tested rather than judged by appearance alone. Text, controls, and focus indicators should remain perceivable for users with low vision or colour-vision differences. 4. Typography and ReadabilityTypography affects comprehension, hierarchy, and accessibility. Important properties include font-family, font-size, font-weight, line-height, letter-spacing, and text-align. body {
font-family: system-ui, -apple-system, "Segoe UI", sans-serif;
font-size: 1rem;
line-height: 1.5;
color: #1f2937;
}
h1 {
font-size: clamp(2rem, 5vw, 3.5rem);
line-height: 1.1;
letter-spacing: -0.02em;
}A font stack provides fallbacks if the first font is unavailable. Unitless line height, such as 1.5, scales with the element’s font size and is generally robust when nested content changes size. The clamp() function accepts a minimum, preferred, and maximum value, allowing a value to vary without becoming too small or large. Readable line length is also important. A paragraph can use max-width: 70ch to limit the number of approximate characters per line. This is a guideline rather than an exact typographic measurement because glyph widths differ. Web fonts may improve branding but introduce performance, licensing, and privacy considerations. A professional implementation should provide fallbacks, avoid unnecessary font weights, and test loading behaviour. 5. The CascadeThe word cascade describes the procedure used to resolve competing declarations. When several rules target the same property, the browser considers, broadly, the following factors: - origin and importance;
- cascade layer;
- selector specificity; and
- source order.
Declarations that do not conflict can combine. For example, one rule may set colour and another may set margin. The cascade becomes visible when two declarations set the same property. p {
color: navy;
}
p {
color: darkgreen;
}Both rules have equal specificity, so the later declaration wins and the paragraph becomes dark green. Importance and originNormal author styles generally override normal user-agent styles supplied by the browser. The !important annotation changes priority within the cascade: .component {
color: #222 !important;
}Although sometimes necessary for user styles or tightly controlled utility systems, frequent use of !important usually indicates a specificity or architecture problem. It should not be used as a routine debugging technique. SpecificitySpecificity is a comparison mechanism used when declarations are otherwise competing at the same cascade level. A useful conceptual tuple is (a, b, c, d): a: inline style declarations;b: ID selectors;c: classes, attributes, and pseudo-classes;d: type selectors and pseudo-elements.
For example: /* (0, 0, 1, 0) */
.card { color: black; }
/* (0, 1, 0, 0) */
#featured { color: blue; }
/* (0, 0, 1, 1) */
.card p { color: green; }The ID selector outranks the other two because its ID component is higher. Specificity is compared lexicographically; a larger value in an earlier component defeats any number of lower components. This is not ordinary arithmetic addition. The pseudo-class :where() contributes zero specificity, which is useful for deliberately low-specificity defaults. :is() takes the specificity of its most specific argument. These features help component authors create controllable APIs. Cascade layersCascade layers provide an explicit order for groups of rules. Later layers normally outrank earlier layers, while unlayered normal author rules outrank layered normal author rules. A common arrangement is: @layer reset, base, components, utilities;
@layer reset {
*, *::before, *::after { box-sizing: border-box; }
}
@layer base {
body { margin: 0; }
}
@layer components {
.button { padding: 0.75rem 1rem; }
}
@layer utilities {
.text-center { text-align: center; }
}The exact order should be chosen deliberately and documented. Layers allow a utility rule to override a component rule without creating excessively specific selectors. They are especially valuable when integrating third-party stylesheets. Inheritance and initial valuesSome properties inherit from a parent, including color and font-family. Others, such as margin, padding, and border, normally do not. Inheritance is distinct from the cascade: inheritance supplies a value from an ancestor only when the element has no applicable declaration for that property. CSS-wide keywords make value behaviour explicit: inherit: use the parent’s computed value;initial: use the property’s initial value;unset: inherit if the property normally inherits, otherwise use its initial value;revert: return to an earlier cascade origin or browser default where applicable.
Understanding inheritance prevents unnecessary repetition: body {
color: #243447;
font-family: system-ui, sans-serif;
}Most textual descendants can use these values automatically. However, form controls may require explicit font inheritance because browser defaults can differ. 6. Custom PropertiesCustom properties, often called CSS variables, store reusable tokens. Their names begin with two hyphens and are read using var(). :root {
--color-brand: #155eef;
--color-surface: #ffffff;
--space-2: 0.5rem;
--radius-md: 0.5rem;
}
.card {
background: var(--color-surface);
padding: var(--space-2);
border-radius: var(--radius-md);
}Custom properties participate in inheritance. A component can define a local override: .alert {
--alert-color: #9a3412;
color: var(--alert-color);
}Fallbacks are useful when a variable is missing: color: var(--text-color, #1f2937); Custom properties support theming, consistent spacing, and controlled component variation. They are not macro substitution: their values are resolved during CSS value processing, and invalid combinations can cause a declaration to become invalid at computed-value time. Therefore, tokens should be named clearly and tested in every supported context. 7. The CSS Box ModelEvery element is represented, conceptually, by four nested areas: - content: text or child content;
- padding: space between content and border;
- border: the visible edge; and
- margin: space outside the border.
The default box-sizing model is content-box. Under this model, a declared width applies to the content area. For a horizontal dimension, the rendered outer size can be expressed as: Outer width = content width + left padding + right padding + left border + right border + left margin + right margin If margin is excluded, the border-box width is: Border-box width = content width + horizontal padding + horizontal border widths These relationships assume ordinary non-replaced block sizing and do not include effects such as transforms, scrollbars, or layout-specific automatic sizing. Example: .box {
width: 300px;
padding: 20px;
border: 5px solid #333;
margin: 10px;
}With content-box, the border-box width is 300 + 20 + 20 + 5 + 5 = 350 px, and the outer horizontal footprint including margins is 370 px. The content width remains 300 px. Many developers apply this practical reset: *, *::before, *::after {
box-sizing: border-box;
}Under border-box, the declared width includes content, padding, and border. The same element has a 300 px border-box width, with the content area reduced to 250 px after subtracting 40 px of padding and 10 px of border. Margins remain outside the declared width. Vertical margins between adjacent block elements can collapse in some normal-flow situations. Padding and borders do not collapse in the same way. Flex and grid layouts also change many traditional margin interactions. Browser developer tools provide a box-model diagram that is often the quickest way to diagnose unexpected dimensions. 8. A Systematic Styling WorkflowA maintainable workflow separates concerns and reduces accidental conflicts. - Inspect the HTML structure. Use semantic elements such as
header, nav, main, article, and footer. - Establish tokens and base rules. Set colours, typography, box sizing, and broad defaults.
- Style components with classes. Prefer readable component classes over deeply nested selectors.
- Add layout rules. Use flexbox or grid where appropriate, while remembering that CSS foundations determine the box dimensions those layouts distribute.
- Add states and responsive adaptations. Include keyboard focus, hover, disabled states, and media queries.
- Inspect conflicts. In browser tools, examine matched rules, crossed-out declarations, computed values, and inherited values.
- Test accessibility and content variation. Test zoom, long text, keyboard navigation, narrow screens, and high-contrast conditions.
A useful convention is to keep specificity low and predictable. For example, .site-header .nav a may work, but .nav-link is usually easier to override and reuse. Naming systems such as Block–Element–Modifier can also make component relationships explicit, although no naming system replaces sound cascade design. 9. Applied Case: A Responsive Course Portal CardBackgroundThis illustrative case concerns a diploma programme portal containing course cards. The first implementation used inline styles, ID selectors, and repeated hexadecimal colours. A later requirement introduced a dark theme, keyboard-visible focus, and a compact mobile layout. ProblemThe original stylesheet contained rules such as: #course-card-1 a { color: #155eef; }
.course-card a { color: #555; }The ID rule was difficult to override. The page also used width: 300px with padding under the default content-box model, causing cards to overflow their grid. AnalysisThe problems were not caused by a missing colour declaration. They resulted from high specificity, duplicated design values, and an unexamined box-sizing assumption. The solution needed a clear cascade order and reusable tokens. Approach and solution@layer reset, base, components, utilities;
@layer reset {
*, *::before, *::after {
box-sizing: border-box;
}
}
@layer base {
:root {
--surface: #ffffff;
--text: #1f2937;
--brand: #155eef;
--space: 1rem;
}
body {
margin: 0;
color: var(--text);
background: var(--surface);
font-family: system-ui, sans-serif;
line-height: 1.5;
}
}
@layer components {
.course-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr));
gap: var(--space);
width: min(92%, 72rem);
margin-inline: auto;
}
.course-card {
padding: var(--space);
border: 1px solid #d1d5db;
border-radius: 0.5rem;
}
.course-card__link {
color: var(--brand);
font-weight: 700;
}
.course-card__link:focus-visible {
outline: 3px solid #f59e0b;
outline-offset: 3px;
}
}
@layer utilities {
.visually-muted {
color: #4b5563;
}
}The reset establishes predictable width calculations. Base rules define inherited values and tokens. Component rules describe the card without IDs. The utility layer can intentionally override component defaults when needed. The grid’s minmax() function allows cards to share available space while preventing them from becoming too narrow. OutcomeCards now resize without overflow, link styling is consistent, and theme values can be changed centrally. Keyboard users receive a visible focus indicator. The stylesheet is easier to extend because it does not depend on a chain of increasingly specific overrides. Learning pointsThe case demonstrates that CSS quality depends on architecture as well as individual declarations. Cascade layers, custom properties, semantic class names, and deliberate box sizing address different problems and work best together. 10. Limitations, Accessibility, and Professional PracticeCSS cannot correct poor HTML semantics. A visually styled div is not automatically a button, heading, or navigation landmark. Accessibility begins with meaningful structure and continues through focus states, readable contrast, scalable text, sufficient target size, and logical responsive behaviour. Do not remove outlines without providing an equally visible alternative. Avoid fixed heights around unknown content because text expansion and translation can cause clipping. Test at increased browser zoom and with user style preferences. Respect reduced-motion preferences when adding transitions: @media (prefers-reduced-motion: reduce) {
*, *::before, *::after {
scroll-behavior: auto;
transition-duration: 0.01ms;
animation-duration: 0.01ms;
}
}CSS also has security and governance implications. External fonts, stylesheets, and embedded resources may create privacy or supply-chain risks. Organisations should review dependencies, licences, content-security policies, and third-party code. CSS should not be used to misrepresent document order or hide essential information from particular users. Contemporary CSS increasingly supports nesting, cascade layers, container queries, logical properties, and advanced colour functions. These features improve adaptability, but browser support and team familiarity must be considered. Progressive enhancement is preferable to requiring every client to support every new feature. AI-assisted coding can suggest CSS, but generated styles must be reviewed for specificity problems, accessibility failures, browser compatibility, and unnecessary complexity. Chapter SummaryCSS applies presentation through selectors, declarations, properties, and values. Selectors may identify elements by type, class, relationship, attribute, state, or pseudo-element. Units should be selected according to whether a dimension must be fixed, scalable, fluid, or related to text or the viewport. The cascade resolves competing declarations through origin and importance, cascade layers, specificity, and source order. Inheritance supplies values from ancestors for inheritable properties, while CSS-wide keywords allow inheritance and reset behaviour to be controlled explicitly. Custom properties provide reusable, inheritable design tokens and support themes and component variation. The box model comprises content, padding, border, and margin. box-sizing: border-box often produces more predictable component dimensions. Professional CSS uses semantic HTML, low and deliberate specificity, accessible interaction states, responsive units, browser inspection tools, and testing with varied content and user settings. A systematic cascade is more maintainable than a collection of emergency overrides. Key TermsSelector: A pattern that identifies elements to which CSS declarations may apply. Declaration: A property–value instruction such as color: navy. Property: A named aspect of presentation controlled by CSS. Value: The setting assigned to a CSS property. Cascade: The algorithm used to resolve competing CSS declarations. Specificity: The relative selector weight used to decide between competing rules. Inheritance: The process by which some property values pass from an ancestor to a descendant. Cascade layer: A named group of rules with an explicit position in the cascade order. Pseudo-class: A selector component describing a state or structural condition. Pseudo-element: A selector component representing a conceptual part of an element. Custom property: A reusable CSS value whose name begins with --. Fallback: An alternative value supplied when a preferred value is unavailable or invalid. Computed value: A value produced after the browser processes declarations and inheritance. Box model: The content, padding, border, and margin model used to represent elements. Content-box: A box-sizing model in which declared width and height apply to content. Border-box: A box-sizing model in which declared width and height include padding and border. Relative unit: A unit whose size depends on another measurement or context. Specificity tuple: A conceptual (a, b, c, d) comparison of inline, ID, class-like, and type selector components. Design token: A named reusable value representing a design decision such as colour or spacing. Review QuestionsShort Answer Questions- What are the two principal parts of a CSS rule?
- Why are classes generally preferred over IDs for reusable visual styling?
- Name two properties that normally inherit and two that normally do not.
- What is the purpose of
box-sizing: border-box? - What does the
:focus-visible pseudo-class help communicate?
Long Answer Questions- Explain how origin, cascade layers, specificity, and source order work together to resolve conflicting declarations.
- Compare
px, %, em, rem, and viewport units, giving an appropriate use for each. - Describe the CSS box model and explain how
content-box and border-box produce different dimensions. - Explain how custom properties support maintainable themes and component design.
- Describe a professional workflow for diagnosing and correcting a CSS rule that is not producing the expected result.
Analytical / Application Questions- A card has
width: 280px, padding: 16px on both sides, and border: 2px on both sides. Calculate its border-box width under content-box, then explain how the result changes when box-sizing: border-box is applied. - A paragraph is styled by
p, .content p, and #article p. Determine which colour wins when all declarations are in the same layer and origin, and justify the result using specificity. - Design a small cascade-layer structure for a site that uses a reset, base styles, components, and utilities. Explain how your order allows utilities to make deliberate component-level adjustments without relying on
!important.
Multiple Choice Questions with AnswersQuestion 1Which part of a CSS rule identifies the elements to be styled? A. The selector B. The property C. The value D. The semicolon Correct Answer: A. The selector Question 2Which selector targets elements with the class name notice? A. #notice B. .notice C. notice D. *notice Correct Answer: B. .notice Question 3When two normal declarations have equal origin, layer, and specificity, which declaration generally wins? A. The declaration with the shorter property name B. The declaration nearest the HTML doctype C. The later declaration in source order D. The declaration with the darker colour Correct Answer: C. The later declaration in source order Question 4Which property normally inherits from a parent element? A. margin B. border C. padding D. font-family Correct Answer: D. font-family Question 5What does :focus-visible primarily support? A. Keyboard and other modality-aware focus indication B. Automatic image compression C. Selection of every focused descendant D. Removal of all browser focus outlines Correct Answer: A. Keyboard and other modality-aware focus indication Question 6Under the default content-box model, an element has a content width of 300 px, 20 px padding on each side, and 5 px border on each side. What is its border-box width? A. 300 px B. 330 px C. 350 px D. 370 px Correct Answer: C. 350 px Question 7Which declaration makes a custom property use #333 if --text is unavailable? A. color: fallback(--text, #333); B. color: var(--text, #333); C. color: custom(--text, #333); D. color: inherit(--text, #333); Correct Answer: B. color: var(--text, #333); Question 8Which selector has the greatest specificity among these choices? A. p B. .article p C. #article p D. article > p Correct Answer: C. #article p Question 9What is a principal benefit of cascade layers? A. They convert CSS into JavaScript B. They provide an explicit ordering for groups of rules C. They prevent all inheritance D. They automatically optimise images Correct Answer: B. They provide an explicit ordering for groups of rules Question 10Which unit is directly based on the root element’s font size? A. em B. rem C. ch D. vh Correct Answer: B. rem
|