Lesson 4 / 7

CSS Selectors and the Box Model

Selectors

p { color: navy; }                  /* every <p> */n.highlight { background: yellow; }  /* any element with class="highlight" */n#main-title { font-size: 40px; }    /* the one element with id="main-title" */nnav a { text-decoration: none; }    /* <a> elements inside <nav> */

A class (.name) can be reused on many elements; an ID (#name) should appear on exactly one element per page. Prefer classes for styling in almost every case — IDs carry higher CSS specificity, which makes them harder to override later and is a common source of “why won’t my CSS apply” frustration.

The box model

Every single HTML element is, as far as CSS is concerned, a rectangular box made of four layered parts, from the inside out: content, padding (space inside the border), border, and margin (space outside the border, between this box and its neighbors).

.card {n    width: 300px;n    padding: 20px;n    border: 1px solid #ccc;n    margin: 16px;n}

box-sizing: border-box

* {n    box-sizing: border-box;n}

By default, width: 300px sets only the content area — padding and border get added on top, so a box with 20px of padding on each side ends up 340px wide, not 300px. This is confusing enough that virtually every real project applies box-sizing: border-box globally, which makes width include padding and border, matching what most people intuitively expect.

Colors and units

color: #1a1a1a;        /* hex */ncolor: rgb(26, 26, 26); /* red, green, blue */nfont-size: 16px;        /* fixed pixels */nfont-size: 1.2rem;      /* relative to the root font-size -- scales with user settings */

rem units respect a visitor’s browser font-size preference, which matters for accessibility — someone who has increased their default text size for readability should see that respected across your whole site, not just wherever you happened to use rem instead of a fixed px.