Linking to an external CSS style sheet file

So far, all the CSS code we have learned about, we put between <style> tags, like this:

<style>
 .myclass {
 background-color:#aaddcc;
 margin:10px;
 }
 </style>

In principle, it will work when you put your CSS anywhere in your HTML document, though the best way is to put them between your <head> and </head> tags.

However, there’s an even BETTER way: put your css code in a separate .css file, and link to that file from within your HTML document. This has several advantages:

  • It keeps your HTML files smaller and cleaner, with their own purpose (structure and content) nicely separated from the CSS with its own purpose (defining the layout). But mostly:
  • It allows you to use the same CSS code accross multiple pages (.html files). Since every web page beyond the most basic one will consist of multiple pages, this makes things a lot less complicated!

Linking to an external style sheet with the <link> tag

Quite analogous to HTML files, CSS files are just plain text files with the .css extension. So open a new document in your text editor and insert the following:

h1,h2,h3 {
color:red;
}
body { 
background-color:#aaffaa;
}

Note that there are no <style> or any other HTML tags needed here! Now, save this file with the name style.css in the same folder as your html file.

Next, open your HTML file, and insert this line in the header section (between <head> and </head>):

<link rel="stylesheet" type="text/css" href="style.css">

So if you started with the index.html file of our hello world lesson, the code should now look something like this:

<!doctype html>
<html>
 <head>
 <title>My first web page!</title>
 <link rel="stylesheet" type="text/css" href="style.css">
 </head>
 <body>
 <!-- actual content comes here -->
 <h3>Hello world!</h3>
 <p>
 This is my first web page, thank you for visiting it!
 </p>
 </body>
</html>

Now save your HTML file, and open it in the browser (by double-clicking on it). If you did everything correctly, you should see that the CSS rules are applied to your page like this:

Screen Shot 2014-01-21 at 13.39.29

Cool huh? From now on, always put your style definition in a separate .css file, and use the <link> tag to link to it.

Advertisements

One comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s