Tech Junkie Blog - Real World Tutorials, Happy Coding!: CSS: Linking to An External Stylesheet With the link Tag and The @import Directive

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

    <link href="Content/bootstrap.css" media="all" rel="stylesheet" type="text/css"></link>
    <script src="Scripts/bootstrap.js"></script>

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.

First create the nav.css file with the following markup

.nav-really-small-font{
    font-size: 5px;
}

Now create the styles.css file with the following markup

@import(nav.css);

body {
}

.styles-really-big-fonts{
    font-size: 50px;
}

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.

The html markup looks like the following:

<!DOCTYPE html>
<html>
<head>
    <link href="Content/bootstrap.css" type="text/css" rel="stylesheet" media="all" />
    <link href="Content/bootstrap.css" rel="stylesheet" />
    <script src="Scripts/bootstrap.js"></script>
    <meta charset="utf-8" />
    <title></title>
    <style>
        @import url(CSS/styles.css);
    </style>
</head>
<body>
    <p class="styles-really-big-fonts">This is from styles stylesheet</p>
    <p class="nav-really-small-font">This is from nav stylesheet</p>
</body>
</html>

The output of the HTML file should look like this


No comments:

Post a Comment