Kodokon kodokon.com

Linking CSS to a page

Discover what CSS is, how to connect it to an HTML page, and how to write your very first rule.

8 min · 3 questions

Open this lesson in Kodokon

HTML describes the content of a web page: the headings, the paragraphs, the images. CSS (short for Cascading Style Sheets) describes its appearance: the colors, the sizes, the spacing. Picture a house: HTML is the walls and the rooms; CSS is the paint, the furniture and the decoration. Without CSS, every web page would look the same: black text on a white background.

A CSS rule is made of three parts. First comes a selector: it says which elements on the page are affected (for example, all the paragraphs). Then, between curly braces { }, come one or more declarations. Each declaration pairs a property (what you want to change, such as the color) with a value (the choice you make, such as red), separated by a colon : and ended with a semicolon ;.

CSS
p {
  color: red;
  font-size: 18px;
}
A CSS rule: all paragraphs in red, sized at 18 pixels.

Let's read this rule word by word. p is the selector: it targets every <p> element on the page, in other words the paragraphs. color is a property that sets the text color, and red is its value. font-size sets the text size, here 18px (18 pixels, the unit used to measure screens). There are three ways to connect this CSS to an HTML page. The recommended method is the external file: the CSS lives in its own file, for example styles.css, which you plug into the HTML with a <link> tag placed inside the <head>.

HTML
<!DOCTYPE html>
<html lang="en">
  <head>
    <link rel="stylesheet" href="styles.css">
  </head>
  <body>
    <p>This text will be red.</p>
  </body>
</html>
The <link> tag connects the styles.css file to the page.

Second method: internal CSS. You write the rules straight into the HTML, inside a <style> tag placed in the <head>. That's handy for a quick test, but the styles only apply to that one page. Third method: inline CSS. You write the declarations directly on a tag, in a style attribute. Notice that there is no selector and no curly braces, since the style applies only to that tag.

HTML
<head>
  <style>
    p {
      color: red;
    }
  </style>
</head>
<body>
  <p style="color: blue;">I am blue.</p>
  <p>I am red.</p>
</body>
Internal CSS inside <style>, and inline CSS on the first <p>.

Knowledge check

Make sure you remember the key points of this lesson.

  1. In the rule p { color: red; }, what is color?
    • The selector
    • The property
    • The value
    • The semicolon
  2. Which tag connects an external CSS file to an HTML page?
    • <style>
    • <css>
    • <link rel="stylesheet" href="styles.css">
  3. Why is the external CSS file the recommended method?
    • It is the only one that works on mobile
    • A single file can style several pages at once
    • It automatically makes the site faster to code