There are four main ways to apply CSS to HTML: adding inline styles to HTML elements, embedding styles using the <style>
tag, linking external stylesheets using the <link>
tag, and importing external stylesheets using @import
.
Embedded styles cannot be cached by the browser and reused for other pages.
<link>
is an HTML tag, while @import
is a CSS statement. It is worth noting that @import
statements need to be placed at the beginning of the CSS stylesheet to correctly import external files.@import
is a concept introduced in CSS 2.1, so older browser versions like IE4 and IE5 cannot correctly import external stylesheets. This can be used to hide CSS2 rules for these older browser versions.<link>
are loaded simultaneously, while files referenced by @import
are loaded after the entire page has finished downloading. Therefore, sometimes pages using @import
to load CSS may appear without styles, causing a flickering effect, especially when the internet connection is slow.<link>
tag can have a rel
attribute, where rel="stylesheet"
means that the stylesheet is applied immediately to the document, and rel="alternate stylesheet"
means that it is an alternate stylesheet that is not applied immediately to the document. The <link>
tag can be accessed using JavaScript, and the stylesheet can be switched immediately by setting the disabled
property, making it useful for switching themes and other functionalities. @import
, on the other hand, is not part of the DOM and cannot be controlled directly using JavaScript.<link>
and @import
may have a negative impact on webpage performance. In some older versions of IE, mixing <link>
and @import
can cause the stylesheets to be loaded one by one, disrupting parallel downloading and slowing down page loading. Additionally, regardless of the browser, if an external CSS file is loaded using <link>
and that CSS file continues to use @import
to load another external CSS file, the stylesheets will be loaded sequentially instead of in parallel. This is because the browser needs to parse the CSS file loaded by <link>
and then discover the @import
statement to load the external CSS file, resulting in slower page loading.