Log inSign up free
Mastering Modern CSS: From Zero to Pro
  1. Getting started

    1. CSS Lesson 1: What Is CSS?
    2. CSS Lesson 2: Selectors and Rules
    3. CSS Lesson 3: How CSS Works: The Cascade
    4. CSS Lesson 4: Colour and Backgrounds
    5. CSS Lesson 5: Typography and Text
    6. CSS Lesson 6: The Box Model
    7. CSS Lesson 7: Units and Sizing
    8. CSS Lesson 8: Display and Positioning
    9. CSS Lesson 9: Flexbox
    10. CSS Lesson 10: Grid
    11. CSS Lesson 11: Responsive Design
    12. CSS Lesson 12: Final Project
Mastering Modern CSS: From Zero to Pro

Getting started · Lesson 4 of 12 · 13 min read · By Jack

CSS Lesson 4: Colour and Backgrounds

By the end, you'll be able to write colours as named, hex, RGB and HSL values, add transparency, and set text, background and border colours.

Downloads for this lesson

Sign up free (or log in) to download these files.

Learning goals: By the end, you'll be able to:

  • write colours as named values, hex, rgb() and hsl()
  • add transparency with an alpha value
  • set text, background and border colours
  • add background images and gradients
  • check text for readable contrast
  • build a small, consistent colour palette

Part 1: Colour in CSS (2 min)

Colour is the quickest way to make a page look designed. You'll use it in three main places:

PropertyColours...
colorthe text
background-colorthe area behind the content
border-color (or the border shorthand)the border

All of them accept the same colour formats, which this lesson covers.

h1 {  
  color: navy;  
  background-color: #fef9c3;  
  border: 2px solid rgb(29, 78, 216);  
}

Part 2: Named colours (2 min)

CSS has about 140 colour keywords, such as red, tomato, navy, skyblue and lightgray.

p {  
  color: darkslategray;  
  background-color: lightyellow;  
}

Named colours are:

  • easy to read and remember
  • great for learning and quick tests
  • limited, because you can't fine-tune a shade

gray and grey both work. The first rows of css_lesson4_colour_values.csv show named colours next to their hex, RGB and HSL equivalents.

Quick check A. What's wrong with color: ff0000;, and what happens?


Part 3: Hex, RGB and HSL (8 min)

Hex

A hex colour is a # followed by six characters. They form three pairs: red, green, blue. Each pair runs from 00 (none) to ff (full), which is 0 to 255 in everyday numbers.

color: #ff0000;   /* full red, no green, no blue */  
color: #000000;   /* black */  
color: #ffffff;   /* white */  
color: #1d4ed8;   /* a strong blue */

If every pair has a repeated digit, you can shorten it:

color: #ff6600;  
color: #f60;      /* same colour */

Hex digits go 0 to 9, then a to f (a is 10 and f is 15). So ff is 255. Hex is the format you'll see most in design tools and style guides.

RGB

The same three channels, written as decimal numbers from 0 to 255:

color: rgb(255, 0, 0);       /* red */  
color: rgb(29, 78, 216);     /* same as #1d4ed8 */

Mixing light works differently to mixing paint. rgb(255, 255, 255) is white, and rgb(0, 0, 0) is black.

HSL

HSL describes a colour the way people think about it:

PartRangeMeaning
Hue0 to 360Position on the colour wheel: 0 red, 60 yellow, 120 green, 180 cyan, 240 blue, 300 magenta
Saturation0% to 100%0% is grey, 100% is vivid
Lightness0% to 100%0% is black, 50% is normal, 100% is white
color: hsl(225, 73%, 57%);   /* a royal blue */  
color: hsl(225, 73%, 30%);   /* the same blue, darker */  
color: hsl(225, 73%, 85%);   /* the same blue, much lighter */

HSL is the easiest format to adjust by hand. To get a darker or lighter shade, change only the lightness. With hex or RGB, you'd have to change all three channels.

Transparency (alpha)

Add a fourth value to make a colour see-through, from 0 (invisible) to 1 (solid).

background-color: rgb(0 0 0 / 0.5);          /* 50% black */  
background-color: rgba(0, 0, 0, 0.5);        /* older syntax, same result */  
background-color: hsl(225 73% 57% / 0.2);    /* 20% blue */  
background-color: #1d4ed880;                 /* 8-digit hex: last pair is alpha */

