Skip to content

Module 03 — Basic CSS & Responsive Styling


1. What is it?

CSS (Cascading Style Sheets) is the declarative stylesheet language used to describe the visual presentation, formatting, color schemes, typography, and responsive geometry of documents authored in markup languages like HTML.

While HTML defines the structural semantics of nodes (what an element is), CSS dictates how those nodes are rendered by the browser's graphical engine (how an element looks, moves, and responds to screens).


2. Why do we use it?

Prior to CSS (in HTML 3.2), styling had to be embedded directly into HTML attributes (e.g., <font color="red" size="4">, <body bgcolor="#000000">). This caused severe engineering problems:

  1. Separation of Concerns: HTML was cluttered with presentation rules, making codebases bloated, error-prone, and impossible to maintain.
  2. Global Consistency: Changing the primary brand color across a 1,000-page enterprise website required editing every single file. With external CSS, changing one variable in a single stylesheet updates the entire web application instantaneously.
  3. Bandwidth Efficiency: Browsers cache external .css files. Once downloaded on the initial page visit, subsequent page transitions render without re-fetching stylistic assets.
  4. Device Adaptability: CSS allows a single HTML codebase to render comfortably on smartwatches, smartphones, tablets, high-resolution desktop monitors, and printed paper via Media Queries.

3. Simple Explanation

Return to our house analogy:

  • HTML gave us the raw concrete walls, window frames, and doorways.
  • CSS is the Architectural Design & Styling: It paints the walls in matte slate, lays down hardwood flooring, installs warm recessed ambient lighting, spaces out the furniture so you don't stub your toe, and ensures the chairs automatically reconfigure whether 1 guest or 10 guests enter the living room.

Without CSS, the web is a stark black-and-white document with blue underlined links. CSS transforms that raw text into modern, responsive, and visually engaging digital products.


4. Technical Explanation: The CSSOM & Cascade Algorithm

When the browser parses HTML and encounters a <link rel="stylesheet">, it initiates the CSS processing pipeline:

CSS Text Stream


Tokenization & Parsing


CSSOM Tree Construction (CSS Object Model)


Cascade Resolution (Specificity, Origin, Importance, Source Order)


Computed Style Calculation (Resolving relative units like rem/% to absolute pixels)

The 3 Ways to Apply CSS:

  1. External Stylesheet (Industry Best Practice): <link rel="stylesheet" href="styles.css"> inside <head>. Cached by browsers and fully separated from markup.
  2. Internal Style Tag: <style> ... </style> inside <head>. Useful for critical above-the-fold styling in single-document deployments.
  3. Inline Styles: <div style="color: blue;">. Avoid in production. Inline styles carry an astronomical specificity weight (1-0-0-0), cannot be cached, clutter HTML, and break design systems.

5. Syntax & Anatomy of a CSS Rule

A CSS rule consists of a Selector and a Declaration Block:

css
selector {
  property: value;
  property: value;
}
┌─────────────────────────────────────────────────────────────┐
│                          CSS RULE                           │
├───────────────┬─────────────────────────────────────────────┤
│   SELECTOR    │              DECLARATION BLOCK              │
├───────────────┼─────────────────────────────────────────────┤
│ .primary-card │ {                                           │
│               │   background-color: #ffffff; ◄── Declaration│
│               │   ▲                 ▲                       │
│               │   │                 └─ Value                │
│               │   └─ Property                               │
│               │   border-radius: 8px;                       │
│               │ }                                           │
└───────────────┴─────────────────────────────────────────────┘

6. CSS Selectors Mastery

Selectors instruct the browser which DOM nodes to target. Understanding selectors prevents messy code:

