Skip to content

Try our new Crash Courses!

Buy one of our new Crash Courses, now hosted on Podia.

Linking a CSS file to an HTML file

Summary

To link a CSS file to an HTML file, use the link element with the rel and href attributes.

<link rel="stylesheet" href="main.css">

Details

For the link element, the href attribute specifies the file path to the CSS file. The rel attribute specifies the relationship the link has to the HTML file. For CSS files, the rel attribute should be set to “stylesheet”.

The link element should be placed in the head element of your HTML file, like in the example below. The exact position inside the head element doesn’t matter. In this case, we placed it between the meta element and the title element, but it could’ve been placed before or after them. The important thing is to be consistent about the placement in your HTML files so you always know where to find the link elements.

<head>
  <meta charset="UTF-8">

  <link rel="stylesheet" href="main.css">

  <title>Document</title>
</head>

If your CSS file is inside a separate folder, make sure to include the folder path in your value for the href attribute. In the example below, the main.css file is inside a file called css.

<head>
  <meta charset="UTF-8">

  <link rel="stylesheet" href="css/main.css">

  <title>Document</title>
</head>

Multiple Stylesheets

If you need to add multiple stylesheets, you can include multiple link elements, like in the example below:

<head>
  <meta charset="UTF-8">

  <link rel="stylesheet" href="main.css">
  <link rel="stylesheet" href="more-styles.css">
  <link rel="stylesheet" href="even-more-styles.css">

  <title>Document</title>
</head>

Remember that rules in the later stylesheets can potentially override styles in the earlier stylesheets. Sometimes you might want to override styles, while other times this may be undesired behavior, so be careful.

Exercises

Add a link element to the index.html file and link the main.css file to it (use the snippet in the Summary as an example).
Check the index.html file in your browser to make sure the files are connected (the text should turn red).

References

The External Resource Link element on MDN

Back to: CSS Reference > CSS Introduction