Term 2 · Module 4 of 8

Introduction to CSS and Styling

Website Development

Introduction to CSS

CSS (Cascading Style Sheets) brings a website to life with visual appearance. If HTML is the skeleton of a page, CSS adds the “skin” – colors, fonts, spacing, layout, and overall style. It separates content (HTML) from presentation (how it looks), making code cleaner, maintainable, and scalable.

What “Cascading Style Sheets” means

  • Style sheets – A set of rules that define how elements on a webpage should look. Each rule specifies properties (e.g., color, font size, margin) and their values.
  • Cascading – Like a waterfall flowing from top to bottom, styles are applied in layers, from the most general to the most specific rules. The cascade determines which rule wins when multiple rules target the same element. (Detailed coverage in a later video.)

The syntax of a CSS rule

A CSS rule consists of a selector and a declaration block:

selector {
  property: value;
}
PartRoleExample
SelectorTargets which HTML element(s) to styleh1
PropertyThe visual characteristic to changecolor
ValueThe specific setting for that propertypurple

Example – The following rule turns the text of every <h1> element purple:

h1 {
  color: purple;
}

This is the simplest form; later modules will introduce more powerful selectors and properties.

Why CSS matters

  • Without CSS, a webpage is functional but bland – like a colouring book with no colours.
  • Early web developers used HTML tags (e.g., <font>) for styling, which cluttered code and made large projects unmanageable.
  • CSS was born in 1996 as a dedicated solution to separate style from structure, enabling efficient, scalable design.

What CSS can do

Think of CSS as adjectives that describe HTML nouns. HTML says “here’s a button”; CSS says “this is a purple, large, rounded button”. Core capabilities covered in this module:

  • Selectors – pinpoint any element (or group of elements) on a page.
  • Properties – change colours, fonts, sizes, backgrounds, borders, margins, padding, and more.
  • The Box Model – how margins, borders, padding, and content combine to form layout.
  • Positioning & Alignment – control where elements sit on the screen.

Exam tip: “Cascading” is a key exam concept. Remember: general rules (e.g., body) apply first, then more specific rules (e.g., h1) override them. The cascade answers “which style wins?”.

What’s coming (Modules 4 & 5)

  • Module 4: Selectors, basic styling, box model, layout, positioning.
  • Module 5: Animations, transitions, responsive design (making pages adjust to different screen sizes).

Key takeaways

  • CSS = Cascading Style Sheets – separates content from presentation.
  • A rule has a selector and a { property: value; } block.
  • The cascade resolves conflicting styles by order of specificity and source.
  • CSS was introduced in 1996 to replace messy HTML styling.
  • It controls colours, fonts, spacing, layout, and much more – turning HTML “bones” into polished websites.

Ways to Add CSS to HTML

CSS (Cascading Style Sheets) is applied to HTML documents through three distinct methods. Each serves a different purpose and is chosen based on project scale, reusability, and workflow. The three methods are inline CSS, internal CSS, and external CSS.


Inline CSS

Inline CSS applies styles directly to a single HTML element using the style attribute. The style attribute is a global attribute – it can be added to any opening HTML tag. Inside, you write property–value pairs (e.g., color: blue). This method is quick for testing or making small, one‑off adjustments.

<h1 style="color: blue;">This is the heading</h1>
  • Targets only the specific element it is placed on.
  • Not reusable – if the same style is needed elsewhere, it must be repeated.
  • Best reserved for prototyping, debugging, or overriding other styles temporarily.

Internal CSS

Internal CSS places all styles inside a <style> tag in the <head> section of the HTML file. The CSS rules target elements by selectors (e.g., p for all paragraph elements) and apply consistently across the entire page.

<head>
  <style>
    p {
      color: green;
    }
  </style>
</head>
  • All <p> elements on the page will have green text.
  • Keeps styles in the same file but separates them from content.
  • Ideal for single‑page websites where no external file is needed.

External CSS

External CSS separates styles into a dedicated .css file. This file is linked to the HTML using a <link> tag in the <head>. The rel attribute must be "stylesheet", and the href attribute points to the file’s path.

<head>
  <link rel="stylesheet" href="style.css">
</head>

Contents of style.css:

h2 {
  color: red;
}
  • Most scalable method – the same .css file can be reused across multiple pages.
  • Changes in one file update the entire site’s appearance.
  • Separates structure (HTML) from presentation (CSS), making code cleaner and easier to maintain.

Comparison & Decision Guide

MethodWhere styles are writtenScopeUse when
Inlinestyle attribute of an elementSingle elementQuick test, one‑off tweak
Internal<style> in <head>One HTML pageSingle‑page site, all styles local
ExternalSeparate .css fileAny page that links the fileMulti‑page sites, reusability

Exam tip: Inline CSS has the highest specificity – it overrides both internal and external rules for the same property on the same element. However, it is the least maintainable.


Key takeaways

  • Three methods: inline (via style), internal (<style> in <head>), external (.css file linked with <link>).
  • Inline = fastest for a single element, but zero reusability.
  • Internal = good for a single page, keeps styles inside the HTML file.
  • External = industry standard for multi‑page sites; separates concerns and enables reuse.
  • The <link> tag requires rel="stylesheet" and href pointing to the .css file.
  • Use the appropriate method based on project size and style reusability needs.

Syntax and Selectors

CSS syntax is the formal structure of every CSS rule. It tells the browser which HTML element to style and how to style it. The fundamental pattern:

selector {
  property: value;
}
  • Selector – identifies the HTML element(s) to style (e.g., h2).
  • Curly braces { } – enclose all style declarations for that selector.
  • Property – the aspect you want to change (e.g., color, font-size).
  • Value – the setting you assign to the property (e.g., red, 16px).
  • Semicolon – separates multiple property–value pairs inside the same braces.

Multiple declarations can be added for one selector:

h2 {
  color: red;
  background-color: green;
}

Exam tip: Every declaration must end with a semicolon. Missing it causes the next rule to fail – a common rookie mistake.


Selector Types

Selectors are how CSS “talks to” HTML. Each type has a specific syntax and use case.

SelectorSyntaxTargetsExample
ElementtagnameAll elements of that tagp { color: green; }
Class.classnameAll elements with that class attribute.orange { color: orange; }
ID#idnameThe single element with that id attribute#main { color: blue; }
Universal*Every element in the document* { margin: 0; }
Attributeelement[attribute] or element[attribute="value"]Elements with a specific attribute (or value)input[type="text"] { border: 1px solid black; }

Element Selector

The simplest: write the tag name. It selects all instances of that tag.

h2 {
  background-color: green;
}
<h2>Second heading</h2>  <!-- styled -->
<p>Sample text</p>       <!-- not styled by h2 -->

Class Selector

The class attribute is a global HTML attribute that groups elements together for shared styling. Class names are reusable across different tag types.