Selector TypeSyntaxExampleTargetSpecificity
Universal** { box-sizing: border-box; }Every single node in the DOM0-0-0-0
Type / Elementelementh1 { font-family: sans-serif; }All <h1> tags0-0-0-1
Class.class.btn { cursor: pointer; }All elements with class="btn"0-0-1-0
ID#id#header { position: sticky; }Unique element with id="header"0-1-0-0
Attribute[attr="val"]input[type="email"] { border: red; }Elements with matching attribute0-0-1-0
Grouping,h1, h2, h3 { line-height: 1.2; }Applies shared rules to all 3Separate
DescendantA Bnav a { color: white; }Any <a> inside <nav> at any depthCombined
Child (Direct)A > Bul > li { list-style: none; }Only <li> that are direct children of <ul>Combined
Adjacent SiblingA + Bh2 + p { margin-top: 0; }<p> immediately following an <h2>Combined
General SiblingA ~ Bh2 ~ p { color: #555; }All <p> elements preceded by an <h2>Combined

Common Pseudo-Classes:

  • User Action: :hover, :focus, :focus-visible, :active.
  • Structural: :first-child, :last-child, :nth-child(2n) (even), :nth-child(odd).
  • State: :disabled, :checked, :valid, :invalid.

7. Color Systems & Modern Color Functions

Colors in CSS can be expressed across multiple color spaces:

  • HEX (Hexadecimal): #0ea5e9 (RGB in base-16) or #0ea5e9cc (with alpha channel).
  • RGB & RGBA: rgb(14, 165, 233) or rgba(14, 165, 233, 0.8).
  • HSL & HSLA: hsl(199, 89%, 48%) (Hue 0–360°, Saturation 0–100%, Lightness 0–100%). HSL is human-friendly because adjusting lightness does not alter the fundamental hue.
  • Modern CSS Color Level 4 Syntax:
    css
    /* Slash syntax for alpha channel */
    background-color: rgb(14 165 233 / 80%);
    color: hsl(199 89% 48% / 0.9);

IMPORTANT

WCAG Contrast Ratios: Always guarantee sufficient contrast between text and background. Normal text requires at least 4.5:1 (WCAG AA), while large text (18pt+ or bold 14pt+) requires at least 3:1.


8. Typography & Font Engineering

css
body {
  /* Font stack with system fallbacks */
  font-family: 'Inter', system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  font-size: 1rem;            /* 16px default browser root size */
  font-weight: 400;           /* Normal weight */
  line-height: 1.6;           /* Unitless line height for proportional scaling */
  letter-spacing: -0.01em;    /* Subtle tracking */
  text-rendering: optimizeLegibility;
  -webkit-font-smoothing: antialiased;
}

h1 {
  font-size: 2.25rem;         /* 36px */
  font-weight: 800;
  line-height: 1.2;
  text-wrap: balance;         /* Modern CSS: Prevents awkward typographical orphans */
}
  • Unitless line-height: Never declare line-height: 24px on parent containers. Use unitless numbers like 1.5 or 1.6. Child elements will multiply their own respective font-size by the multiplier, preventing text collisions!

9. The CSS Box Model: Mental Architecture & border-box Reset

Every element rendered on a screen is a rectangular box consisting of four concentric layers:

┌───────────────────────────────────────────────────────────┐
│                          MARGIN                           │
│   (Transparent space outside the border separating boxes) │
│  ┌─────────────────────────────────────────────────────┐  │
│  │                       BORDER                        │  │
│  │        (The boundary outline surrounding padding)   │  │
│  │  ┌───────────────────────────────────────────────┐  │  │
│  │  │                    PADDING                    │  │  │
│  │  │     (Interior breathing room inside border)   │  │  │
│  │  │  ┌─────────────────────────────────────────┐  │  │  │
│  │  │  │                 CONTENT                 │  │  │  │
│  │  │  │        (Text, images, child nodes)      │  │  │  │
│  │  │  └─────────────────────────────────────────┘  │  │  │
│  │  └───────────────────────────────────────────────┘  │  │
│  └─────────────────────────────────────────────────────┘  │
└───────────────────────────────────────────────────────────┘

The Universal box-sizing: border-box Reset:

Under legacy box-sizing: content-box, if you declare width: 200px; padding: 20px; border: 2px solid black;, the total rendered width becomes: $$\text{Total Width} = 200 + 20 + 20 + 2 + 2 = 244\text{px}$$ This calculation caused layouts to constantly break and overflow.

Modern web applications solve this globally using the Universal Box-Sizing Reset:

css
*, *::before, *::after {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

Under border-box, width: 200px represents the total visual footprint. Adding padding or borders absorbs space inward from the content area, never expanding outward.


10. Dimensions & Units: Absolute vs Relative

  • px (Pixels): Fixed absolute screen dots. Useful for thin decorative borders (border: 1px solid).
  • rem (Root EM): Relative to the root <html> font size (default 16px). Highly accessible because if a user changes their default browser font size for readability, all rem-based paddings, margins, and headings scale proportionally.
  • em: Relative to the current element's or parent's font-size. Ideal for button padding that scales automatically with font size.
  • %: Relative to the parent container's dimension.
  • vw / vh: 1% of viewport width / height.
  • dvh / svh / lvh: Modern dynamic viewport units that account for disappearing mobile address bars.

11. CSS Display: Normal Flow vs None

The display property controls how an element participates in the page flow:

  • display: block: Starts on a new line, takes full width, respects width, height, margin, padding (e.g., <div>, <p>).
  • display: inline: Flows inside text, ignores width and height, and vertical margins do not push adjacent lines away (e.g., <span>, <a>).
  • display: inline-block: Flows inline like text, but respects width, height, vertical margins, and paddings. Perfect for buttons and badges.
  • display: none: Completely removes the element from both the visual screen and the Accessibility Tree (takes zero space).
  • visibility: hidden: Hides the element visually, but preserves its blank space in the document layout.

12. CSS Positioning: Static, Relative, Absolute, Fixed, Sticky

Static (Default document flow)

Relative (Offset relative to itself; creates coordinate anchor)

Absolute (Removed from flow; positioned relative to nearest non-static ancestor)

Fixed (Removed from flow; pinned relative to viewport window)

Sticky (Hybrid: flows normally until scroll threshold, then sticks)

The Absolute-Inside-Relative Pattern:

To position an element (such as a badge or close icon) inside a card:

css
.card {
  position: relative; /* Acts as the coordinate anchor for child */
  padding: 24px;
  background: white;
  border-radius: 12px;
}

.card-badge {
  position: absolute;
  top: 12px;
  right: 12px;
  background: #0ea5e9;
  color: white;
  padding: 4px 8px;
  border-radius: 20px;
}

13. Mobile-First Responsive Design & Media Queries

Mobile-first engineering means authoring base CSS for mobile screens first, then layering on complexity for larger viewports using min-width queries:

css
/* Base Styles: Mobile (Default for all screen sizes) */
.grid-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
  padding: 16px;
}

/* Tablet Breakpoint (>= 768px) */
@media (min-width: 768px) {
  .grid-container {
    flex-direction: row;
    flex-wrap: wrap;
  }
  .grid-item {
    flex: 1 1 calc(50% - 16px);
  }
}

/* Desktop Breakpoint (>= 1024px) */
@media (min-width: 1024px) {
  .grid-container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 32px;
  }
  .grid-item {
    flex: 1 1 calc(33.333% - 16px);
  }
}

