If you've read any of my earlier posts, you may have noticed I have an article on the 3 ways CSS can be applied to your HTML file. If not, here's a recap:
CSS can be applied either inline(within the same line), internally(within the same document), or externally(from a separate stylesheet). As you can see by the title, our focus here will be on this last method.
Out of all the application methods, external is the best since it keeps markup and style separate and thus makes both more organized and easier to manage. It also works best when having to deal with multipage projects to keep styles consistent.
So, how exactly do we link an external stylesheet to the document we want to apply the styles to? That's what we're gonna cover right now!
Applying a Stylesheet
Let's say you have an HTML file and a CSS sheet. Let's give them the typical "index.html" and "styles.css" names. You've already created the stylesheet; you're now just trying to connect it to the corresponding document.
Within index.html, you have the <head>
section, all the way at the top. Within that section, you have to add a <link>
element, like so:
<html>
<head>
<link rel="stylesheet" href="styles.css">
</head>
</html>
Sometimes, you'll see a type
attribute within the link:
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
</html>
Adding this attribute is completely optional. So whether you add it or not, it'll link all the same.
Now let's break down the attributes in the link tag.
Link Tag Attributes
The rel
Attribute
The rel
attribute indicates the relationship between the current file and the external file. In the case of external CSS, it's a stylesheet.
The href
Attribute
The href
attribute indicates what file you're importing. For our example, it's "styles.css." One thing to note is that you can leave the path as "styles.css" if the sheet is in the same folder as the HTML document. If not, then you have to write "folder/styles.css."
The type
Attribute
The type
attribute indicates what type of file it is you're linking. If you include it for stylesheets, it's "text/css." As stated earlier, this is completely optional, and more often than not you'll see this attribute omitted.
Wrap-up
Now not only do you know how to link an external stylesheet to a file, you know what attributes go into the link and what they mean. Pretty simple, huh?
As usual, if you've found this helpful or have anything else to say, just write them below in the comments! And if you liked it, maybe consider sharing it?
Happy Coding!