Alpha lets whatever is behind the element show through.

Which should you use?

FormatBest for
NamedLearning and quick tests
HexCopying colours from design tools
RGBWhen you need to add alpha, or work with channel numbers
HSLBuilding shades and palettes by hand

All four are equally valid. Pick one format and stay consistent in a project.

Quick check B. Write #f60 in full six-digit form, and in rgb().

Quick check C. What colours are rgb(0, 0, 0) and rgb(255, 255, 255)?

Quick check D. Roughly what colour is hsl(0, 100%, 50%)? What about hsl(0, 0%, 50%)?

Quick check E. You have hsl(220, 80%, 50%) as a button colour. Write a darker version for the hover state.


Part 4: Background colour and opacity (3 min)

background-color fills the content area and the padding, up to the border.

body {  
  background-color: #f9fafb;  
  color: #1f2937;  
}  
  
.card {  
  background-color: #ffffff;  
  border: 1px solid #e5e7eb;  
  padding: 16px;  
}

Always set text and background colours together. If you only set one, a user's settings (such as dark mode in some browsers) could produce an unreadable mix.

Opacity vs alpha

There are two ways to make something see-through, and they behave differently.

.fade   { opacity: 0.5; }                              /* the whole element fades */  
.panel  { background-color: rgb(0 0 0 / 0.5); }        /* only the background fades */

opacity fades everything in the element, including its text and children. An alpha colour affects only the colour it's applied to. For a see-through panel with crisp text, use alpha.

Quick check F. You want a half-transparent black box with fully solid white text inside. Do you use opacity: 0.5 or an alpha background? Why?


Part 5: Background images and gradients (5 min)

Background images

.hero {  
  background-image: url("images/hero.jpg");  
  background-size: cover;  
  background-position: center;  
  background-repeat: no-repeat;  
  color: #ffffff;  
  min-height: 300px;  
}
PropertyCommon valuesEffect
background-imageurl("...")Choose the image
background-repeatno-repeat, repeat, repeat-x, repeat-yBy default, images tile
background-sizecover, contain, 200pxcover fills the box (may crop), contain fits the whole image (may leave gaps)
background-positioncenter, top right, 50% 20%Where the image sits

Notes:

  • The path in url() is relative to the CSS file, not the HTML file.
  • Add a background-color as a fallback, in case the image is slow or fails to load.
  • Background images are decoration. If an image carries meaning, use an <img> with alt text instead (Lesson 5 of the HTML course).
  • You can combine everything with the background shorthand:
.hero {  
  background: #1e3a8a url("images/hero.jpg") center / cover no-repeat;  
}

Gradients

A gradient is a generated image that blends colours.

