CSS, Layout and Responsive DesignIntroductionCascading Style Sheets (CSS) is the language used to describe the presentation of HTML documents. Whereas HTML defines structure and meaning, CSS controls visual appearance, spacing, typography, positioning, and adaptation to different screen sizes. Effective frontend development requires more than memorising properties: developers must understand how the browser resolves competing declarations, calculates dimensions, lays out elements, and responds to changes in viewport size. A responsive interface remains usable across phones, tablets, laptops, and large displays. It should support readable text, accessible controls, logical information hierarchy, and efficient interaction without requiring users to zoom or scroll unnecessarily in two directions. This chapter develops the essential CSS concepts needed to create such interfaces using the cascade, specificity, inheritance, the box model, typography, colour, Flexbox, Grid, media queries, and mobile-first design. Learning ObjectivesBy the end of this chapter, you should be able to: - explain how the cascade, specificity, inheritance, and source order determine a CSS result;
- calculate the dimensions of elements using the CSS box model;
- select suitable typography, colour, spacing, and measurement units;
- use Flexbox for one-dimensional alignment and Grid for two-dimensional layout;
- apply media queries and mobile-first techniques to responsive interfaces;
- diagnose common layout failures using browser developer tools; and
- evaluate responsive designs for usability, accessibility, maintainability, and performance.
1. The CSS Mental ModelA CSS rule consists of a selector and one or more declarations. A declaration contains a property and a value. .card {
padding: 1rem;
background-color: #ffffff;
}The selector .card identifies elements. padding and background-color are properties, while 1rem and #ffffff are values. The browser parses the stylesheet, matches selectors to elements, resolves conflicts, computes values, and then paints the result. Three related ideas are central: - The cascade determines which applicable declaration wins.
- Specificity gives selectors different weights when declarations compete.
- Inheritance allows some properties to obtain their values from an ancestor.
These mechanisms are independent. A declaration may win because it has greater importance, greater specificity, or later source order; inheritance applies only to properties that inherit and only when an element has no overriding value of its own. The cascadeIn ordinary author stylesheets, the browser considers declarations in approximately this order: - relevance: does the selector match and does a condition such as a media query apply?
- origin and importance: for example, user-agent, user, or author rules, including
!important rules; - specificity: how specifically does the selector identify the element?
- scoping proximity where relevant;
- source order: if earlier criteria are tied, the later declaration wins.
!important should not be used as a routine repair mechanism. It reverses some normal precedence relationships and makes later maintenance difficult. A better approach is usually to reduce selector complexity, remove unnecessary competing rules, or reorganise component styles.
SpecificitySpecificity is commonly described using four components: inline styles, ID selectors, class/attribute/pseudo-class selectors, and type/pseudo-element selectors. For example: p { color: black; }
.notice { color: blue; }
#warning { color: red; }For <p id="warning" class="notice">Text</p>, the ID selector normally outranks the class and type selectors, so the text is red. Specificity is not simply the number of selectors. One ID is not defeated by many type selectors. The universal selector * and combinators do not add specificity. Good practice is to keep selectors short and predictable. Component classes such as .card__title are generally easier to maintain than deeply nested selectors such as .page main section article h2. Inheritance and initial valuesProperties such as color, font-family, and line-height commonly inherit. Properties such as margin, padding, border, and width generally do not. The values inherit, initial, unset, and revert allow a developer to control this behaviour explicitly. A robust base style often establishes inherited typography on the root element and then lets components override it selectively: :root {
font-family: system-ui, sans-serif;
line-height: 1.5;
color: #202124;
}2. The Box ModelEvery element is represented by a rectangular box containing four conceptual areas: content, padding, border, and margin. Padding separates content from the border; margin separates the border from neighbouring boxes. With the default content-box model, declared width applies only to the content area. The rendered outer width is: 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 These relationships assume physical horizontal sides and no transformations or unusual layout effects. All lengths must use compatible CSS units; the browser converts relative units such as rem and percentages during computation. For example, an element with width: 300px, horizontal padding of 20px on each side, and a 2px border on each side has a border-box width of: 300 + 20 + 20 + 2 + 2 = 344px.
If each horizontal margin is 16px, its outer occupied width becomes 376px. Most projects use: *,
*::before,
*::after {
box-sizing: border-box;
}With border-box, declared width includes content, padding, and border. This makes percentage widths and component sizing more intuitive. The rule does not make margins part of the declared width. Width, height, overflow, and margin collapsemin-width, max-width, min-height, and max-height constrain sizing. A common responsive image rule is:
img {
display: block;
max-width: 100%;
height: auto;
}This prevents an image from exceeding its containing block while preserving its intrinsic aspect ratio. Content may overflow when it is wider or taller than its box. overflow: auto can provide scrolling, but horizontal scrolling should not be used to hide a poorly designed responsive layout. Vertical margins of adjacent block elements can sometimes collapse; padding, borders, flex containers, and grid containers change that behaviour. Understanding margin collapse helps explain why adding a border or display: flow-root may alter apparent spacing. 3. Typography, Colour, and UnitsTypography affects both visual hierarchy and usability. Important properties include font-family, font-size, font-weight, line-height, letter-spacing, and text-align. A font stack should provide fallbacks: body {
font-family: Inter, Arial, sans-serif;
font-size: 1rem;
line-height: 1.5;
}A relative unit such as rem is based on the root element’s font size, while em is generally based on the current element’s computed font size. Percentages depend on the property and containing context. vw and vh refer to viewport dimensions, but text sized solely with viewport units may become too small or too large. The clamp() function can establish a flexible range: h1 {
font-size: clamp(2rem, 5vw, 4rem);
}This expresses a minimum, preferred fluid value, and maximum. It does not guarantee ideal typography by itself; line length and user zoom must still be tested. For comfortable reading, paragraphs should not become excessively wide. A maximum width expressed in characters is often useful: .prose {
max-width: 70ch;
}Colour should communicate hierarchy while preserving sufficient contrast between text and its background. Colour must not be the only means of conveying status; icons, text, patterns, or position may be needed for users with colour-vision differences. Focus indicators must remain visible, and removing the browser’s outline without supplying an equivalent indicator is harmful. CSS supports named colours, hexadecimal notation, rgb(), hsl(), and newer colour functions. Design tokens reduce inconsistency: :root {
--color-primary: #1457a6;
--color-surface: #ffffff;
--space-unit: 0.25rem;
}
.button {
background: var(--color-primary);
padding: calc(var(--space-unit) * 3);
}Custom properties inherit by default and can be overridden in a component or media query. They are useful for themes, spacing systems, and consistent design decisions. 4. Normal Flow and PositioningIn normal flow, block elements generally stack vertically and inline content flows within lines. The browser allocates space according to the formatting context. Modern layout should usually be built with normal flow, Flexbox, or Grid rather than extensive absolute positioning. The position property provides special behaviour: static is the default;relative remains in flow but can be visually offset and can establish a positioning context;absolute is removed from normal flow and positioned relative to an appropriate containing block;fixed is positioned relative to the viewport in common cases; andsticky behaves like relative positioning until a scrolling threshold is reached.
Absolute positioning is appropriate for overlays, badges, and icons inside a deliberately positioned component. It is not generally appropriate for arranging an entire page because content changes, zoom, and translation can cause overlap. 5. Flexbox: One-Dimensional LayoutFlexbox arranges items along a main axis and a cross axis. The container is made flexible using display: flex or display: inline-flex. .navigation {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
flex-wrap: wrap;
}flex-direction determines whether the main axis is a row or column. justify-content distributes items along the main axis, while align-items aligns them on the cross axis. gap creates consistent spacing without requiring margin calculations. flex-wrap permits items to move onto additional lines.
The item properties flex-grow, flex-shrink, and flex-basis determine how available space is distributed. The shorthand flex: 1 commonly means that items may grow and shrink with a basis of zero, although exact computed behaviour should be understood when precise sizing matters. order changes visual order and can create accessibility problems if it differs substantially from the meaningful reading and focus order. Flexbox is especially suitable for navigation bars, button groups, media objects, rows of controls, and layouts where content determines item size. It is less suitable than Grid when both rows and columns must align across a complete structure. 6. CSS Grid: Two-Dimensional LayoutGrid defines columns and rows simultaneously. A basic responsive card layout is: .card-list {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr));
gap: 1.5rem;
}repeat() avoids repetition, minmax() establishes a lower and upper track size, auto-fit places as many tracks as fit, and 1fr distributes available free space. The result is often responsive without a breakpoint.
Grid can also express named page regions: .page {
display: grid;
grid-template-columns: 16rem 1fr;
grid-template-areas: 'sidebar main';
gap: 2rem;
}
.sidebar { grid-area: sidebar; }
.main { grid-area: main; }At a narrow width, the structure can change: @media (max-width: 48rem) {
.page {
grid-template-columns: 1fr;
grid-template-areas: 'main' 'sidebar';
}
}Grid placement can be explicit or automatic. Explicit placement is useful for dashboards and editorial compositions, while automatic placement generally adapts better to changing content. Developers should test long titles, missing images, translated text, and increased browser font sizes. 7. Responsive Design and Media QueriesResponsive design treats the viewport and device capabilities as variable conditions rather than designing one fixed desktop canvas. A media query applies declarations only when its condition is true: @media (min-width: 48rem) {
.header {
padding-inline: 2rem;
}
}Useful features include min-width, max-width, orientation, prefers-reduced-motion, prefers-color-scheme, and pointer or hover capabilities. Breakpoints should be chosen when the content requires a change, not merely copied from device labels. A mobile-first stylesheet begins with the simplest narrow layout and adds enhancements for larger available spaces: .container {
width: min(100% - 2rem, 72rem);
margin-inline: auto;
}
.layout {
display: grid;
gap: 1rem;
}
@media (min-width: 48rem) {
.layout {
grid-template-columns: 2fr 1fr;
gap: 2rem;
}
}This approach usually produces a smaller baseline, prioritises essential content, and reduces overrides. It is not a rule that every mobile layout must be single-column; it is a strategy for starting with constrained conditions and progressively enhancing the interface. The viewport meta element is essential for mobile browsers: <meta name='viewport' content='width=device-width, initial-scale=1'> Responsive design also includes responsive images, touch targets, keyboard operation, zoom support, and content reflow. A layout that technically fits a screen but creates tiny controls or unreadable text is not responsive in a meaningful user-centred sense. 8. A Practical Design and Debugging MethodA reliable workflow is more valuable than trial-and-error editing. - Identify semantic HTML structure and content priorities.
- Establish global box sizing, typography, colour tokens, and base spacing.
- Build the narrow layout in normal flow.
- Use Flexbox for one-dimensional relationships and Grid for two-dimensional relationships.
- Add breakpoints only when the content becomes crowded or inefficient.
- Test at intermediate widths, not only at named device sizes.
- Inspect computed styles, box dimensions, and layout overlays in developer tools.
- Test keyboard navigation, zoom, screen readers where possible, reduced motion, and long or translated content.
When an element is unexpectedly sized, inspect box-sizing, padding, borders, min-width, and intrinsic content size. When a declaration appears ineffective, check whether the selector matches, the media query is active, another rule has greater specificity, or the property is inherited differently than expected. When a flex item overflows, consider its automatic minimum size and whether min-width: 0 is appropriate for that item. Applied Case: Responsive Course DashboardBackgroundThis illustrative case concerns a fictional training provider whose course dashboard was designed for a 1440-pixel desktop display. The dashboard contained a sidebar, course cards, progress indicators, and a notification panel. ProblemOn phones, the sidebar consumed most of the viewport, cards overflowed horizontally, long course titles pushed buttons outside their containers, and colour alone indicated overdue work. Keyboard users also lost a visible focus indicator. AnalysisThe original implementation used fixed widths, absolute positioning for card controls, and several highly specific selectors. The card grid had four fixed columns, while images were assigned fixed dimensions. The design therefore assumed a particular viewport and content length. Approach and solutionThe redesign used semantic sections and a mobile-first structure. The sidebar moved below the primary content at narrow widths and became a first-column region on larger screens. Course cards used repeat(auto-fit, minmax(16rem, 1fr)). Images received max-width: 100% and height: auto. Card content used Flexbox so action controls remained aligned without absolute positioning. The team introduced custom properties for surface, text, warning, and spacing values. Overdue courses used a text label and icon in addition to colour. Focus styles were retained and strengthened. A prefers-reduced-motion query disabled non-essential transitions. The team tested at 320px, 768px, 1024px, and 1440px widths, plus intermediate widths and 200% zoom. OutcomeThe dashboard no longer required horizontal scrolling at tested widths, course cards expanded and contracted with available space, and content remained usable when titles were substantially longer. The CSS became easier to maintain because component selectors were less specific and layout responsibilities were separated. Learning pointsThe principal lesson is that responsive design is a combination of layout technique, content prioritisation, accessibility, and testing. A media query alone cannot correct a rigid information architecture. Flexible intrinsic sizing, semantic structure, clear focus treatment, and realistic content are equally important. Challenges, Limitations, and Professional PracticeCSS is powerful but complex. Different formatting contexts interact, intrinsic sizes can produce surprising results, and browser support may vary for new features. Developers should consult current compatibility data and provide sensible fallbacks where necessary. A fallback should preserve functionality, not merely visual similarity. Overuse of breakpoints can create contradictory rules and maintenance costs. Overuse of utility classes can also make markup difficult to interpret unless a coherent design system is used. Conversely, excessively abstract CSS may conceal the relationship between a component and its styles. Accessibility is an engineering requirement, not an optional visual enhancement. Developers should preserve logical source order, support keyboard focus, honour user preferences such as reduced motion, maintain readable contrast, avoid forced fixed heights, and allow text enlargement. Privacy and governance also matter: externally hosted fonts, analytics-driven personalisation, and third-party widgets can introduce data protection, performance, and supply-chain concerns. Use only the resources necessary for the interface and evaluate their security and licensing implications. Contemporary CSS increasingly supports container queries, cascade layers, logical properties, nesting, and advanced colour functions. Container queries allow a component to respond to the size of its own container rather than the viewport. Logical properties such as margin-inline and padding-block improve internationalisation because they adapt to writing direction. These features are valuable, but they should be introduced with progressive enhancement and an understanding of project browser requirements. Best Practices Checklist- Prefer semantic HTML and normal flow before adding positioning.
- Use
box-sizing: border-box consistently. - Keep selectors simple and avoid unnecessary
!important. - Use custom properties for repeated design decisions.
- Choose Flexbox for one-dimensional alignment and Grid for two-dimensional structure.
- Use fluid sizing and intrinsic layout functions before adding many breakpoints.
- Start with a usable narrow layout and progressively enhance it.
- Test real content, zoom, keyboard navigation, intermediate widths, and user preferences.
- Do not communicate essential information through colour alone.
- Measure performance and avoid unnecessary fonts, images, animations, and third-party code.
Chapter SummaryCSS transforms structured HTML into a readable, interactive, and adaptable interface. The cascade resolves competing declarations through relevance, importance, specificity, and source order, while inheritance supplies values for selected properties. The box model explains how content, padding, borders, and margins determine occupied space; border-box sizing often makes responsive calculations more predictable. Typography and colour must support hierarchy, readability, contrast, and accessibility. Normal flow should be the starting point for layout. Flexbox manages relationships along one main axis, whereas Grid manages rows and columns together. Media queries and mobile-first design allow interfaces to respond to changing conditions, but responsive quality also depends on flexible content, semantic structure, keyboard support, zoom, and testing. Professional CSS is therefore not merely decorative code: it is a maintainable system for presenting information under varied technical and human conditions. Key TermsCascade: The process by which the browser resolves competing CSS declarations. Specificity: The selector weighting used when applicable declarations compete. Inheritance: The transfer of selected property values from an ancestor to a descendant. Box model: The model of content, padding, border, and margin surrounding an element. Content box: The content area inside an element’s padding and border. Border box: The content, padding, and border considered together as the declared box. Intrinsic size: A size determined by an element’s content or natural dimensions. Normal flow: The default layout arrangement used by the browser. Formatting context: A layout environment that determines how boxes interact. Flexbox: A one-dimensional CSS layout system. Main axis: The primary direction in which flex items are arranged. Cross axis: The direction perpendicular to a flex container’s main axis. CSS Grid: A two-dimensional layout system based on rows and columns. Media query: A conditional CSS rule based on viewport or device features. Mobile-first design: Designing for constrained conditions first and enhancing for larger spaces. Breakpoint: A condition at which layout or styling changes. Custom property: A CSS variable defined with a name beginning with --. Responsive image: An image that adapts to its containing space and preserves appropriate proportions. Progressive enhancement: Providing a usable baseline and adding capabilities when supported. Logical property: A property expressed relative to writing direction, such as margin-inline. Review QuestionsShort Answer Questions- What are the four major areas of the CSS box model?
- How do
justify-content and align-items differ in a flex container? - Why is
box-sizing: border-box commonly used? - What is the purpose of a media query?
- Why should colour not be the sole method of communicating information?
Long Answer Questions- Explain how cascade, specificity, inheritance, and source order work together to determine a computed style.
- Compare Flexbox and CSS Grid, including the types of layout problems for which each is most appropriate.
- Describe a mobile-first workflow for developing a responsive page.
- Explain how typography, units, line length, and contrast influence usability.
- Discuss the accessibility and maintainability risks of fixed dimensions, excessive specificity, and absolute positioning.
Analytical / Application Questions- A four-column card layout overflows at 700px, and each card has a fixed width of 320px. Propose a Grid-based redesign and explain why it is more adaptable.
- A navigation bar fits at 1200px but wraps awkwardly at 850px. Identify two possible causes and propose a systematic debugging process.
- Design a responsive course dashboard strategy that supports keyboard users, long translated text, 200% zoom, reduced motion, and both narrow and wide screens. Justify your layout and CSS choices.
Multiple Choice Questions with AnswersQuestion 1Which factor normally resolves a conflict when two applicable author declarations have equal importance and specificity? A. The declaration that appears later in source order B. The declaration with the shorter property name C. The declaration with the larger pixel value D. The declaration inherited from the nearest ancestor Correct Answer: A. The declaration that appears later in source order Question 2With box-sizing: border-box, what does a declared width include? A. Only the content area B. Content, padding, and border C. Content, padding, border, and margin D. Only padding and margin Correct Answer: B. Content, padding, and border Question 3Which Flexbox property distributes items along the main axis? A. align-items B. align-content C. justify-content D. flex-direction Correct Answer: C. justify-content Question 4Which CSS layout system is most directly designed for simultaneous row and column alignment? A. Float layout B. Flexbox C. Inline formatting D. CSS Grid Correct Answer: D. CSS Grid Question 5What does max-width: 100%; height: auto commonly achieve for an image? A. It crops every image to a square B. It prevents the image exceeding its container while preserving its ratio C. It makes every image exactly 100 pixels wide D. It removes the image's intrinsic dimensions Correct Answer: B. It prevents the image exceeding its container while preserving its ratio Question 6Which approach describes mobile-first CSS? A. Designing only for desktop and hiding content on phones B. Starting with constrained layouts and adding enhancements at larger widths C. Using fixed pixel widths for all devices D. Using a separate stylesheet for every phone model Correct Answer: B. Starting with constrained layouts and adding enhancements at larger widths Question 7In repeat(auto-fit, minmax(16rem, 1fr)), what is the role of minmax()? A. It sets a lower and upper track size B. It disables responsive behaviour C. It changes text into columns D. It forces every track to be exactly 16rem Correct Answer: A. It sets a lower and upper track size Question 8Which practice best supports keyboard accessibility? A. Removing all focus outlines B. Using colour alone for focus indication C. Providing a visible focus indicator D. Reordering all content with the order property Correct Answer: C. Providing a visible focus indicator Question 9Which property commonly inherits from an ancestor? A. margin B. padding C. border D. color Correct Answer: D. color Question 10Why should breakpoints generally be chosen according to content rather than device names? A. Device names determine CSS specificity B. Content becomes crowded at different widths depending on its structure C. Device names cannot be used in HTML D. Content never changes size Correct Answer: B. Content becomes crowded at different widths depending on its structure
|