14. Common Mistakes & Gotchas

  1. Margin Collapsing Confusion:
    • Problem: When two vertical margins meet (e.g., margin-bottom: 20px on heading and margin-top: 30px on paragraph), they do NOT add up to 50px. They collapse into the single largest margin (30px).
    • Solution: Modern layouts avoid vertical margin collapsing entirely by using Flexbox or CSS Grid with the gap property.
  2. Fixed Width Layout Breaking on Mobile:
    • Bad: .container { width: 1200px; } (Causes horizontal scrollbars on mobile phones).
    • Fix: .container { width: 100%; max-width: 1200px; margin: 0 auto; }.
  3. Overusing #id Selectors in CSS:
    • IDs carry heavy specificity (0-1-0-0) that cannot be overridden by classes without messy specificity wars. Always style using classes (.btn).
  4. Hardcoding Heights on Text Containers:
    • Bad: .card { height: 200px; }
    • If a user increases font size or text wraps to two lines, text overflows outside the box. Always prefer min-height or let content dictate height with padding.

15. Technical Interview Questions & Answers

Q1: Explain the CSS Box Model and how box-sizing: border-box alters its behavior.

Answer: The CSS Box Model represents every element as four nested rectangles: Content, Padding, Border, and Margin. Under the initial W3C specification (box-sizing: content-box), the width and height properties apply strictly to the inner content area. Any padding and borders added are calculated outwards, expanding the total rendered footprint of the element. Under box-sizing: border-box, the specified width and height encompass content, padding, and border combined. Any padding or border applied reduces the inner content area rather than expanding the box, allowing developers to build predictable fluid grid systems.

Q2: What is the containing block for an element with position: absolute?

Answer: An element with position: absolute is removed from the normal document flow. Its containing block (the coordinate reference for top, right, bottom, left) is determined by the nearest ancestor whose position property is set to anything other than static (such as relative, absolute, fixed, or sticky), or an ancestor that has a transform, perspective, or filter applied. If no such positioned ancestor exists, the element is positioned relative to the Initial Containing Block (the viewport origin).


16. Quick Revision Checkpoints

  • Always apply the universal box-sizing reset: *, *::before, *::after { box-sizing: border-box; }.
  • Use rem for typography and spacing, px for thin borders, % for container bounds.
  • Unitless line-height: 1.5 prevents text collision bugs on inherited elements.
  • position: relative on parents acts as an anchor for position: absolute children.
  • Always design mobile-first using min-width media queries.

17. Next Topic & Learning Path

Proceed to Module 04 — Advanced CSS, Flexbox & Grid, where we explore the complete Cascade specificity algorithm, @layer, modern selectors (:has()), deep Flexbox & Grid layouts, clamp(), container queries, animations, and design tokens.

G-TEC Jain Keerti Education — Global Leader in IT Education