How to use the HTML <style> Element

Learn how to use the HTML <style> element.

The <style> element is used to embed styles directly into your HTML document:

<style>
  h1 {
    color: red;
  }
  p {
    color: green;
  }
</style>

The <style> element lives inside your HTML document’s <head> element:

<!DOCTYPE html>
<html>
  <head>
    <style>
      h1 {
        color: red;
      }
      p {
        color: green;
      }
    </style>
  </head>
  <body>
    <h1>This is a red heading</h1>
    <p>This is a green paragraph</p>
  </body>
</html>

You can also import an external stylesheet, which is done with the <link> element. This is generally the preferred method, at least on on larger websites.

Good to know:

If you use both the <style> and the <link> element to style in the same document, it’s easy to override styles by mistake.

For example, look at the following example, which uses both styling approaches:

<!DOCTYPE html>
<html>
  <head>
    <!-- Embedded (internal) styles -->
    <style>
      h1 {
        color: red;
      }
      p {
        color: green;
      }
    </style>
    <!-- Import external style sheet -->
    <link href="/styles/main.css" rel="stylesheet" />
  </head>
  <body>
    <h1>This is a red heading</h1>
    <p>This is a green paragraph</p>
  </body>
</html>

So for example if the external stylesheet defines a color property value on the h1 and p selector, e.g. by giving it a blue color value, then the red and green will be overwritten, because the <link> element comes after the <style> element in the markup example above.

It’s so easy to mix this up, therefore I advice that you generally stick to using the <link> element to import styles — and only use the <style> element for highly specific use cases.


Has this been helpful to you?

You can support my work by sharing this article with others, or perhaps buy me a cup of coffee 😊

Kofi

Share & Discuss on