How to use the HTML <link> Element

Learn how to use the HTML <link> element.

The HTML <link> element is primarily used to import external CSS files that add styles to your website.

The <link> element lives inside the <head> element, and accepts several types of attributes:

<!DOCTYPE html>
<html>
  <head>
    <title>Document title</title>
    <link href="/styles/main.css" rel="stylesheet" />
  </head>
  <body></body>
</html>

The most common <link> element attributes are the two you see above, href and rel:

  • href specifies the location of your linked file, in this case a style sheet called main.css
  • rel stands for relationship, and it specifies the relationship between the document it sits inside and the linked CSS file.

An alternative way to style your website is to use the <style> element, which allows you to embed CSS styles directly inside your document (also called inline CSS).

However, the modern way of styling websites is to use <link> to import styles, either from your own project folder your-project/styles/main.css, or from an external provider (on another domain).

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