Colors and Units

How to say exactly what color and what size

7 min read

Two questions come up in almost every CSS rule you write: what color, and how big? This lesson gives you the vocabulary to answer both.

Naming colors

The easiest way to pick a color is by name. CSS understands around 140 color names, from the plain ones like red and black to lovely ones like tomato, rebeccapurple, and lightseagreen:

body {
  background-color: lightseagreen;
}

Named colors are perfect for experimenting. But 140 names cannot cover the millions of colors a screen can show, so CSS also has more precise ways to describe color.

Hex codes

A hex code starts with a hash and is followed by six characters, like #1e90ff. The first two describe how much red is in the color, the next two how much green, and the last two how much blue. You do not need to read them by eye. Any color picker will give you the hex code, and you just paste it in:

h1 {
  color: #1e90ff;
}

Hex codes are the most common color format on the web. When a designer says "use our brand blue", they will usually hand you a hex code.

RGB

The same idea, written with plain numbers from 0 to 255: rgb(30, 144, 255) is the same blue as #1e90ff. RGB is handy because there is a fourth option, alpha, which controls transparency. rgba(30, 144, 255, 0.5) is that blue at half transparency, which is great for subtle overlays.

Units: how big is big?

When you set sizes in CSS, you attach a unit to the number. These are the ones you will meet first:

  • px (pixels) is a fixed size. font-size: 20px; means the same thing on every screen. Simple and predictable, great for starting out.
  • % is relative to the parent element. width: 50%; means half as wide as whatever contains it.
  • rem is relative to the page's base font size, which is usually 16px. So 1rem is 16px and 1.5rem is 24px. Rems are popular because if a visitor increases their browser's font size, everything sized in rems scales up with it.

Here is a rule using all three:

.intro {
  font-size: 1.25rem;
  width: 80%;
  margin-bottom: 24px;
}

Do not stress about picking the perfect unit yet. A good beginner habit is: pixels for small fixed things like borders, rems for font sizes, and percentages for widths that should flex with the page.

Try this on your own site: pick a color you love from a color picker website, copy its hex code, and set it as the color of your headings. One line of CSS, instant personality.

Quick check

Q1 Which of these is a hex color code?

Q2 If the base font size of the page is 16px, how big is 2rem?

Want to save your progress? It's free.

Create a free account