CSS: selectors, colour, fonts and classes

HTML says what things are. CSS says what they look like. You can put CSS inside a <style> tag, and it is made of rules:

h1 {
  color: crimson;
  font-size: 40px;
}

Read that as: "find every h1, make its text crimson and 40 pixels tall". The part before the curly brackets is the selector (which elements). Inside are declarations, each one a property: value; pair. Forget the semicolon and the next line often gets ignored, with no error message. CSS fails silently, which is rude but you get used to it.

Some properties you will use constantly:

  • color: the text colour
  • background-color: the colour behind it
  • font-size: how big the text is, like 18px
  • font-family: the typeface, like Georgia, serif

Note the American spelling: it is color, never colour, no matter how you spell it in real life.

A tag selector like p hits every paragraph. Usually you want to pick just some of them, and for that you use a class. Give the element a class attribute, then select it with a dot:

<p class="warning">Do not feed the gremlins.</p>

.warning {
  color: red;
}

One class can go on as many elements as you like, and one element can have several classes separated by spaces: class="warning big". That is how real sites stay consistent: style a class once, reuse it everywhere.

Try it yourself

Edit it. Break it. Run it again.
<style>
  body {
    font-family: Arial, sans-serif;
  }
  h1 {
    color: teal;
    font-size: 36px;
  }
  .tip {
    background-color: lightyellow;
    font-style: italic;
  }
</style>
<h1>Styling 101</h1>
<p>This paragraph only gets the body font.</p>
<p class="tip">This one has the tip class, so it gets a yellow background too.</p>
Ctrl/Cmd + Enter runs. Esc, then Tab, leaves the editor.

Your turn

Type it yourself. That is the whole trick.

1Red heading

Write a CSS rule in the <style> tag that makes the <h1> text red.

<style>
  /* your rule goes here */
</style>
<h1>Danger zone</h1>
Ctrl/Cmd + Enter runs. Esc, then Tab, leaves the editor.

2Highlight one paragraph

Create a class called highlight that sets background-color to yellow. Then put that class on the second paragraph only.

<style>
</style>
<p>First paragraph.</p>
<p>Second paragraph, the important one.</p>
<p>Third paragraph.</p>
Ctrl/Cmd + Enter runs. Esc, then Tab, leaves the editor.

Code editor. Press Control or Command plus Enter to run the code. Tab indents; to move focus out of the editor, press Escape and then Tab.