Adding CSS Styles to an HTML Document

There are three main ways to add CSS styles to an HTML document:

  1. inline as an attribute of an element,
  2. within the <style></style> element, or
  3. linked to a separate file.

⚠️ Don’t forget that although you can include CSS inside your HTML that CSS is an entirely different language. This can get particularly confusing for beginners.

Adding CSS Styles with the style Attribute

<p style="background: blue; color: white;">This is a paragraph.</p>

These show up as the element.style in your Developer Tools

Adding CSS Styles with the style Element

The <style></style> element can be anywhere in your HTML document. Usually they are within <head></head> but not necessarily.

Notice the main difference is that we now need a CSS selector.

<!doctype html>
<html>
  <head>
    <title>Hello World</title>
    <style>
      body, html {
        background: #000000;
      }
    </style>
  </head>
  <body>
    <p>Hello World</p>
  </body>
</html>

⚠️ It is very common to forget the selectors in this form of doing it.

So perhaps the most common way to use styles is to put them in another separate file and link them in.

First you have to have a file. Something like the following would be named styles.css and right next to the index.html file.

body, html {
  background: #000000;
}

Notice there are no <style></style> tags here because they are HTML, not CSS.

<!doctype html>
<html>
  <head>
    <title>Hello World</title>
    <link rel=stylesheet href="styles.css">
  </head>
  <body>
    <p>Hello World</p>
  </body>
</html>

⚠️ Keep in mind that you will see a lot of tutorials out there that still have type="text/css", which is entirely deprecated and unnecessary now (and has been for years).