Learn CSS from Scratch

Colors, Units and the Box Model

Lesson 3 of 9 2 min read Updated 28 September 2026

Colours

color: red;                 /* name */
color: #2563eb;             /* hex */
color: rgb(37, 99, 235);    /* rgb */
color: hsl(221, 83%, 53%);  /* hsl */
background: rgba(0, 0, 0, 0.5);  /* with transparency */

Units

UnitMeaning
pxFixed pixels
%Percent of the parent
emRelative to the element's font size
remRelative to the root font size (best for text)
vw, vhPercent of viewport width or height

The box model

Every element is a box made of four layers, from inside to outside: content, padding, border and margin.

<style>
.box {
  width: 200px;
  padding: 20px;
  border: 4px solid #2563eb;
  margin: 30px;
  background: #eff6ff;
  box-sizing: border-box;
}
</style>
<div class="box">Box model demo</div>
  • Padding is space inside the border.
  • Margin is space outside the border.
  • With box-sizing: border-box, width includes padding and border, which makes layouts much easier. Most developers set it for every element:
*, *::before, *::after { box-sizing: border-box; }

Shorthand

margin: 10px 20px 30px 40px; /* top right bottom left */
padding: 10px 20px;          /* vertical horizontal */

Margin collapsing and centring

Vertical margins between block elements can collapse: when a paragraph with margin-bottom: 20px sits above one with margin-top: 30px, the gap is 30px, not 50px. Horizontal margins never collapse.

To centre a block horizontally, give it a width and set the side margins to auto:

.container { max-width: 900px; margin: 0 auto; }

Borders, outlines and rounded corners

.card { border: 1px solid #e5e7eb; border-radius: 12px; }
.avatar { border-radius: 50%; }          /* a circle when width equals height */
button:focus { outline: 3px solid #93c5fd; outline-offset: 2px; }

An outline is drawn outside the border and does not change the layout. Never remove focus outlines without giving keyboard users another clear focus style.

Inspect it in your browser

Right-click any element and choose Inspect. The browser shows its box model diagram with the exact content, padding, border and margin sizes. This is the fastest way to debug spacing problems.

Practice

Create a card 300px wide with padding, a border, rounded corners using border-radius and a light shadow using box-shadow: 0 4px 12px rgba(0,0,0,0.1);.