CSS Tutorial - Chapter 5: The CSS file

In the previous chapter we looked at how to set up some CSS definitions for some HTML elements using ID's and classes, as well as a "default redefinition" of an <h1> element. Now, we are going to stick our CSS in one file and our HTML in another, and introduce the two to eachother.

First, create a blank text file named example.css. Then put the following CSS snippets from the last chapter into it, and save it:

h1{
  color: blue;
}

#bodySettings{
  background-color: yellow;
}

.redText{
  color: red;
}

.greenText{
  color: green;
}



Now, let's create our HTML file. Simply open up a new blank text file, name this one example.html and then put the code from last chapter in it, but with one small modification - three new lines are added in the <head> area that tells our document to recieve its style settings from our CSS file:

<html>
  <head>
    <title>Setting a few IDs and Classes</title>
    <style type="text/css" media="all">
      @import "example.css";
    </style>
  </head>
  <body id="bodySettings">
    <h1>Another blue topic</h1>
    <p class="redText">
      Oh no, not the red apples again?
    </p>
    <p class="greenText">
      Green apples resurrected.
    </p>
  </body>
</html>



Make sure that these two files are stored in the same folder, then open the HTML file with your browser. If everything was done right, it should display something like this on your screen:



That should give you the basic idea of how CSS works. You define your CSS in the .css file, put references to the ID's and classes in the .html file on the tags that you want to make use of them, and then just include the CSS file with those three lines <title> in the <head>.



You should also be aware of the fact that there are actually two ways to include your CSS file in your HTML document. You can @import it in a <style> tag as I did above, or you can also link to it with a <link> tag. The link method would have looked like this in the <head> area:

  <head>
    <title>Setting a few IDs and Classes</title>
    <link href="example.css" rel="stylesheet" type="text/css" media="all">
  </head>

Why you would choose one method over the other is really outside of the scope of this chapter, I recommend that you google these two methods if you want to learn more about their particulars. As long as you're only learning the basics however, it doesn't really matter which one you use.





< Previous: IDs and Classes

robert@eagleowl.se     +46 (0)26-16 13 61     www.eagleowl.se
©2021 EagleOwl