Methods of Including CSS in HTML
Category Programming Technology
There are four ways to include CSS in HTML. Two of these methods involve directly adding CSS code within the HTML file, while the other two involve linking to external CSS files. Let's explore these methods and their pros and cons.
Inline Method
The inline method refers to adding CSS directly within the style
attribute of an HTML tag.
Example:
<div style="background: red"></div>
This is generally a poor practice as it only changes the style of the current tag. If multiple <div>
elements need the same style, you have to repeat the same style for each <div>
. If you need to modify a style, you have to change it in all the style
attributes. Clearly, using inline CSS makes the HTML code verbose and difficult to maintain.
Embedded Method
The embedded method involves writing CSS code within the <style>
tag in the HTML head.
Example:
<head>
<style>
.content {
background: red;
}
</style>
</head>
Embedded CSS is only effective for the current webpage. Since the CSS code is within the HTML file, it keeps the code centralized, which is beneficial when writing template pages. However, this method leads to code redundancy and poor maintainability when multiple pages need the same CSS.
Linked Method
The linked method involves using the <head>
tag in HTML to link to an external CSS file.
Example:
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
This is the most common and recommended way to include CSS. With this method, all CSS code resides in a separate CSS file, ensuring good maintainability. The CSS file is loaded once during the initial page load, and subsequent page switches only require loading the HTML file.
Import Method
The import method involves using a CSS rule to import an external CSS file.
Example:
<style>
@import url(style.css);
</style>
Comparison of Linked and Import Methods
Both the linked method (referred to as link) and the import method (referred to as @import
) are ways to include external CSS files. Here, we compare these methods and explain why @import
is not recommended.
-
link is part of HTML and uses the href attribute in the <link>
tag to reference external files, while @import
is part of CSS and should be written within the CSS. Note that import statements should be at the beginning of the stylesheet to ensure proper import;
-
@import
is a concept introduced in CSS2.1, so older browsers may not support it correctly;
-
When an HTML file is loaded, the file referenced by link is loaded simultaneously, whereas the file referenced by @import
is loaded only after the entire page is downloaded;
Summary: We should primarily use the <link>
tag to import external CSS files and avoid or minimize the use of the other three methods.
>
Article source: https://segmentfault.com/a/1190000003866058