Does the order the of the <link> elements matter?


#1

Question

Does the order the of the <link> elements matter?

Answer

The order of <link> elements matters when we have conflicting CSS selectors - the linked resouce with the conflicting selector that is physically lower in the HTML document will be applied. This has to do with the concept of cascade; the order of CSS rules matters.

Say we have two CSS files with a conflicting selector:

stylesheetOne.css:

h1 {
  color: red;
}

stylesheetTwo.css:

h1 {
  color: green;
}

Given the following HTML, which color will be applied to the <h1> element?:

<!DOCTYPE html>
<html>
<head>
  <title>My Site</title>
  <link rel="stylesheet" href="stylesheetTwo.css">
  <link rel="stylesheet" href="stylesheetOne.css">
</head>
<body>
  <h1>Hello World</h1>
</body>
</html>

The <h1> element will have the color: red; style applied because the stylesheetOne.css file is physically lower in our HTML document.

When implementing Bootstrap we will want to make sure our <link> to Bootstrap comes before the <link> to our own CSS file, otherwise, prewritten CSS declarations in Bootstrap may override styles we’ve declared.