.banner {  
  background-image: linear-gradient(to right, #1d4ed8, #7c3aed);  
}  
  
.banner-angled {  
  background-image: linear-gradient(135deg, #f59e0b, #ef4444, #8b5cf6);  
}

You can set a direction (to right, 135deg) followed by two or more colours.

A dark overlay for readable text

You can stack backgrounds, separated by commas. The first one sits on top.

.hero {  
  background-image:  
    linear-gradient(rgb(0 0 0 / 0.5), rgb(0 0 0 / 0.5)),  
    url("images/hero.jpg");  
  background-size: cover;  
  background-position: center;  
  color: #ffffff;  
}

The semi-transparent black layer darkens the photo so white text stays readable.

Quick check G. What's the difference between background-size: cover and background-size: contain?


Part 6: Contrast and accessibility (4 min)

Text must stand out clearly from its background. Poor contrast affects people with low vision, colour blindness, or anyone reading on a phone in sunlight.

The Web Content Accessibility Guidelines (WCAG) set a minimum contrast ratio, from 1:1 (identical colours) to 21:1 (black on white):

LevelNormal textLarge text (about 24px, or 19px bold)
AA (the usual target)4.5 : 13 : 1
AAA (enhanced)7 : 14.5 : 1

I calculated these ratios with the WCAG formula, and the full list is in css_lesson4_contrast_pairs.csv:

TextBackgroundRatioNormal text AA
#1f2937#ffffff14.68 : 1Pass
#1d4ed8#ffffff6.70 : 1Pass
#6b7280#ffffff4.83 : 1Pass
#9ca3af#ffffff2.54 : 1Fail
#fffffftomato #ff63472.95 : 1Fail
#000000tomato #ff63477.13 : 1Pass
#ffff00#ffffff1.07 : 1Fail

Notice that white on tomato fails, but black on tomato passes comfortably. Don't assume white text works on every bold colour.

Practical habits:

  • Light grey text on white is the most common failure. Use a darker grey for body text.
  • Don't use colour as the only signal. For errors, add words or an icon, not just red.
  • Chrome and Edge DevTools show a contrast ratio in the colour picker when you click a colour swatch in the Styles panel. Use it to check as you build.
  • Test with your screen brightness turned down.

Quick check H. Which ratios pass AA for normal-sized text: 3.5 : 1, 4.6 : 1, 6.9 : 1?

Quick check I. #9ca3af text on white has a ratio of 2.54 : 1. Does it pass for large text?


Part 7: Building a simple palette (3 min)

Beginner pages often look messy because they use too many colours. Use a small, fixed palette:

RoleExampleUsed for
Primary#1d4ed8Links, buttons, headings
Accent#f59e0bOne highlight, such as a call to action
Text#1f2937Body copy
Background#f9fafbPage background
Surface#ffffffCards and panels
Border#e5e7ebDividing lines

Use HSL to generate related shades from one colour by changing lightness:

/* Same hue and saturation, different lightness */  
/* 95%  90%  70%  50%  30%  10% */  
background-color: hsl(220, 80%, 95%);   /* very pale */  
background-color: hsl(220, 80%, 50%);   /* main */  
background-color: hsl(220, 80%, 30%);   /* dark */

Pick your colours at the start, write them in a comment at the top of your stylesheet, and use only those:

/*  
  Palette  
  Primary:    #1d4ed8  
  Accent:     #f59e0b  
  Text:       #1f2937  
  Background: #f9fafb  
  Surface:    #ffffff  
  Border:     #e5e7eb  
*/

(Later you could store these as CSS variables. That's one of the bonus lessons.)


Common mistakes

MistakeFix
color: ff0000;Add the #: #ff0000
colour: red;Use the US spelling, color
Missing ) in rgb(0, 0, 0;Close every bracket
Image path wrong in url()Paths are relative to the CSS file
Tiled background imageAdd background-repeat: no-repeat
opacity used for a see-through boxUse an alpha colour so the text stays solid
Light grey text on whiteCheck contrast and darken the text
Seven different colours on one pageStick to a small palette
Text colour set without a background colourSet both together

Key takeaways

  • Colours can be written as names, hex, rgb() or hsl(), and all are valid.
  • Hex pairs and RGB channels both cover 0 to 255.
  • HSL is easiest for making shades, because you change only lightness.
  • Alpha makes a colour see-through, while opacity fades the whole element including text.
  • background-image, size, position and repeat control images, and gradients are generated images.
  • A dark overlay gradient keeps text readable on photos.
  • Meet at least 4.5 : 1 contrast for normal text.
  • A small palette keeps a design consistent.

Exercises (15 min guided, plus extras)

1. Convert (3 min).

  • a) #ff8800 to rgb()
  • b) #3366cc to rgb()
  • c) rgb(0, 128, 255) to hex
  • d) rgb(255, 255, 0) to hex

Hint: ff is 255, 80 is 128, 00 is 0. Each pair is two hex digits, and cc is 204.

2. Describe the colour (2 min). Describe each in plain words:

  • a) hsl(60, 100%, 50%)
  • b) hsl(240, 100%, 50%)
  • c) hsl(0, 0%, 50%)
  • d) hsl(0, 100%, 90%)

3. Fix the errors (3 min). There are five errors in this CSS:

body {  
  background-color: #f9fafb  
  color: 1f2937;  
}  
  
h1 {  
  color: rgb(29, 78, 216;  
}  
  
.hero {  
  background-image: url(hero.jpg)  
  background-size: cover;  
}  
  
.card {  
  background-colour: lightyellow;  
}

4. Pick the readable pair (2 min). Which of these would you use for body text on a white page, and why? Name the best one.

  • a) #1f2937
  • b) #6b7280
  • c) #9ca3af

5. Build it: a palette card page (10 min). Create colour.html and colour.css.

  1. In colour.css, write a six-colour palette as a comment at the top.
  2. Style body with a background colour and text colour from your palette.
  3. Add a <header class="hero"> with an <h1>. Give it either a gradient background or a background image (any image saved in an images folder) with a dark overlay. Make the heading text white.
  4. Add three <div class="swatch"> elements. Colour the first with a hex value, the second with rgb() and the third with hsl(), all using the same colour so they look identical.
  5. Add a fourth swatch using a semi-transparent alpha colour over a coloured background.
  6. Choose a text and background pair for one paragraph and check its contrast in DevTools.

6. Challenge (4 min). Choose a hue and write five swatches using HSL with lightness of 90%, 70%, 50%, 30% and 10%. Add white text to each and check which swatches have enough contrast. Then open css_lesson4_contrast_pairs.csv and add three pairs of your own.


Lesson 4 checkpoint

  • I can write a colour as a name, hex, rgb() and hsl().
  • I can convert a simple hex colour to RGB.
  • I can make lighter and darker shades using HSL.
  • I know the difference between alpha and opacity.
  • I can add a background image with cover and no-repeat.
  • I can create a gradient and a dark overlay.
  • I can check that text meets the 4.5 : 1 contrast target.


⬇️ ANSWER KEY (only scroll once you've tried the questions)

Quick check A: The # is missing. A hex colour must start with it, so the browser ignores the declaration and the text keeps its previous colour.

Quick check B: #ff6600, which is rgb(255, 102, 0). Each digit is repeated, and 66 in hex is 102.

Quick check C: Black and white.

Quick check D: hsl(0, 100%, 50%) is pure red. hsl(0, 0%, 50%) is mid-grey, because zero saturation removes all colour.

Quick check E: Lower the lightness, for example hsl(220, 80%, 35%). The exact number is up to you, as long as hue and saturation stay the same.

Quick check F: An alpha background, such as rgb(0 0 0 / 0.5). opacity: 0.5 would fade the white text too.

Quick check G: cover scales the image to fill the whole box, which may crop some of it. contain scales it to fit entirely inside, which may leave empty space.

Quick check H: 4.6 : 1 and 6.9 : 1 pass. 3.5 : 1 fails for normal text (it would pass for large text only).

Quick check I: No. 2.54 : 1 is below the 3 : 1 minimum for large text, so it fails at both sizes.

Exercise 1:

  • a) rgb(255, 136, 0)
  • b) rgb(51, 102, 204)
  • c) #0080ff
  • d) #ffff00

Exercise 2:

  • a) pure yellow
  • b) pure blue
  • c) mid-grey
  • d) a very light red, like pale pink

Exercise 3 (corrected):

body {  
  background-color: #f9fafb;  
  color: #1f2937;  
}  
  
h1 {  
  color: rgb(29, 78, 216);  
}  
  
.hero {  
  background-image: url(hero.jpg);  
  background-size: cover;  
}  
  
.card {  
  background-color: lightyellow;  
}

The five errors were: a missing semicolon after #f9fafb, a missing # on 1f2937, a missing closing bracket in rgb(...), a missing semicolon after url(hero.jpg), and background-colour spelt with a u.

Exercise 4: Option a (#1f2937) is best, at 14.68 : 1. Option b (#6b7280) passes at 4.83 : 1 but only just, so it suits secondary text. Option c (#9ca3af) fails at 2.54 : 1.

Exercise 5: Check that the three swatches look identical, the alpha swatch lets the background show through, the heading text is easy to read over the hero, and the palette comment is at the top of the file. Your paragraph pair should show a ratio of at least 4.5 in DevTools.

Exercise 6: Using the same hue and saturation, white text generally passes only on the darker swatches (30% and 10% lightness), and fails on the pale ones. The exact cut-off depends on your hue, so use the DevTools ratio to confirm.

Keep track of your learning

This lesson comes with 3 downloads. Create a free account to unlock them and track your progress.

  • Track your progress through every course
  • Take the quizzes and see your score
  • Download the worksheets and resources
  • Get a certificate when you finish

Related reading on our blog

Rather have it done for you?

We build websites for small businesses

Everything in this course is what we do every day for local businesses: fast, mobile-friendly sites that are built to be found on Google. See our web design services or our website packages.