Learning Objectives

By the end of this session, you will be able to:

LO1Apply CSS to HTML using inline, internal, and external methods.
LO2Use element, class, ID, combinator, attribute, and pseudo selectors.
LO3Calculate specificity and resolve style conflicts.
LO4Explain the cascade and how inheritance works.
LO5Apply the box model, including box-sizing.
LO6Use color formats: keyword, HEX, RGB(A), HSL(A).
LO7Style text with core typography properties.
LO8Embed custom fonts with @font-face and Google Fonts.
LO9Apply backgrounds, gradients, borders, and shadows.
LO10Build a fully styled UI component from scratch.

Aligned to: CO2 — Design and develop well-structured, standards-compliant web pages using HTML5 and CSS3 following accessibility and web standards guidelines.

Quick Recap: CSS Syntax & How We Apply It

CSS = Cascading Style Sheets — it separates presentation (how a page looks) from structure (HTML)

selector {
  property: value;
  property: value;
}

p { color: navy; }
Inlinestyle="color:red;" — Highest priority. Avoid for maintainability.
Internal<style> in <head> — Fine for single-page demos.
External<link rel="stylesheet"> — Best practice: cacheable & reusable across pages.
Try it » Inline vs. Internal
Result
💡 Rule of thumb: keep styles in an external .css file linked from <head> — it separates concerns and lets the browser cache it.

External stylesheet — try it live

