Using external style sheets (CSS)

In the previous tutorial, we look at how to use inline styling and internal style sheets to change the colour of text and apply some basic CSS formatting to a web page. However, what if you want to apply a theme to several pages across a web page? Won’t it be difficult to manually update the styling in every single page if you want to modify the theme? Well, we can use external style sheets to solve that problem.

By using external style sheets, we store the CSS properties and values inside a separate file eg. mystylesheet.css and we reference that style sheet in every HTML file we want to apply the style to. The image below shows how to reference a CSS file:

Referencing an external style sheet.
Referencing an external style sheet.

The image below shows how to add CSS properties and values to an external style sheet (.css file):

An external style sheet (.css file).
An external style sheet (.css file).

Watch the video below to see how to use external style sheets and then scroll down to see the sample code.

The sample code for the HTML file:

<!DOCTYPE html>
<html>
<head>
 <title>Adding CSS to a webpage using external stylesheets</title>
 <meta charset="utf-8"/>
 <link rel="stylesheet" href="stylesheet.css" type="text/css"/>
</head>
 
<body>
 <h1>This is a heading.</h1>
 <h2>A smaller heading</h2>
 <p>This is a paragraph</p>
</body>
 
</html>

And here is the code for the external style sheet (the stylesheet.css file):

h1{
 color:red;
 border: solid 1px;
}
 
h2{
 background-color:yellow;
}
 
p{
 color:blue;
}