Unays Learn ยท CSS

CSS selectors and the box model

Most CSS confusion comes from two things: styles applying to the wrong elements, and boxes being bigger than expected. This guide explains both.

Choosing elements with selectors

p { }              /* every paragraph */
.note { }          /* every element with class="note" */
#signup { }        /* the element with id="signup" */
nav a { }          /* links inside a nav */
.card > h2 { }     /* h2 that is a direct child of .card */
a:hover { }        /* a link while the pointer is over it */
input:focus-visible { } /* an input focused with the keyboard */

Prefer classes for styling. They are reusable, and you can give an element several: class="card featured".

When two rules disagree

If two rules set the same property, the more specific selector wins: an id beats a class, and a class beats an element name. If they are equally specific, the rule written later wins.

.note { color: green; }
p { color: blue; }
/* <p class="note"> is green: a class beats an element */

Keep selectors short and avoid !important. It breaks the normal rules and makes later changes harder.

The box model

Every element is a box made of four layers, from the inside out:

  1. Content: the text or image.
  2. Padding: space inside the border.
  3. Border: the line around the box.
  4. Margin: space outside the border, pushing other boxes away.
.card {
  width: 300px;
  padding: 20px;
  border: 2px solid #17594f;
  margin: 16px;
}

By default width sets only the content, so this card is actually 300 + 40 + 4 = 344 pixels wide.

The border-box fix

Most developers add this rule at the top of every stylesheet so width includes padding and border:

*, *::before, *::after {
  box-sizing: border-box;
}

Now the card above is exactly 300 pixels wide, which makes layouts far easier to reason about.

Inspect the boxes

Right-click any element and choose Inspect. The developer tools show which rules apply (crossed-out rules lost to a more specific one) and a diagram of the element's margin, border and padding. It is the fastest way to answer "why is this here?"

Try it yourself

In Unays Code, make three cards with different padding and borders. Measure them in the inspector, then add the border-box rule and see what changes. Continue with Flexbox and Grid.

This tutorial was written with AI assistance and reviewed by Unays. The runnable code examples were tested before publishing. Spotted a mistake? Tell us at [email protected].