External CSS is a method of adding CSS to one or more HTML documents using a separate stylesheet file. The CSS rules are written in a file with the .css extension and linked to the HTML document using the <link> tag.
In this chapter, you will learn what External CSS is, its syntax, how to link a CSS file, examples of External CSS, and its advantages and disadvantages.
External CSS is used when the same styles are required on multiple HTML pages. Instead of writing CSS inside every HTML document, all CSS rules are stored in a separate file with the .css extension.
The HTML document is connected to the stylesheet using the <link> tag, which is placed inside the <head> section. Any changes made to the external CSS file are automatically reflected on every HTML page that uses that stylesheet.
The following syntax is used to link an external stylesheet to an HTML document.
<head>
<link rel="stylesheet" href="style.css">
</head>
In this syntax:
The following example demonstrates how to use an external stylesheet.
HTML File:
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
</head>
CSS File (mystyle.css):
body {
background-color: lightblue;
}
h1 {
color: navy;
margin-left: 20px;
}
Explanation
In this example:
One external stylesheet can be shared by multiple HTML pages.
index.html
about.html
contact.html
style.css
All three HTML files contain the following code inside the <head> section:
<link rel="stylesheet" href="style.css">
Explanation
All the HTML pages use the same style.css file. If the stylesheet is modified, the changes are automatically applied to every page linked to it.
An external stylesheet is created as a separate file with the .css extension. It contains only CSS rules and does not include HTML tags.
p {
color: green;
font-size: 18px;
}
button {
background-color: blue;
color: white;
}
Explanation
The stylesheet contains CSS rules for paragraphs and buttons. These styles are applied to every HTML document that links this stylesheet.
The href attribute can specify the location of the CSS file using a relative path.
<link rel="stylesheet" href="css/style.css">
Explanation:
In this example, the CSS file named style.css is stored inside the css folder. The browser loads the stylesheet using the specified path.
We request you to subscribe our newsletter for upcoming updates.