Skip to main content
HTML & CSS Foundations·Lesson 2 of 5

CSS Fundamentals

CSS controls how HTML elements look on screen. Before diving into layouts, you need a solid understanding of how styles are selected, calculated, and applied.

Selectors

Selectors target the elements you want to style. Here are the ones you will use most:

Ctrl+Enter
HTML
CSS
JS
Preview

Specificity

When multiple rules target the same element, specificity determines which one wins. Think of it as a three-part score: (ID, Class, Element).

SelectorSpecificityScore
p(0, 0, 1)1
.card(0, 1, 0)10
#hero(1, 0, 0)100
.card p(0, 1, 1)11
#hero .title(1, 1, 0)110

Practical rules:

  • Prefer classes over IDs for styling.
  • Avoid !important — it breaks the cascade and makes debugging painful.
  • Keep selectors short. .card-title beats .sidebar .card .card-body .card-title.

The Box Model

Every element is a rectangular box with four layers:

┌─────────── margin ───────────┐
 ┌──────── border ──────────┐ 
  ┌────── padding ───────┐  
                          
        content           
                          
  └──────────────────────┘  
 └──────────────────────────┘ 
└──────────────────────────────┘

By default, width sets the content width, and padding/border are added on top. This is confusing, so always use border-box:

Ctrl+Enter
HTML
CSS
JS
Preview

With border-box, a width: 300px element stays 300px total, including padding and border.

Ctrl+Enter
HTML
CSS
JS
Preview

Units

Choose the right unit for the job:

UnitUse forBase
pxBorders, shadows, fine detailsAbsolute
remFont sizes, spacing, widthsRoot font size (usually 16px)
emPadding/margin relative to current fontCurrent element's font size
%Widths relative to parentParent dimension
vw / vhViewport-relative sizingViewport width/height
dvhFull-height layouts on mobileDynamic viewport height
Ctrl+Enter
HTML
CSS
JS
Preview

Tip: Use rem for most spacing. It scales consistently and makes responsive adjustments easy — change the root font size, and everything updates.

Custom Properties (CSS Variables)

Custom properties let you define reusable values and swap them dynamically:

Ctrl+Enter
HTML
CSS
JS
Preview

Custom properties cascade and inherit, making them perfect for theming. Change the variable in one place, and every element using it updates.

Practical Reset

A minimal reset gives you a consistent starting point:

Ctrl+Enter
HTML
CSS
JS
Preview

This reset eliminates default margins, makes images responsive, and ensures form elements inherit font styles.