This box simulates a real project: the left pane is your HTML, the right pane is a separate styles.css "file". Change color below (try purple or #2f9e5c), then click Run.

Try it Yourself » External Stylesheet
index.html
styles.css
Result
🔗 In a real project, styles.css would be its own file on disk, linked with <link rel="stylesheet" href="styles.css"> in <head> — exactly like css3-fundamentals.html links to lesson-style.css. Both panes here just let you edit HTML and CSS separately, the same way you would across two real files, without leaving the browser.

01 · Selectors & Specificity

How CSS targets elements — and how conflicts get resolved

Basic Selector Types

The five ways to target elements before you add relationships or state

* Universal* { margin: 0; } — targets every element
E Type / Elementp { line-height: 1.6; } — targets every element of that tag
. Class.card { padding: 1rem; } — targets every element with that class
# ID#main-nav { ... } — targets the one element with that ID
, Groupingh1, h2, h3 { font-family: ...; } — applies one rule to several selectors
Try it Yourself »
Result
Best practice: prefer classes for reusable styling. Reserve IDs for unique, single-use hooks (and JS/anchor targets), not general styling.

Combinators — Selecting by Relationship

Target an element based on its position relative to another

A B Descendant.card p { } — any B inside A, at any depth
A > B Child.card > p { } — B is a direct child of A
A + B Adjacent siblingh2 + p { } — B immediately after A
A ~ B General siblingh2 ~ p { } — any B after A, same parent
Try it Yourself »
Result

Attribute Selectors & Pseudo-Classes

Target elements by their attributes, or by the state they're currently in

Attribute selectors

[type="text"]input[type="text"] { }
[href^="https"]a[href^="https"] { } — ^= starts with
[href$=".pdf"]a[href$=".pdf"] { } — $= ends with
[alt]img[alt] { } — has the attribute at all

Pseudo-classes — element in a state

:hovera:hover { color: orange; }
:focusinput:focus { outline: 2px solid; }
:first-childli:first-child { margin-top: 0; }
:last-childli:last-child { margin-bottom: 0; }
:nth-child(2n)tr:nth-child(2n) { background: #f5f5f5; }
:not(...)button:not(.disabled) { cursor: pointer; }
Try it Yourself »
Result

Pseudo-Elements — Styling a Part of an Element

::before and ::after insert generated content before/after an element's content — icons, quote marks, clearfix hacks

Try it » Where does each one land?
Result

Real-world use: decorative quote marks that aren't part of the actual text (so screen readers and copy/paste skip them)

Try it » Smart Quotes
Result

::first-line and ::first-letter are also common — for editorial / magazine-style typography.

Who Wins? The Specificity Hierarchy

When two rules target the same element, the browser scores each selector and the higher score wins

1000Inline style — style="color:red;"
100ID selector — #header { }
10Class / Attribute / Pseudo-class — .btn, [type], :hover
1Element / Pseudo-element — p, ::before

Worked example

#nav .item a:hover { color: orange; }
#nav1 ID  →  +100
.item1 class  →  +10
:hover1 pseudo-class  →  +10
a1 element  →  +1

Total specificity = 100 + 10 + 10 + 1 = 121

!important overrides normal specificity entirely — powerful, but makes styles hard to override later. Use sparingly.

02 · The Cascade

How the browser picks a winner when rules conflict

Order of Precedence When Rules Conflict

1Origin & Importance — user !important > author !important > author styles > user styles > browser default
2Specificity — higher specificity wins (inline > ID > class > element)
3Source Order — if specificity ties, the last rule declared wins
Try it Yourself » Which Rule Wins?
Result
Edit the CSS above: reorder rules, delete the #winner rule, or add !important — then click Run and watch which color wins change with it.

Inheritance & Special Values

Some properties pass down from parent to child automatically — others don't

Inherited by default

color, font-family, font-size, line-height, text-align, visibility

Not inherited by default

margin, padding, border, background, width, height

inheritForce this property to take its parent's computed value
initialReset the property to the CSS spec's default value
unsetActs as inherit if the property normally inherits, else initial
revertReset to the browser's built-in (user-agent) stylesheet value
Try it Yourself » Inheritance in Action
Result

03 · The Box Model

Every element is a box: content, padding, border, margin

Content → Padding → Border → Margin

Contentwidth / height — the actual text, image, etc.
PaddingSpace between content and the border
BorderThe line around the padding (width, style, color)
MarginSpace between this box and neighboring elements
Try it Yourself »
Result

box-sizing: content-box vs border-box

content-box (default)width: 300px applies to content only — rendered width = 300 + padding + border
border-box (recommended)width: 300px includes padding + border — rendered width stays 300px, padding/border eat into the content area instead
Try it Yourself »
Result
*, *::before, *::after { box-sizing: border-box; } /* common reset — predictable sizing */

Margin Collapsing & Inspecting the Box Model

Margin collapsing

When two block elements stack vertically, their top/bottom margins can overlap and collapse into a single margin — equal to the larger of the two, not the sum.

Try it »
Result
DevTools tip: Right-click any element → Inspect → the Elements panel's Computed tab shows a live box-model diagram with real pixel values for content, padding, border, and margin. Use it to debug unexpected spacing before changing any CSS.

04 · Colors

Five ways to describe the same color in CSS

CSS Color Formats

Keywordsteelblue
HEX#4682B4
RGBrgb(70, 130, 180)
RGBArgba(70, 130, 180, 0.6) — with alpha (transparency)
HSLhsl(207, 44%, 49%)
Try it Yourself »
Result
💡 Why HSL? Hue-Saturation-Lightness makes it easy to create tints/shades of the same hue — just change the L value. Remember: opacity affects the whole element + children; the alpha channel (RGBA/HSLA) only affects that color.

05 · Typography

Font families, sizing units, and text styling

Font Families & Font Stacks

font-family: "Poppins", "Segoe UI", Arial, sans-serif;
SerifTimes New Roman, Georgia
Sans-serifArial, Helvetica, Calibri
MonospaceCourier New, Consolas
Try it »
Result
Always end a font stack with a generic family as a fallback — if custom fonts fail to load, the browser still renders sensibly.

Sizing Units: px, %, em, rem

pxFixed pixel value — doesn't scale with user/browser settings. e.g. 16px
%Relative to the parent element's font-size. e.g. 150%
emRelative to the current element's (or parent's) font-size — compounds when nested. e.g. 1.5em
remRelative to the root (<html>) font-size — predictable, recommended for accessibility. e.g. 1.5rem
Try it »
Result

Core Text Styling Properties

font-weightnormal | bold | 100–900
font-stylenormal | italic
line-height1.5 (unitless preferred)
letter-spacing0.5px
text-alignleft | center | right | justify
text-decorationunderline | line-through | none
text-transformuppercase | capitalize
text-indent2em
Try it Yourself »
Result

06 · Web Fonts

Going beyond web-safe fonts with @font-face and Google Fonts

@font-face & Google Fonts

Self-hosted with @font-face
@font-face {
  font-family: "Poppins";
  src: url("poppins.woff2")
       format("woff2");
  font-weight: 400;
  font-display: swap;
}
Hosted via Google Fonts
<link rel="stylesheet"
  href="https://fonts.googleapis.com/css2?family=Poppins&display=swap">
body { font-family: "Poppins", sans-serif; }
Try it »
Result
💡 font-display: swap shows a fallback font immediately, then swaps once the custom font loads — avoids invisible text while waiting.

07 · Backgrounds

Color, images, positioning, and gradients

Background Properties

background-color#f5f5f5
background-imageurl("bg.jpg")
background-repeatno-repeat | repeat-x
background-positioncenter | 20px 40px
background-sizecover | contain
background-attachmentfixed | scroll
Try it Yourself »
Result
/* shorthand */
background: #222 url(bg.jpg) no-repeat center / cover;

08 · Borders

Widths, styles, colors, and rounded corners

Border Styles & border-radius

border: 2px solid #1572B6;
border-top: 4px dashed #e8622c;
Try it Yourself »
Result
💡 border-radius: 50% on a square element makes a perfect circle — the classic technique for circular avatars.

09 · Shadows

Adding depth with box-shadow and text-shadow

box-shadow & text-shadow

box-shadow: 0 4px 12px rgba(0,0,0,.25);
/*           x  y  blur  spread  color */

text-shadow: 2px 2px 4px rgba(0,0,0,.5);
Try it »
Result
Tip: stack multiple shadows (comma-separated) for richer depth, or use inset for a pressed-in look.

Laboratory Activity

Style a Profile Card  ·  contact styles.css  ·  20 points

🖥️ Task: Starting from a plain, unstyled HTML file, apply everything from today's session to build a polished profile card component.
✓Link an external stylesheet (styles.css)
✓Use 3+ selector types, including one pseudo-class (:hover)
✓Apply box-sizing: border-box globally
✓Define a custom color palette (HEX or HSL)
✓Apply a Google Font or @font-face to headings
✓Add a background (gradient or image)
✓Round the avatar into a circle with border-radius
✓Apply box-shadow to the card and text-shadow to the name
4 ptsSelectors & Specificity
3 ptsBox Model
3 ptsColors
4 ptsTypography / Web Fonts
2 ptsBackgrounds
2 ptsBorders
2 ptsShadows
💡 Save as styles.css linked from your profile card HTML  ·  Total: 20 points

Key Takeaways

CSS3 Fundamentals: Selectors · Specificity · Cascade · Box Model · Colors · Typography · Web Fonts · Backgrounds · Borders · Shadows

  1. CSS separates presentation from structure — external stylesheets are best practice.
  2. The cascade resolves conflicts using importance, specificity, then source order.
  3. The box model (content, padding, border, margin) underlies all CSS layout.
  4. Consistent color, type, and spacing choices are what make an interface feel professional.
  5. These fundamentals are the foundation for the next lesson: Flexbox, Grid, and positioning.

References

Course resources for this topic

MDN Web DocsCSS Reference — developer.mozilla.org/en-US/docs/Web/CSS
CSS-Trickscss-tricks.com
W3SchoolsCSS Tutorial — w3schools.com/css
Duckett, J. (2014)HTML & CSS: Design and Build Websites. Wiley.
Freeman & Robson (2020)Head First HTML and CSS (2nd ed.). O'Reilly.
Robbins, J. N. (2018)Learning Web Design (5th ed.). O'Reilly.

▶ Next Week

CSS3 Layouts & Responsive Design

Flexbox, Grid, Positioning, Variables, Transitions & Animations, Mobile-First, Media Queries, Bootstrap 5