CSS syntax: a dot (.) followed by the class name.

<p class="orange">This is orange</p>
<p class="orange">Another orange paragraph</p>
.orange {
  color: orange;
  font-weight: bold;
}

All elements with class="orange" (regardless of tag) receive the styles.

ID Selector

The id attribute must be unique within a document – it identifies a single element.

CSS syntax: a hash (#) followed by the ID value.

<h1 id="main-element">First heading</h1>
#main-element {
  color: blue;
  text-align: center;
}

Exam tip: IDs are one-of-a-kind. Using the same ID twice is invalid HTML and may cause unpredictable styling.

Universal Selector

* applies styles to every element. Useful for resetting default browser margins/paddings.

* {
  margin: 0;
  padding: 0;
}

The universal selector overrides default spacing for all elements (though it can be affected by later, more specific rules – that’s the cascade, covered in another lesson).

Attribute Selector

Targets elements based on the presence of an attribute, or the exact value of that attribute.

SyntaxMeaning
element[attr]Element has the attribute (any value)
element[attr="value"]Element has attribute with that exact value

Example – target by attribute value:

<input type="text" placeholder="Do not enter your name">
<input type="email" placeholder="Enter your email">
input[type="text"] {
  border: 5px solid darkmagenta;
}

Only the text input gets the purple border.

Example – target by attribute presence (any value):

<button draggable="true">Click me</button>
button[draggable] {
  color: pink;
}

The button is styled because it has the draggable attribute, regardless of its value.


When to Use Class vs. ID

  • Class – for reusable styles that apply to multiple elements (teams).
  • ID – for a single, unique element (individual).

Exam tip: Class selectors are more flexible and recommended for most styling. Reserve IDs for JavaScript hooks or very specific, one-off styling.


