This write-up will discuss the procedure for adding an external CSS file in HTML. We will also explain linking and importing an external CSS file in HTML. Moreover, examples related to the mentioned methods will be provided. So, let’s start!
How to add an external CSS file in HTML
There are two methods for adding an external CSS file HTML: linking and importing.
Linking an external CSS file in HTML
First of all, we will create a CSS file in HTML. For this purpose, you can open your favorite code editor; however, we will use Visual Studio Code.
After opening VS Code, we will create a “style.css” CSS file for adding styles:
Next, we will specify the style we want to apply to the web page in the opened CSS file. Here, we have assigned the values to the “background” and “font” properties for the HTML “body” and also added the “color” for the heading:
font: 18px Arial, sans-serif;
Press “Ctrl+S” to save the added code in the “style.css” file:
The “<link>” tag is utilized for linking an external CSS to an HTML file. This tag is added in the “<head>” section of an HTML document. We have linked our HTML file with “style.css” in the below-given program, using the <link> tag. Then, we have added a heading with the <h1> tag and a paragraph with the <p> tag. The specified style in the “style.css” file will be applied to these HTML elements:
As you can see, we have successfully applied the specified style to our HTML elements by linking them with the external CSS file:
Importing an external CSS file in HTML
You can import an external CSS file in HTML by simply adding the “@import” declaration in the <style> tag of the HTML document. In this way, you will be allowed for adding other CSS rules for the HTML elements, within the same <style> tag:
Our “myProject.html” file has the following HTML elements with the applied styles: