CSS Foundations, Cascade and Box ModelIntroductionCascading Style Sheets (CSS) is the language used to control the presentation of HTML documents. HTML provides structure and meaning; CSS controls visual appearance, layout, spacing, typography, colour, borders and responsive presentation. A useful separation of responsibilities is: - HTML describes what content is.
- CSS describes how that content should appear.
- JavaScript describes behaviour and interaction.
CSS is not merely a collection of visual decorations. It is a rule-based system. The browser reads CSS declarations, determines which declarations apply to each element, resolves conflicts through the cascade, calculates the box model, and then paints the result on the screen. This chapter introduces the foundations required to style practical web pages. It explains selectors, declarations, values and units; colour, typography, backgrounds and borders; inheritance and the cascade; specificity and source order; and the CSS box model. Learning ObjectivesBy the end of this chapter, you should be able to: - Explain the purpose and structure of CSS rules.
- Select elements using common selector types.
- Apply declarations involving units, colours, typography, backgrounds and borders.
- Explain inheritance, specificity, source order and the cascade.
- Calculate the rendered dimensions of a CSS box.
- Diagnose common styling and spacing problems.
- Apply CSS foundations to a small, maintainable web interface.
1. CSS Rules and DeclarationsA CSS rule normally contains a selector and a declaration block: p {
color: #25324a;
line-height: 1.6;
}The selector, p, identifies the elements to which the rule applies. The declarations are the property-value pairs inside the braces. In this example, color and line-height are properties, while #25324a and 1.6 are values. A declaration consists of a property, a colon, a value and a semicolon. The final semicolon is good practice even when technically optional because it makes later editing safer. CSS may be placed in three ways: - External stylesheet: a separate file linked with
<link>. This is normally preferred because styles can be reused and maintained independently. - Internal stylesheet: CSS inside a
<style> element in the document head. This may be suitable for a single document or a small demonstration. - Inline style: a
style attribute on an individual element. Inline styles are difficult to maintain and often create unnecessary specificity problems.
An external stylesheet is commonly linked as follows: <link rel="stylesheet" href="styles.css"> Comments help explain intent without affecting rendering: /* Main navigation links */
.nav-link {
color: navy;
}2. SelectorsA selector identifies elements. Choosing selectors carefully is important for both maintainability and accessibility because predictable styles reduce accidental changes. 2.1 Type, class and ID selectorsA type selector targets an HTML element type: h1 {
font-size: 2rem;
}A class selector begins with a period and can be reused: .card {
border: 1px solid #d0d7de;
}The HTML element can use the class as follows: <article class="card">Course information</article> An ID selector begins with # and targets an element with a matching unique ID: #main-header {
background-color: #102a43;
}IDs should generally be used sparingly for styling. Classes are more reusable and usually produce a more flexible stylesheet. 2.2 Attribute, grouping and universal selectorsAn attribute selector targets elements according to an attribute: input[type="email"] {
border-color: #2563eb;
}A comma groups selectors that share declarations: h1, h2, h3 {
font-family: Arial, sans-serif;
}The universal selector, *, matches all elements. It is often used in a small reset: * {
box-sizing: border-box;
}2.3 Combinators and pseudo-classesCombinators express relationships between elements: .card p { color: #475569; } /* descendant */
.card > h2 { margin-top: 0; } /* direct child */
nav a { text-decoration: none; } /* descendant relationship */A descendant selector applies to an element at any depth inside another element. A child selector, >, applies only to direct children. A pseudo-class represents a state or position: a:hover {
text-decoration: underline;
}
li:first-child {
font-weight: bold;
}
input:focus {
outline: 3px solid #93c5fd;
}Keyboard users must be able to see focus. Removing outlines without providing an equally visible replacement creates an accessibility problem. 3. Values, Units and ColoursCSS values may be keywords, numbers, strings, functions, colours or measurements. Choosing an appropriate unit supports readability and responsive design. 3.1 Common units| Unit | Type | Typical use |
|---|
px | Absolute CSS pixel | Borders, precise small measurements | % | Relative | Widths and proportional spacing | em | Relative to current element font size | Component-scaled spacing | rem | Relative to root font size | Consistent typography and spacing | vw | Relative to viewport width | Fluid sizing, used carefully | vh | Relative to viewport height | Viewport-based sections, used carefully |
A rem is based on the root element's computed font size. If the root font size is 16px, then 2rem computes to 32px. The value of em depends on the relevant element's font size and can compound through nesting. For general spacing systems, rem is often easier to reason about. Percentages depend on the property. A width percentage is usually relative to the containing block's content width, while a percentage height may require a definite parent height to behave as expected. CSS also supports unitless values. For example, line-height: 1.5 is a multiplier of the element's font size and is often preferable to a fixed length. 3.2 Colour notationCSS colours can be written using named colours, hexadecimal notation, RGB functions and HSL functions: color: navy;
color: #1d4ed8;
color: rgb(29 78 216);
color: hsl(221 83% 53%); Modern colour functions may include an alpha component for transparency, such as rgb(29 78 216 / 0.8). Colour should not be the only method of communicating meaning. For example, an error message should include text or an icon as well as a red colour. Sufficient contrast between foreground and background is important for readability. Designers should test colour combinations using accessibility tools rather than relying only on personal perception. 4. TypographyTypography affects readability, hierarchy and the perceived quality of an interface. Important properties include: body {
font-family: system-ui, sans-serif;
font-size: 1rem;
line-height: 1.5;
color: #1f2937;
}
h1 {
font-size: 2rem;
font-weight: 700;
letter-spacing: -0.02em;
}font-family may contain a preferred font followed by fallbacks. A generic family such as sans-serif ensures that the browser can select an available alternative. Common generic families include serif, sans-serif, monospace, cursive and fantasy.
font-size controls text size; font-weight controls thickness; font-style can produce italic text; and text-align controls horizontal alignment. line-height controls vertical separation between lines. A unitless line-height usually scales appropriately when the font size changes.
The font shorthand can combine several properties, but its syntax must be used carefully: body {
font: 400 1rem/1.5 system-ui, sans-serif;
}This represents weight, size, line-height and family. Shorthand declarations may reset omitted subproperties, so longhand declarations can be clearer while learning or when precise control is needed. 5. Backgrounds and BordersBackground properties control the area behind an element's content and padding. They include background-color, background-image, background-repeat, background-position and background-size. .hero {
background-color: #e0f2fe;
background-image: linear-gradient(135deg, #e0f2fe, #dbeafe);
background-size: cover;
background-position: center;
}A background image is decorative in many cases. Meaningful information should normally be represented in HTML text or an image element with suitable alternative text. Borders surround the padding and content area. A border requires at least a style to become visible: .panel {
border: 1px solid #cbd5e1;
border-radius: 0.5rem;
}The border shorthand sets width, style and colour. Individual sides can be styled independently, for example border-bottom. Rounded corners affect the visual shape but do not change the fundamental box-model calculation of width and height. 6. Inheritance, the Cascade and Specificity6.1 InheritanceSome properties are inherited from a parent to its descendants. Text-related properties such as color, font-family and often line-height commonly inherit. Box-model properties such as margin, padding, border and width generally do not inherit. For example: body {
color: #334155;
font-family: system-ui, sans-serif;
}A paragraph inside the body normally receives these inherited values unless another rule overrides them. Inheritance can be controlled with keywords such as inherit, initial, unset and revert. 6.2 The cascadeMore than one rule may apply to the same element. The cascade determines which declaration wins. In practical terms, the browser considers the origin and importance of declarations, selector specificity and source order. Author stylesheets are the styles written by the site developer; user-agent styles are the browser's defaults. The !important flag changes priority, but it should not be used as a routine solution. Excessive use makes the stylesheet difficult to override and maintain. It may be justified in carefully controlled accessibility or utility-system situations, but normal conflicts should be resolved through better selectors and organization. 6.3 SpecificitySpecificity is a comparison mechanism used when declarations compete. A useful conceptual ordering is: - Inline styles
- ID selectors
- Class, attribute and pseudo-class selectors
- Type and pseudo-element selectors
- Source order when competing declarations have equal specificity
For example: p { color: black; }
.notice { color: blue; }
#urgent { color: red; }For <p id="urgent" class="notice">Message</p>, the ID rule wins because it has greater specificity. A class selector usually beats a type selector. Specificity is not a licence to write increasingly complicated selectors; low-specificity, reusable classes are generally easier to maintain. 6.4 Source orderIf two declarations have equivalent priority and specificity, the later declaration wins: .button { background: gray; }
.button { background: steelblue; }The button is steelblue. This is the principle of source order. A well-organized stylesheet uses predictable layers, component sections and media queries rather than relying on accidental ordering. 7. The CSS Box ModelEvery element is represented by a rectangular box. The traditional content-box model contains four areas: - Content: text, image or child layout area.
- Padding: space between content and border.
- Border: visible boundary around padding.
- Margin: external space separating the element from neighbouring boxes.
The default value of box-sizing is content-box. Under this model, a declared width applies only to the content area. The total horizontal outer size is: Outer width = content width + left padding + right padding + left border + right border + left margin + right margin If margins are excluded, the border-box width is: Border-box width = content width + horizontal padding + horizontal border widths With box-sizing: border-box, the declared width includes content, padding and borders. Margins remain outside the declared width. A common foundational rule is: *,
*::before,
*::after {
box-sizing: border-box;
}Worked exampleConsider: .box {
width: 300px;
padding: 20px;
border: 5px solid black;
margin: 10px;
}With the default content-box model, the border-box width is: 300px + 20px + 20px + 5px + 5px = 350px The outer width including margins is: 350px + 10px + 10px = 370px With box-sizing: border-box, the declared 300px includes content, padding and border. The outer width including margins is therefore: 300px + 10px + 10px = 320px The content width in the border-box case is 250px because 300px − 40px padding − 10px border = 250px. These calculations assume fixed horizontal values and no additional transforms or layout effects. Margin collapsingIn normal block flow, adjacent vertical margins can collapse rather than add. For example, the bottom margin of one block and the top margin of the next may combine into a single margin whose size is commonly the larger margin, not their sum. Margin collapsing has rules and exceptions; padding, borders, flex containers and grid containers can prevent it. When predictable internal spacing is required, using parent padding or a layout method such as flexbox or grid is often clearer. 8. Practical Styling WorkflowA disciplined workflow reduces debugging time: - Start with semantic HTML.
- Establish base typography and colour variables.
- Use reusable classes for components.
- Apply a consistent box-sizing rule.
- Add layout and spacing gradually.
- Inspect elements in browser developer tools.
- Check computed styles, not just the source CSS.
- Test keyboard focus, zoom, narrow screens and colour contrast.
CSS custom properties support consistent design decisions: :root {
--color-primary: #1d4ed8;
--color-text: #1f2937;
--space-md: 1rem;
}
.card {
color: var(--color-text);
padding: var(--space-md);
}Custom properties are useful for themes and maintenance. They are not variables in exactly the same sense as variables in a general-purpose programming language; they participate in the CSS cascade and can be changed according to context. 9. Illustrative Case: Styling a Course Information CardBackgroundA training provider needs a course card showing a title, description, duration and enrolment link. The first version uses inline styles, inconsistent spacing and a fixed width that overflows on small screens. ProblemThe card is difficult to maintain because each card has different declarations. A dark background and dark text create poor contrast, and the enrolment link does not display a clear keyboard focus state. AnalysisThe design requires reusable classes, responsive width, consistent spacing, visible borders and accessible interaction states. The card should not depend on an ID selector because many course cards will appear on the same page. Approach and Solution<article class="course-card">
<h2>Front-End Foundations</h2>
<p class="course-card__description">Learn the structure and presentation of web pages.</p>
<p><strong>Duration:</strong> 8 weeks</p>
<a class="course-card__link" href="enrol.html">View course</a>
</article> * {
box-sizing: border-box;
}
.course-card {
width: min(100%, 28rem);
padding: 1.25rem;
color: #172033;
background: #ffffff;
border: 1px solid #cbd5e1;
border-radius: 0.75rem;
box-shadow: 0 0.25rem 0.75rem rgb(15 23 42 / 0.12);
}
.course-card__description {
line-height: 1.5;
}
.course-card__link {
display: inline-block;
padding: 0.6rem 0.9rem;
color: white;
background: #1d4ed8;
border-radius: 0.4rem;
text-decoration: none;
}
.course-card__link:hover,
.course-card__link:focus-visible {
background: #1e40af;
}OutcomeThe component can be reused for multiple courses. box-sizing: border-box makes width calculations predictable, min() prevents unnecessary overflow, and the focus-visible state supports keyboard navigation. The class naming pattern also reduces accidental styling of unrelated paragraphs or links. Learning PointsThe case demonstrates that CSS quality depends on more than appearance. Reusability, source organization, accessibility, responsive sizing and predictable box dimensions are all part of professional front-end work. 10. Challenges, Limitations and Contemporary PracticeCSS is powerful but has complexity. Browser defaults differ, inherited values may be unexpected, and a small specificity mistake can affect many components. Fixed pixel widths may cause overflow, while excessive use of viewport units can produce uncomfortable text sizes. Large stylesheets can become difficult to manage if component boundaries and naming conventions are unclear. Modern CSS includes features such as cascade layers, container queries, logical properties, nesting support in modern browsers, and functions such as clamp(), min() and max(). These features improve adaptability but should be introduced only when the target browser support and team skill level are understood. Logical properties such as margin-inline and padding-block can support writing modes more effectively than only using left and right properties. This is especially relevant for internationalized interfaces. AI-assisted coding tools can suggest CSS, but generated code must be reviewed. Developers remain responsible for checking browser compatibility, security, accessibility, performance and licensing. A tool may produce overly specific selectors, inaccessible colour choices or unnecessary !important declarations. Human testing and professional judgement remain essential. Best Practices- Prefer external stylesheets for reusable site styles.
- Use classes for reusable component styling.
- Keep selector specificity low and predictable.
- Avoid using
!important as a normal debugging method. - Use relative units where they improve flexibility.
- Test colour contrast and keyboard focus.
- Apply
box-sizing: border-box consistently when appropriate. - Inspect computed styles in browser developer tools.
- Organize styles by base rules, components and responsive adaptations.
- Treat CSS as a maintainable system rather than a collection of isolated fixes.
Chapter SummaryCSS is a declarative language that controls the presentation of structured HTML. Rules consist of selectors and declarations. Selectors may target elements by type, class, ID, attributes, relationships or states. CSS values include colours, measurements, keywords and functions; units such as rem, %, em, px, vw and vh serve different purposes. Typography, backgrounds and borders establish visual hierarchy and component identity. Inheritance allows selected properties to pass from parent to descendant, while the cascade resolves competing declarations through priority, specificity and source order. Reusable classes and low-specificity selectors generally produce more maintainable styles. The box model represents content, padding, border and margin. Under content-box, declared width excludes padding and borders; under border-box, declared width includes them. Understanding this distinction is essential for preventing overflow and calculating layout dimensions. Professional CSS also requires accessibility, responsive testing, maintainability and careful use of modern tools. Key TermsSelector: A pattern that identifies the elements to which CSS declarations apply. Declaration: A property-value instruction inside a CSS rule. Property: The aspect of an element being styled, such as color or padding. Value: The setting assigned to a CSS property. Class selector: A reusable selector beginning with a period. ID selector: A selector targeting an element with a matching unique ID. Pseudo-class: A selector representing a state or structural condition, such as :hover. Inheritance: The transfer of selected property values from an ancestor to a descendant. Cascade: The process used to resolve competing CSS declarations. Specificity: The relative priority of selectors when declarations compete. Source order: The position of a declaration in the stylesheet; later equal-priority rules win. Box model: The model describing content, padding, border and margin areas. Content box: The area containing an element's content. Padding: Space between content and border. Border: The boundary surrounding padding and content. Margin: External space outside the border. box-sizing: A property defining how declared width and height are calculated.
Computed style: The final value produced by the browser after CSS rules are resolved. Custom property: A CSS value defined with a name beginning with -- and accessed using var(). Specificity conflict: A situation in which multiple applicable declarations provide different values for the same property. Review QuestionsShort Answer Questions- What are the two main parts of a CSS rule?
- Why are classes generally more reusable than ID selectors for styling?
- Name the four areas of the CSS box model.
- What does inheritance mean in CSS?
- What is the purpose of
box-sizing: border-box?
Long Answer Questions- Explain how the cascade, specificity and source order work together when two rules target the same element.
- Compare
px, %, em and rem, giving an appropriate use for each. - Explain the difference between
content-box and border-box, including their effects on width calculations. - Discuss how typography, colour, background and border choices affect usability and accessibility.
- Describe a professional workflow for diagnosing a CSS rule that does not appear to work.
Analytical / Application Questions- A component has
width: 320px, horizontal padding of 16px on each side, 2px borders on each side and 12px margins on each side. Calculate its outer width under content-box and under border-box. - Given rules for
p, .warning and #critical, determine which colour applies to an element containing all three matching selectors and explain why. - Design a reusable course-card style that remains usable on a narrow screen. Justify your choices of selector type, units, box-sizing, contrast and focus styling.
Multiple Choice Questions with AnswersQuestion 1Which part of a CSS rule identifies the elements to be styled? A. The selector B. The declaration value C. The semicolon D. The comment Correct Answer: A. The selector Question 2Which selector has the greatest specificity among these choices? A. p B. .notice C. #urgent D. [role="alert"] Correct Answer: C. #urgent Question 3Which property commonly inherits from a parent element? A. margin B. border C. color D. width Correct Answer: C. color Question 4Under the default content-box model, does declared width include padding? A. Yes, always B. No, padding is added outside the declared width C. Only when a border is present D. Only for inline elements Correct Answer: B. No, padding is added outside the declared width Question 5What happens when two equal-specificity declarations set the same property? A. The first declaration always wins B. The browser ignores both C. The later declaration normally wins D. The declaration with more spaces wins Correct Answer: C. The later declaration normally wins Question 6Which unit is relative to the root element's font size? A. rem B. em C. vh D. px Correct Answer: A. rem Question 7What is the main purpose of a pseudo-class such as :focus? A. To add an HTML element B. To represent a state or condition C. To define a colour variable D. To calculate margin size Correct Answer: B. To represent a state or condition Question 8A box has content width 300px, horizontal padding of 20px on each side and 5px borders on each side. What is its border-box width under content-box sizing? A. 300px B. 330px C. 350px D. 370px Correct Answer: C. 350px Question 9Which practice generally improves CSS maintainability? A. Using many ID selectors B. Using !important for every override C. Using reusable classes with low specificity D. Writing all styles inline Correct Answer: C. Using reusable classes with low specificity Question 10Why should a keyboard focus state remain visible? A. It increases image resolution B. It helps keyboard users identify the active control C. It changes the box model D. It prevents inheritance Correct Answer: B. It helps keyboard users identify the active control
|