Key Takeaways

  • CSS syntax: selector { property: value; } – every declaration ends with a semicolon.
  • Element selector – targets all elements of a given tag.
  • Class selector (.name) – targets any element with that class attribute; reusable.
  • ID selector (#name) – targets a single unique element.
  • Universal selector (*) – targets every element; great for resets.
  • Attribute selector ([attr] or [attr="val"]) – targets elements by attribute presence or exact value.
  • Use classes for reusable groups, IDs for unique elements.

Tools and References

CSS is vast — there are dozens of properties just for text (e.g., letter-spacing, line-height, text-transform) and many ways to achieve the same visual effect (e.g., multiple border properties). The goal is not to memorise everything, but to understand the fundamentals and know where to find answers.

Key Resources

ResourceWhat it providesHow to use it
MDN Web Docs (Mozilla Developer Network)Detailed explanations for every CSS property, with code examples and rendered previewsSearch for any property (e.g., box-shadow) and read the complete reference
Google (or any search engine)Quick answers for specific problems, tutorials, and videosSearch phrases like "CSS rounded corners" to find step‑by‑step guides
Online CSS generators (e.g., color pickers)Pre‑written CSS code for common effects (colours, gradients, shadows)Pick colours, copy the generated rule, and paste into your stylesheet

Workflow: How to approach a CSS problem

Exam tip: Interviewers or exams rarely test rote recall of property names. Instead, they assess your ability to find the right property and apply it correctly. Become fluent with MDN’s CSS reference — it’s your primary cheat sheet.

Practical Advice

  • Master the basics: Syntax, selectors, the cascade — these never change.
  • Look it up when you get stuck: Even professional developers search for properties daily.
  • Use tools without guilt: Colour pickers, gradient generators, and shadow tools save time and reduce errors.
  • Build often: The more you code, the more familiar the common properties become.

Key takeaways

  • CSS has hundreds of properties; memorising all of them is neither expected nor efficient.
  • MDN Web Docs is the definitive reference — every property includes syntax, examples, and live previews.
  • Google and online CSS generators are legitimate, everyday tools for real‑world development.
  • Focus on fundamentals (syntax, selectors, layout) and learn to find the rest on demand.

Colors in CSS

CSS provides multiple ways to define colors to set the foreground (text) color and the background color of elements. Understanding these representations lets you precisely control the visual tone of a webpage.

Color Properties

PropertyPurposeExample
colorSets the text color (foreground)color: blue;
background-colorSets the background of the elementbackground-color: lightblue;

The shorthand background property can also set gradients and images. Stick to background-color for solid colors.

Color Representation Methods

CSS accepts three common ways to specify a color:

  1. Named colors – Simple, browser‑recognised words (e.g., red, teal, beige, aqua).
  2. Hexadecimal (hex) codes – A six‑character code preceded by # (e.g., #FF5733).
  3. RGB notation – rgb(red, green, blue) where each value is an integer 0–255 (e.g., rgb(255, 87, 51)).
MethodSyntaxExampleUse Case
Namedcolor: red;Simple, fast prototyping
Hexcolor: #FF5733;Compact, most common in production
RGBcolor: rgb(255, 87, 51);When you want to adjust numeric values

How Hex and RGB Relate

The RGB color system is an additive model – red, green, and blue light combine to create colors.

  • Zero of all three → black.
  • Full (255) of all three → white.
  • Equal amounts of red and green → yellow; adding blue → becomes white.

Hexadecimal is just another way to write the same three numbers (0–255 for each channel) in base‑16.

  • Digits: 0‑9 and a‑f (16 total).
  • Example: decimal 255 → FF; decimal 150 → 96; decimal 200 → C8.
  • So a hex code like #FF5733 means R=255, G=87, B=51.

Exam tip: A hex code is exactly an RGB triplet written in base‑16 – no magic! You can convert any RGB value to hex and vice versa.

Color Tools and Palettes

  • Color pickers (built into browsers or online) let you visually select a color and copy its hex or RGB value.
  • Palette websites (e.g., Color Hunt) provide pre‑matched harmonious color sets. Click to copy a hex code, then paste it into your CSS with a #.

Worked Example

ElementCSS appliedEffect
<h1>color: blue; background-color: aqua;Blue text on light blue background
<p>color: #XXXXXX; (hex from palette)Text color set to palette colour
<button>color: rgb(…, …, …);Greenish text (random numbers)
<input>color: red; background-color: #XXXXXX;Red typed text, custom background inside the box
<html>background-color: beige;Entire page background beige (cascades but can be overridden by specific element backgrounds)

Notable behaviours demonstrated:

  • The color property on an <input> affects only the typed text, not the placeholder text.
  • Background colors cascade – adding a background to <html> shows behind elements that do not have their own background set (but specific background‑color rules override it). This is part of the cascading nature of CSS.

Key Takeaways

  • color controls text colour; background-color controls the element’s background.
  • Three main ways to define colors in CSS: named, hex, and RGB.
  • Hex codes are compact base‑16 representations of RGB values – no need to memorise conversion, just copy from a picker.
  • Use color pickers and palettes (e.g., Color Hunt) to quickly choose harmonious colours.
  • Placeholder text inside <input> is not affected by the color property – that requires the ::placeholder pseudo‑element.

CSS Fonts

Fonts are central to web design — they control readability, tone, and visual hierarchy. CSS offers a suite of properties to adjust typeface, size, thickness, slant, and alignment. Use them to make text both expressive and accessible.

1. Font Size (font-size)

Controls how large or small text appears. Units fall into two categories:

Absolute units — fixed size, unaffected by context.

  • px (pixels): 1px=196inch≈0.26mm1\text{px} = \frac{1}{96}\text{inch} \approx 0.26\text{mm}. Renders identically regardless of device.
  • pt (points): 1pt=172inch≈0.35mm1\text{pt} = \frac{1}{72}\text{inch} \approx 0.35\text{mm}. Common in print; also works on screen.

Relative units — size depends on another element.

  • em: Multiplied by the parent element’s font-size. If parent is 20px20\text{px}, 2em ⇒2×20=40px\Rightarrow 2 \times 20 = 40\text{px}.
  • rem: Multiplied by the root element’s (<html>) font-size. If root is 30px30\text{px}, 1.5rem ⇒1.5×30=45px\Rightarrow 1.5 \times 30 = 45\text{px}.

Named sizes — keywords like small, medium, large. Imprecise; only for prototyping.

Exam tip: em compounds when elements are nested (each child multiplies its parent). rem stays consistent — always relative to the root. Use rem for predictable, responsive sizing.

Worked example :

ElementRuleParent/Root sizeComputed size
<h1>font-size: 60px—60px
Parent <div>font-size: 20px—20px
Child (.em-based)font-size: 2emparent = 20px2×20=40px2 \times 20 = 40\text{px}
Root <html>font-size: 30px—30px
Child (.rem-based)font-size: 1.5remroot = 30px1.5×30=45px1.5 \times 30 = 45\text{px}

Table: Font-size units compared

UnitTypeRelative toUse case
pxAbsolute—Fixed, pixel-perfect control
ptAbsolute—Print styling
emRelativeParent’s font-sizeCompound scaling (use with care)
remRelativeRoot font-sizeConsistent, responsive layouts
NamedKeywordBrowser defaultQuick prototyping only

2. Font Weight (font-weight)

Controls the thickness of characters.

  • Keywords: normal (400), bold (700), lighter, bolder
  • Numerical values: 100 (thin) → 900 (heavy). 400 = normal, 700 = bold.
  • Not all typefaces support every weight; missing values fall back to the nearest available.

Example: h1 { font-weight: 800; } .em-based { font-weight: 500; }


3. Font Family (font-family)

Selects the typeface (e.g., Arial, Times New Roman). Always provide a font stack — a comma‑separated list of fallbacks.

p {
  font-family: 'Gill Sans', Calibri, 'Trebuchet MS', sans-serif;
}

The browser tries the first font; if unavailable, moves down the list. End with a generic fallback (serif, sans-serif, monospace).

Google Fonts — load custom fonts via a <link> in the document <head>, then reference the font name in CSS.

Example:

<link href="https://fonts.googleapis.com/css2?family=Bokor&display=swap" rel="stylesheet">
h1 {
  font-family: 'Bokor', sans-serif;
}

This ensures the same look across browsers and devices.


4. Font Style (font-style)

Controls slanting of text.

  • normal — upright.
  • italic — uses the italic version of the typeface (if it exists).
  • oblique — artificially slants the upright glyphs. May take an optional angle (e.g., oblique 15deg).

Use italic for emphasis. Example: .em-based { font-style: italic; }


5. Text Alignment (text-align)

Horizontal alignment of text within its container.

ValueEffect
leftAligns text to the left edge (default for LTR languages)
rightAligns to the right edge
centerCenters text horizontally
justifyStretches each line so both left and right edges are flush (adds or removes space between words)

Justify creates a clean, book‑like block but can produce awkward gaps on short lines. Example: p { text-align: justify; }


Key takeaways

  • font-size uses absolute (px, pt) or relative (em, rem) units. Prefer rem for responsive design.
  • em scales relative to the parent; rem scales relative to the root — avoid nested em traps.
  • font-weight uses keywords or numeric values (100–900); 400 = normal, 700 = bold.
  • font-family should always include a font stack with a generic fallback.
  • Google Fonts are loaded via <link> and referenced by name — they ensure cross‑browser consistency.
  • font-style (italic/oblique) and text-align (left, center, right, justify) control slant and horizontal alignment.
  • Font choices affect readability and tone — experiment but always test fallbacks.

CSS Inspection

CSS inspection refers to using the browser’s developer tools to examine, debug, and experiment with CSS in real time. Instead of guessing why a style doesn’t look right, you open the tools and see exactly which rules are applied, which are overridden, and what the final rendered values are.

Opening Chrome Developer Tools

Three equivalent methods:

MethodAction
MenuThree dots → More Tools → Developer Tools
KeyboardCtrl+Shift+I (Windows) / Cmd+Option+I (Mac) – also F12
Right-clickRight‑click any element → Inspect (directly shows that element’s HTML)

The Elements Tab: Styles Panel

Once DevTools is open, the Elements tab shows the HTML structure. Selecting an element (either by clicking in the HTML tree or using the element‑picker icon in the top‑left of DevTools) reveals the Styles panel on the right.

The Styles panel displays:

  • All CSS rules that apply to the selected element, in order of specificity.
  • The source file and line number for each rule. Clicking a file link jumps directly to the source code.
  • Which rules are overridden (shown with a strikethrough). For example, font-size: 2em crossed out when a later rule sets font-size: 60px.
  • An inline edit capability – you can type a new property (e.g. color: chocolate) and see the change live on the page.

    Important: These edits are temporary. They disappear on page refresh and do not modify your source files. Use them for rapid experimentation only.

Computed Tab

The Computed tab (next to Styles) solves the confusion of overridden rules. It aggregates all resolved styles into one clean list, showing the final value for every property after cascading and inheritance. This is the definitive answer to “what value does this element actually get?”

Box Model Visualisation

Both the Styles panel (at the bottom) and the Computed tab display a box model diagram for the selected element. It shows:

┌───── Margin ─────┐
│ ┌── Border ──┐   │
│ │ ┌ Padding ┐ │   │
│ │ │ CONTENT │ │   │
│ │ └─────────┘ │   │
│ └─────────────┘   │
└───────────────────┘

Each region is labelled with its current pixel (or other unit) value. This is invaluable for diagnosing spacing and layout issues.

CSS Overview Tool

A separate, aggregate tool that summarises all CSS used on a page:

  1. Open DevTools → three‑dot menu (⋮) → More Tools → CSS Overview.
  2. Click Capture overview.

It reports:

  • Colors used (with count)
  • Fonts used
  • Unused declarations (or other diagnostics)

Useful when reverse‑engineering a design from a live website or auditing your own project for consistency.

Exam tip: The Computed tab is the fastest way to find the final value of a property when multiple rules conflict. Always look there before debugging specificity.

Key takeaways

  • Open DevTools with Ctrl+Shift+I, F12, or right‑click → Inspect.
  • The Styles panel shows all applied rules, source links, and overridden (strikethrough) values.
  • Live editing is temporary – use it to test, then update your source file.
  • The Computed tab gives the final resolved values, ignoring overridden rules.
  • The box model diagram helps visualise margin, border, padding, and content dimensions.
  • CSS Overview captures a summary of colors, fonts, and overall CSS usage on any page.

Box Model

Every element on a webpage is enclosed in an invisible box. The CSS box model defines how the element’s content, padding, border, and margin are sized and how they interact to determine the element’s total space and layout.

  • Content – the actual text, image, or inner element.
  • Padding – space between content and border; expands the element inward.
  • Border – visible or invisible boundary around padding.
  • Margin – space outside the border; separates the element from others.

Height & Width

height and width set the dimensions of the content area. Units can be absolute (px) or relative (%, vw, etc.).

ExampleCodeResult
Fixed sizeheight: 300px; width: 150px;Box is exactly 300px × 150px.
Percentage widthwidth: 50%;Width = 50% of parent container (e.g., <body>). Resizes with viewport.

Exam tip: Changing height or width affects the content area only – padding, border, and margin add extra space.

Border

border adds a boundary around the element. Shorthand: border: <width> <style> <color>;

Styles: solid, dashed, dotted, double, etc.

Individual side controls: border-width, border-style, border-color accept 1, 2, or 4 values.

Number of valuesApplies to
1All four sides
2Top & bottom (1st), left & right (2nd)
4Top, right, bottom, left (clockwise)

Example (shorthand with 4 values):

border-width: 10px 30px 50px 60px;
border-color: red green blue black;
border-style: dotted double dashed solid;

border-radius rounds the corners.

  • 1 value: all corners.
  • 2 values: first → top-left & bottom-right, second → top-right & bottom-left.
  • 4 values: clockwise from top-left.

Padding

padding creates internal space between content and border.

  • Expands the element’s total size outward from the content.
  • Same 1/2/4 value rules as border.

Example: padding: 20px; adds 20px on all sides.

Margin

margin creates external space outside the border, separating elements.

  • Also uses 1/2/4 value shorthand.
  • Margin collapsing: When two adjacent vertical margins meet, they collapse to the larger value (not the sum).
    • E.g., element A margin-bottom: 30px, element B margin-top: 20px → gap = 30px, not 50px.

Worked Example: Total Width of an Element

Given the first box:

margin: 30px;
border: 10px solid black;
padding: 20px;
width: 150px;   /* content width */

Total width (left to right) = margin-left + border-left + padding-left + content width + padding-right + border-right + margin-right = 30 + 10 + 20 + 150 + 20 + 10 + 30 = 270px.

Exam tip: The box model is additive by default (box-sizing: content-box). To include padding and border inside the declared width, use box-sizing: border-box.


Using <div> for Grouping

The <div> element is a generic block-level container. It groups elements so they can be styled as a unit.

.grouping {
  border: 20px solid green;
  padding: 20px;
  text-align: center;
}

This applies the same border, padding, and alignment to all children (e.g., <h1> and <p> inside the div).


Key takeaways

  • Box model: content → padding → border → margin (inside-out).
  • height/width set content size; use % for responsive layouts.
  • border shorthand: width, style, color. Use 2 or 4 values for side-specific control.
  • padding expands element size; margin creates external spacing; vertical margins collapse.
  • border-radius softens corners.
  • <div> groups content for efficient styling.
  • Inspect elements in DevTools to see the box model visually.

The Cascade

The cascade refers to the order in which CSS rules are applied. When multiple rules target the same element and property, later declarations override earlier ones — "whatever comes later takes priority."

Definition: Cascade = waterfall-like flow. In CSS, styles applied later in source order have higher precedence (at the same specificity level).

Demonstration

Consider an <h1> element and two rules in the same stylesheet:

h1 { color: green; }   /* line 1 */
h1 { color: brown; }   /* line 5 – overrides green */

The heading appears brown. Adding a third rule below (e.g., color: cornflowerblue) overrides both. This principle holds within a single selector (multiple identical properties) and across selectors of equal specificity.

External vs. Internal vs. Inline – Source Order

  • External stylesheets linked in <head> are loaded in order of appearance.
  • Internal styles (<style> in <head>) are treated like another stylesheet — they follow the same cascade.
  • Inline styles (via the style attribute) are considered to "come last" in source order for the element itself, but they also carry higher specificity (see below).

When two stylesheets have selectors of equal specificity, the sheet linked lower in the HTML wins.

Exam tip: Cascade only matters when specificity is tied. Always check specificity first – see next section.

Key takeaways

  • Cascade: later styles override earlier ones within the same specificity level.
  • Applies to both internal and external CSS.
  • Source order (position in HTML / within a file) determines precedence when specificity is equal.

Specificity

Specificity is the algorithm CSS uses to decide which rule "wins" when multiple selectors target the same element. Think of it as a ranking: some selectors are inherently more powerful than others.

Selector hierarchy (lowest → highest)

Selector typeExampleSpecificity weight (MDN notation)
Element / type selectorh1, p, div(0,0,1)
Class / attribute selector.class-a, [type="text"](0,1,0)
ID selector#unique-id(1,0,0)
Inline style (on the element)style="color: red"(1,0,0,0) – always wins over external/internal
!important annotationcolor: green !important;Overrides all of the above (see below)
  • Each higher level overrides any number of lower-level selectors. Ten element selectors cannot beat a single class.
  • When two selectors have the same highest weight, cascade (source order) breaks the tie.

Demonstration with <h2 class="class-abc" id="id-abc">

  1. Element selector wins if only element rules exist; last one in the file applies (cascade).
  2. Add a class selector (.class-abc { color: orange; }). Even if it appears before element selectors in the source, the heading turns orange – class is more specific.
  3. Add an ID selector (#id-abc { color: darkblue; }). Even at the top of the file, it overrides both element and class.
  4. Multiple properties inside the ID selector: cascade still applies — #id-abc { color: darkblue; color: gray; } → gray wins (later).
  5. Two external stylesheets each with an ID selector: the sheet loaded second wins because both have the same specificity (1,0,0), so cascade decides.
  6. Internal style with ID selector: treated as another CSS source. If loaded before the external ID, cascade gives the later one precedence. If moved below (later in the HTML), it overrides.
  7. Inline style (style="color: fuchsia") overrides all external and internal ID/class/element rules – inline has the highest specificity (1,0,0,0).

Exam tip: Inline styles are rarely recommended because they break separation of concerns and are difficult to override. Use them only for quick tests.

Worked example: selector conflict

/* external stylesheet 1 (loaded first) */
h2           { color: green; }        /* (0,0,1) – overridden */
.class-abc   { color: orange; }       /* (0,1,0) – overridden */
#id-abc      { color: darkblue; }     /* (1,0,0) – overridden by later ID */

/* external stylesheet 2 (loaded second) */
h2           { color: blueviolet; }   /* (0,0,1) – ignored */
#id-abc      { color: khaki; }        /* (1,0,0) – wins (higher cascade) */

Result: heading is khaki.

If an inline style is added:

<h2 id="id-abc" class="class-abc" style="color: fuchsia">Heading</h2>

Result: fuchsia – inline specificity of (1,0,0,0) beats any external ID.

Key takeaways

  • Specificity: ID > class > element.
  • Equal specificity → cascade (source order) decides.
  • Inline styles beat all external/internal selectors.
  • !important beats everything (except another !important with later source order).

The !important Keyword

Adding !important to a property declaration forces it to override any other rule, regardless of specificity or cascade — except another !important rule later in source order.

h2 { color: green !important; }   /* this will win over any other 'color' rule */
  • Use sparingly. It makes CSS hard to debug and override.
  • If two rules both have !important, cascade applies again – later one wins.
h2 { color: green !important; }
h2 { color: cornflowerblue !important; }  /* wins because later */

Exam tip: Always try to solve style conflicts by adjusting selector specificity before resorting to !important. Overuse is a code smell.


Putting It All Together – CSS Resolution Order

Complete precedence (from strongest to weakest):

  1. !important declarations (tie → cascade)
  2. Inline styles (no !important)
  3. ID selectors
  4. Class / attribute selectors
  5. Element selectors
  6. Universal selector, inherited values (not covered here)

Key takeaways

  • !important should be a last resort.
  • For all other cases: specificity first, then cascade.
  • Inline styles are the second-strongest non-!important option (but avoid them).
  • When two rules have the same specificity and no !important, the one that appears later in the source order (including style order in HTML) applies.

Combining CSS Selectors

Combining selectors lets you target elements precisely without modifying HTML or adding extra classes/IDs. This keeps styles organized and efficient.

Descendant Selector

Selects elements nested anywhere inside a parent – no matter how deep. Use a space between selectors.

.container p {
  color: orange;
}

Targets all <p> elements within any element with class container, including grandchildren, great-grandchildren, etc. The parent div itself is not selected.

Exam tip: Descendant selectors are the default “combination” – if you forget the space, you get chaining (see below). Always double-check the separator.

Child Selector (>)

Selects only direct children – one level deep. Use the > combinator.

.parent > p {
  color: green;
}

Only <p> elements that are immediate children of .parent are affected. Nested <p> inside another <div> inside .parent is ignored.

Adjacent Sibling Selector (+)

Selects an element that appears immediately after a specific element, sharing the same parent.

h2 + h3 {
  color: blueviolet;
}

Only the first <h3> that directly follows an <h2> gets styled. Subsequent <h3> siblings are ignored.

Example HTMLStyled?
<h2>Title</h2>
<h3>Subtitle</h3>
Yes (first <h3> after h2)
<h2>Title</h2>
<h3>Second</h3>
<h3>Third</h3>
Only the first <h3>

Common use case: styling a <label> that comes right after a checkbox or radio input.

input[type="checkbox"] + label {
  color: dodgerblue;
}

Grouping Selector (,)

Apply the same styles to multiple, unrelated selectors. Separate them with a comma.

#heading4, .heading5class, h6 {
  color: indigo;
}

Reduces repetition and keeps CSS concise.

Exam tip: Grouping does not create a relationship between selectors – it’s purely a shorthand. Each selector still targets its own elements independently.

Chaining Selectors

Write selectors without any space to target an element that must satisfy all conditions simultaneously. Good for selecting a specific element that has both a tag and a class/ID.

button.asd {
  color: red;
}

This matches only <button> elements that also have class asd. An <input> with class asd or a <button> without the class are left unstyled.

When chaining, it is best practice to start with the element selector (e.g., button) followed by class/ID selectors (.asd, #menu). This improves readability because class and ID prefixes (. and #) clearly mark the start of each condition.

You can chain multiple classes and an ID:

div.container.main#menu { ... }
/* matches a <div> with classes container AND main, AND id="menu" */

Key Takeaways

  • Descendant (space): targets any descendant, any depth.
  • Child (>): targets only direct children.
  • Adjacent sibling (+): targets the next immediate sibling.
  • Grouping (,): apply same rule to multiple selectors.
  • Chaining (no space): element must match all selectors in the chain.
  • Chaining is ideal for applying a variation to a specific element without extra HTML classes/IDs.
  • Always choose the simplest combination that does the job – avoid overspecificity.

Pseudo-Classes and Pseudo-Elements

Pseudo‑class selectors and pseudo‑element selectors target elements based on their state or internal parts without requiring extra HTML markup. They transform static pages into interactive, polished interfaces.

Pseudo‑Class Selectors

A pseudo‑class is a keyword added to a selector (with a single colon :) that specifies a special state of the selected element. Examples: :hover, :active, :nth-of-type(), :checked, :visited, :enabled, :disabled.

:hover

Triggered when the user’s pointer hovers over an element. Commonly used for buttons, links, or any interactive feedback.

button:hover {
  color: chocolate;
  background-color: lightgreen;
  text-decoration: underline;
}

Effect: The button changes colour and gains an underline only while the mouse cursor is over it.

:active

Applies styles when the element is being activated – typically while the mouse button is pressed down.

button:active {
  color: aqua;
  background-color: black;
}

Sequence: Normal → :hover → :active (on click) → back to normal after release.

:nth-of-type()

Targets elements by their position among siblings of the same type. The argument can be a number, a keyword (odd, even), or an algebraic expression like An+B.

ArgumentSelects
3Only the 3rd element
2nEvery 2nd element (2, 4, 6, …)
3nEvery 3rd element (3, 6, 9, …)
7nEvery 7th element (7, 14, 21, …)
li:nth-of-type(3n) {
  background-color: khaki;
}

Result: List items 3, 6, 9, 18, … get a khaki background.

Exam tip: :nth-of-type(3) selects only the third element; :nth-of-type(3n) selects every third element. The n makes the formula iterative.


Pseudo‑Element Selectors

A pseudo‑element is a keyword added with a double colon :: that lets you style a specific part of the selected element. Examples: ::first-letter, ::first-line, ::selection.

::first-letter

Styles the first letter of a block‑level element (e.g., paragraph, heading).

p::first-letter {
  font-size: 60px;
  color: blue;
}

Effect: The initial character becomes large and blue, like a drop‑cap.

::first-line

Styles the first line of a block‑level element (the actual line as it wraps in the browser).

p::first-line {
  color: cadetblue;
}

Only the text on the first visual line receives the colour; subsequent lines remain unaffected.

::selection

Applies styles to the portion of an element that the user highlights (selects). Can be set globally or scoped to specific elements.

::selection {
  background-color: orange;
}
p::selection {
  background-color: darksalmon;
  text-decoration: underline;
}

Effect: Selecting any text shows an orange background; selecting text inside a <p> uses darksalmon with an underline.


Pseudo‑Class vs. Pseudo‑Element — Quick Comparison

AspectPseudo‑ClassPseudo‑Element
What it targetsA state of the elementA part or fragment of the element
SyntaxSingle colon :Double colon :: (legacy single‑colon also works for some)
Examplea:visitedp::first-letter
TriggerUser interaction or DOM positionStructural part of the element

Key Takeaways

  • Pseudo‑classes (:hover, :active, :nth-of-type()): style an element based on its state or position.
  • Pseudo‑elements (::first-letter, ::first-line, ::selection): style a specific part of an element.
  • :nth-of-type(An+B) accepts formulas: 2n = even, 3n = every third, etc. Without n, it selects only the nth occurrence.
  • Pseudo‑elements often use double colons (::) to distinguish them from pseudo‑classes, though older browsers may accept single colon.
  • Both require no extra HTML classes or IDs — purely CSS‑driven interactivity and typographic control.

CSS Inheritance

Inheritance is the mechanism by which certain CSS properties are automatically passed from a parent element to its child elements, unless the child has that property explicitly set. Intuitively: set a text color on <body> and every piece of text inside the page picks it up – no extra work needed.

Default inheritance from the nearest defined parent

When a property is inherited, a child element looks for the closest ancestor that has that property defined. If no ancestor has it, the default browser style applies.

Example – given this HTML:

<body>
  <h1>Heading</h1>
  <section>
    <h2>Subheading</h2>
    <p>Paragraph text</p>
  </section>
  <div>
    <h3>Div heading</h3>
    <input type="text">
    <button>Click</button>
  </div>
</body>
  1. Set color: goldenrod on <body> → all text inside inherits goldenrod.
  2. Then set color: blue on <section> → <h2> and <p> inside the section become blue (inherited from the closer parent). <h1>, <h3>, <input>, and <button> remain goldenrod because they still inherit from <body> – the section rule does not affect them.

The paragraph inspects as “inherited from section” (overriding “inherited from body”).

Exam tip: Inheritance doesn’t override explicit styles on the child – it only kicks in when no value is set on the child. Specificity and direct styling still win.

Elements that do not inherit by default

Form elements like <input> and <button> do not inherit text styling (color, font-family) from their parent by default. In the example, the button remained black (default user-agent style) even though <body> had color: goldenrod.

Forcing inheritance with the inherit keyword

You can explicitly tell an element to inherit any property using the inherit keyword.

button {
  color: inherit;   /* now takes the parent's goldenrod */
}

After adding this rule, the button’s text turns goldenrod. Developers use inherit to make form elements consistent with surrounding text.

Which properties are inherited?

There is no universal rule – you must check each property. The MDN documentation lists “Inherited” in the “Formal definition” section of every property.

Commonly inheritedCommonly not inherited
colormargin
font-family, font-sizeborder
letter-spacingpadding
text-alignwidth, height
visibilitybackground

Exam tip: The easiest way to know: if a property describes the appearance of text, it’s usually inherited. If it describes the layout or box of the element, it’s usually not inherited.

Recap with a decision tree

Key takeaways

  • Inheritance allows child elements to automatically get a property’s value from the nearest ancestor that defines it.
  • Properties like color, font-family, and letter-spacing are inherited; margin, border, padding are not.
  • The inherit keyword forces any property (even non-inherited ones) to take the parent’s computed value – useful for form elements.
  • Elements inside <form> (inputs, buttons) often do not inherit by default; use inherit to align them.
  • MDN’s “Formal definition” section is the authoritative source for a property’s inheritance behavior.

The <span> Element for Inline Styling

The <span> element is an inline container that wraps around a portion of text (or other inline content) without breaking the flow of the document. Unlike a block-level <div> which takes the full width, <span> sits within the line, allowing precise CSS styling of only that fragment.

Intuitively: you want to colour one word red, underline a phrase, or enlarge the first letter – <span> gives you a handle to attach a class or ID and apply styles exactly where you want, without affecting surrounding text.

Comparing <span> and <div>

ElementDisplay typeDefault behaviourUse case
<span>InlineWraps content; stays within the lineStyling a word, phrase, or inline image
<div>BlockStarts on a new line; takes full widthStructuring sections, containers

Exam tip: <span> is the go‑to for “I need to style just this bit of text inside a paragraph.” It does not add any line breaks or semantic meaning – it’s purely a styling hook.

Worked example: Highlighting “highlighted heading”

HTML (inside a <h1>):

<h1>This is a <span class="highlight">highlighted heading</span></h1>

CSS:

.highlight {
  color: blue;
}

Result: only the words inside the <span> turn blue. The rest of the heading remains its original colour.

Using <span> for word‑ or line‑level styling

GoalApproachCSS applied
Style the first word of a paragraphWrap the first word in <span class="first-word">font-size: 2em; color: brown;
Style the first few linesWrap those lines (including spaces) in <span class="first-lines">text-decoration: underline; background-color: aqua;

Compared to CSS pseudo‑elements like ::first-letter or ::first-line, <span> gives more precise control – you can target arbitrary text fragments, not just the first letter/line.

How it works in practice

No extra markup, no layout shift – the inline flow continues unchanged.

Key takeaways

  • <span> is an inline, non‑semantic container for styling fragments.
  • It does not break the text flow or create new lines.
  • Use a class or ID on <span> to target it with CSS.
  • More flexible than pseudo‑elements for arbitrary text selection (e.g., first word, first two lines).
  • Works on any inline content, including images or other elements.

Display Property

The display property controls whether an element behaves as a block or inline box. Intuitively: block elements claim their own horizontal line; inline elements sit next to each other like words. By changing display, you override the default behavior of any element.

Default flow: block vs. inline

By default:

  • Block-level elements (e.g., <div>, <p>) stack vertically and take up the full available width.
  • Inline elements (e.g., <span>, <a>) flow along the same line as adjacent content.
PropertyBlock elementInline element
WidthTakes entire parent widthShrinks to content
StackingAlways new lineStays on same line
Box modelRespects width, height, margin, padding fullyIgnores height, vertical margin; horizontal padding/margin only shift content on that line

Changing display values

Syntax: display: block | inline | inline-block | none;

Example

HTML: <div class="block">...</div> and <span class="inline">...</span>.

With .block { display: inline; } and .inline { display: block; }:

  • The <div> no longer spans full width — it becomes inline.
  • The <span> takes full width — it becomes block.

Key insight: The display property overrides an element’s native behaviour; any element can become any box type.

Box-model behavior: inline vs. block

When adding height, width, padding, margin:

  • Block element: all properties are respected. Padding and margin push surrounding content both horizontally and vertically.
  • Inline element: height and vertical margin are ignored. Padding is applied visually but does not push content above or below — it only affects that line. This makes inline elements unsuitable for layout control.

Inline-block: the hybrid

A third value, display: inline-block, combines the best of both:

  • The element stays inline (it aligns with text and other elements on the same line).
  • It respects all box-model properties (width, height, margin, padding) on every side.
ValueStays inline?Respects width/height?Respects vertical margin?
blockNoYesYes
inlineYesNoNo
inline-blockYesYesYes

Practical example

Three <div> boxes (class box) with height: 100px; width: 100px; margin: 20px;:

  • display: block → stacked vertically.
  • display: inline → side by side but dimensions collapse to content (100px ignored).
  • display: inline-block → side by side, dimensions respected.

Exam tip: Use inline-block for buttons, badges, or icons that need to sit beside text while having explicit width/height.

Display: none

display: none completely removes the element from the rendered page — it leaves no trace, as if the element never existed (unlike visibility: hidden which still occupies space).

Use case

Hide a button until a user completes an action (e.g., form fill). The button exists in the HTML and can be shown later via JavaScript by switching display to block or inline-block.

<button type="button" class="hidden-btn">Click me</button>
.hidden-btn { display: none; }

Key difference: The element is invisible and does not affect layout; perfect for dynamic toggling.

Key takeaways

  • display overrides an element’s default box type: block, inline, inline-block, or none.
  • Block elements take full width, stack vertically, and respect all box-model properties.
  • Inline elements flow horizontally; they ignore height and vertical margin.
  • Inline-block gives inline flow with full box-model control — ideal for aligned, dimensioned components.
  • display: none hides an element completely; it is removed from layout and can be toggled by JavaScript.

Position Property

The position property controls how an element is placed in the document — relative to its normal flow, a parent, the viewport, or the scroll position. It takes one of five values: static, relative, absolute, fixed, or sticky. Together with the offset properties top, right, bottom, left, you can fine-tune placement.

Static (position: static)

Default for all elements. The element follows normal document flow — block elements stack vertically, inline elements flow horizontally. Offset properties (top, left, etc.) have no effect; they are ignored.

MDN: The static property prevents top, left, etc. from having any effect. The element remains in its natural position.

Relative (position: relative)

The element stays in the normal flow (its original space is preserved), but you can shift it relative to its own original position using offset properties.

  • top: 50px moves the element down by 50px.
  • left: 50px moves it to the right by 50px (positive left adds space on the left side).
  • Negative offsets move in the opposite direction.

The original space remains occupied — other elements do not reflow into the gap.

Example: A green box with position: relative; top: 50px; left: 50px; appears 50px down and 50px right from where it would have been, while its original footprint stays empty.

Absolute (position: absolute)

The element is removed from normal flow — no space is reserved for it. It is positioned relative to the closest positioned ancestor (an ancestor whose position is not static). If no such ancestor exists, it positions relative to the initial containing block (typically the <html> element).

Offset properties (top, left, etc.) specify the distance from the edges of that containing block.

Key behaviour:

  • Other elements ignore the absolute element; they may overlap.
  • The containing block must be positioned (e.g., relative, absolute, fixed, or sticky) for the absolute child to nest inside it.

Example: A child div with position: absolute; top: 50px; left: 100px; inside a parent with position: relative; will be offset 50px from the top and 100px from the left of the parent’s content box. Without the parent being positioned, it would be relative to the document root.

Fixed (position: fixed)

The element is removed from normal flow and positioned relative to the viewport. It stays fixed in place even when the page is scrolled.

  • Offset properties (top, left, right, bottom) are relative to the viewport edges.
  • Commonly used for persistent navigation bars, back-to-top buttons, or sticky headers.

Example: A fixed element with top: 100px; left: 500px; remains 100px from the top and 500px from the left of the viewport, unaffected by scrolling.

Sticky (position: sticky)

A hybrid: the element behaves as relative until a specified scroll threshold is reached, then becomes fixed relative to the viewport (or its scrolling container). It stays “stuck” as long as its parent container is visible.

  • Must have at least one offset property (e.g., top: 50px) to define the sticky point.
  • The element remains in the normal flow and its original space is preserved – when it becomes fixed, it “sticks” but the reserved space remains.
  • Important: The element’s parent must contain enough scrollable content for the sticky behaviour to work. If the parent is too short, the element will never reach its sticky point.

Exam tip: Always ensure the sticky element’s parent has overflow content (or sufficient height) that can be scrolled; otherwise, sticky will appear broken.

Example: A heading with position: sticky; top: 0; inside a tall scrollable <div> will scroll normally until its top reaches the top of the viewport, then it “sticks” there while the rest of the content scrolls underneath.

Summary Table

ValueIn normal flow?Offset relative toSpace preserved?Page scroll effect
staticYes— (offsets ignored)YesScrolls normally
relativeYesIts own original positionYesScrolls normally
absoluteNoClosest positioned ancestor (or initial containing block)NoScrolls with document (unless in fixed ancestor)
fixedNoViewportNoStays fixed
stickyYes, until thresholdOwn flow, then viewportYesScrolls until threshold, then sticks

Worked Example (Conceptual)

Given three sibling boxes inside a container:

  • Box 1: static (default) → sits at top-left of container.
  • Box 2: relative; top: 30px; left: 20px; → moves down 30px and right 20px from where it would normally be; its original spot remains empty (visible as a gap).
  • Box 3: absolute; top: 0; right: 0; → container must have position: relative; otherwise Box 3 would go to document right‑top corner; it sits at top‑right corner of container, overlapping any content.

Key Takeaways

  • Use static for default flow; offsets are ignored.
  • relative keeps the element in flow but lets you nudge it; original space is preserved.
  • absolute removes the element from flow; position relative to the nearest positioned ancestor.
  • fixed pins the element to the viewport – stays on screen during scroll.
  • sticky toggles between relative and fixed at a defined scroll threshold; requires a scrollable parent.
  • The offset properties top, right, bottom, left only work when position is not static.

Float and Clear

Float and clear are CSS properties originally designed to wrap text around images—like a newspaper layout. Intuitively: you want an image on the side and let the text flow naturally around it. Float was not intended for overall page layout; use Flexbox or CSS Grid for that. Understanding float/clear, however, builds a solid CSS foundation.

The float Property

  • Purpose: Takes an element out of the normal document flow and positions it to the left or right, allowing inline content (e.g., text) to wrap around it.
  • Values: left | right | none (default)
  • Effect: The floated element stays part of the page but no longer participates in the normal flow—subsequent content “flows” around it.
/* Float an image to the left */
img {
  float: left;
}

Common pitfall: Because floated elements are removed from normal flow, they can cause overlapping or collapsed parent containers. This is why float is tricky for layouts.

The clear Property

  • Purpose: Applied to a non-floated element (e.g., a paragraph) to prevent it from wrapping around a floated element. It forces the element to start below any floated elements on the specified side.
  • Values: left | right | both | none (default)
ValueEffect
leftClears only left-floated elements; element starts below them.
rightClears only right-floated elements.
bothClears both left and right floats; element starts on a new line below.
/* Force a paragraph to appear below any left-floated elements */
#p-other {
  clear: left;
}

How they work together

Real example

Given an image floated left and two paragraphs:

  • Without clear: Both paragraphs wrap around the image.
  • With clear: left on the second paragraph: That paragraph starts below the image (on the left side), ignoring the float.
  • With clear: both: The element is forced below all floats on either side.

Caveat: float for layout is obsolete

Floated layouts are fragile—elements overlap, containers collapse, and responsive design becomes painful. Modern CSS provides Flexbox and Grid for robust, predictable layouts. Float should only be used for its original purpose: text wrapping around media.

Exam tip: If a question asks about the original purpose of float, answer wrapping text around images, not layout. And remember that clear is applied to the following element, not the floated one.

Key takeaways

  • float: left/right moves an element out of normal flow so text wraps around it.
  • clear: left/right/both forces a non-floated element to start below any floated elements.
  • Float was designed for newspaper-style text wrapping, not page layout.
  • For layout, use Flexbox or Grid.
  • Floated elements can cause unpredictable overlapping and container collapse.

Styling a Website with CSS

CSS (Cascading Style Sheets) controls the visual presentation of a web page. The goal is to apply styles consistently while making minimal changes to the HTML structure. Styling begins by inspecting the target design — colours, fonts, and layout — then replicating them through selectors, the box model, and pseudo-classes.

Extracting design specs

Use the CSS Overview tool in Chrome DevTools to capture the design system of a reference website:

  1. Right-click → Inspect → three-dot menu → More tools → CSS Overview.
  2. Capture an overview to see lists of text colours, background colours, font families, font sizes, and unused declarations.

Example: the IIMB website uses Times New Roman as font, and specific hex colours (e.g., #72828, #aabbcc).

Exam tip: The CSS Overview tool is not a standard exam requirement, but understanding how to extract colours and fonts from any page is a practical skill often tested in applied coding tasks.

Structuring the header

A header containing a logo image and a heading can be wrapped in a <div> with a class (e.g., main-div). Style it using the class selector (.main-div).

.main-div {
  border-bottom: 5px solid #72828;
  padding: 20px;
}

To align logo and heading side by side, set the immediate children (image and <h1>) to display: inline-block and use vertical-align: middle.

.main-div > * {
  display: inline-block;
  vertical-align: middle;
}

Spacing can be added via padding on the <h1>. For centering the header content, use calc() to subtract the logo width from 50%:

.main-div h1 {
  padding-left: calc(50% - 400px); /* approximate centering */
}

Exam tip: calc() is a powerful CSS function; you can combine any units. However, for production layouts, Flexbox or Grid are preferred (covered in the next module).

Global typography

Set a default font for the entire page using the element selector on html or body:

html {
  font-family: Times New Roman, serif;
}

Style headings and paragraphs with colour, font-size, and text alignment. Use the descendant selector to target elements after a specific parent (e.g., p immediately after .main-div):

.main-div + p {
  font-size: x-large;
  text-align: center;
  color: #72828;
}

Navigation interactivity

The navigation bar (<nav>) can be centred, padded, and its anchor links styled as buttons.

  1. Style the <nav> element: text-align: center; padding: 40px;
  2. Style the <a> tags inside <nav> using nav a selector.
nav a {
  display: inline-block;          /* allows padding */
  padding: 20px 10px;
  border: 3px solid red;
  border-radius: 30px;           /* rounded corners */
  background-color: #aabbcc;
  color: white;
  font-weight: bold;
}

Add interactivity with pseudo-class selectors:

Pseudo-classTriggerExample
:hoverMouse over elementChange background to a lighter colour, text to white
:activeWhile element is being clickedChange background to a darker colour
nav a:hover {
  background-color: lightblue;
  color: white;
}
nav a:active {
  background-color: darkblue;
}

These styles apply to all pages because the same CSS file is linked to every HTML file, and the selector (nav a) matches all navigation links.

Table styling

Tables use <th> (header cells) and <td> (data cells). Default behaviour shows separate borders with gaps — use border-collapse: collapse on the <table> element to merge them.

table {
  border-collapse: collapse;
  text-align: center;
  width: 100%;
}
th {
  border: 2px solid #72828;
  background-color: #aabbcc;
  color: white;
}
td {
  border: 1px solid #72828;
  padding: 10px;
}

Exam tip: border-collapse applies only to the <table> (or inline-table) element, not to <th> or <td>. Applying it to individual cells will have no effect.

Set column width using width on <th> or <td>, and adjust cell spacing with padding.

Form and button styling

Style <input>, <select>, and <button> elements to match the theme.

  • For input fields: border: 2px solid #72828
  • Apply to both <input> and <select> using a group selector: input, select { ... }
input, select {
  border: 2px solid #72828;
}
form {
  color: #72828;
}

Style the submit button (<button>):

button {
  background-color: #aabbcc;
  color: white;
  padding: 20px;
  border: none;
  border-radius: 20px;
  font-weight: bold;
}

Add hover and active effects with the same pseudo-class pattern as the navigation links.

Background and layout adjustments

Apply a background colour to the entire page using the body selector. Remove the default margin on body to eliminate white edges.

body {
  background-color: #e0e0e0;
  margin: 0;
}

To prevent the header from inheriting the background, give the .main-div a white background. Use the main element (already present in HTML) to add padding for content below the header.

.main-div {
  background-color: white;
}
main {
  padding: 10px;
}

The box model is referenced whenever inspecting sizes in the DevTools – padding, border, and margin can be observed and adjusted directly.

Exam tip: The box model (content → padding → border → margin) is fundamental. When styling, always check the computed dimensions in the Elements panel to debug unexpected spacing.

Key takeaways

  • Use CSS Overview in DevTools to extract a design’s colours and fonts.
  • Style with class selectors (.class) and element selectors (e.g., html, body).
  • Align elements side-by-side with display: inline-block and vertical-align: middle.
  • Add interactivity via :hover and :active pseudo-classes.
  • Tables require border-collapse: collapse on the <table> to remove gaps.
  • Use calc() for dynamic spacing; prefer Flexbox/Grid in production.
  • Always check the box model in DevTools to understand padding, border, and margin contributions.