Thursday, January 10, 2019

CSS: Linking to An External Stylesheet With the link Tag and The @import Directive

One of the first thing you would do in web development is to link an external Cascading Stylesheet to an HTML document. As a matter of fact bootstrap would not work if you didn't link the bootstrap.css file in your HTML document. Linking an external document is easy enough you often see the link like this

Now let's break it down link attributes, there are four possible attributes for the link tag.

They are the following:

rel (required) - Relations, relationship to this page. For CSS stylesheets its "stylesheet"

type (optional) - is the type of the link, "text/css" is the type for CSS stylesheets

href (required) - is the location of the resource, it could a relative path or an actual URL like a CDN

media (optional) - with this attribute you can specify which media the stylesheet is meant for. For example the media attribute can have the "projector" value.

Another way you can link to an external stylesheet is with the @import directive, which you don't see very often. It is used a little differently. You have to put it on the first line or before the CSS rules inside the <style> tag like so

<style>
@import url(CSS/styles.css);
</style>

The cool thing about the @import directive is that you can have one stylesheet imported in another. To demonstrate this let's create two stylesheets and have one stylesheet import the other.

The next step is to create an index.html file to import the styles.css file. Even though you only imported the styles.css file with the @import directive, you also have access to the nav.css style rules because the styles.css file already imported the nav.css file.