Embedding CSS Code in a Web Page

This tutorial is part of a web programming course for people who have no programming experience.


There are three different ways to include CSS code in a web page, but really only one of them is recommended.

Using a STYLE Element

As you saw in the previous lesson, you can add a style element in your HTML code and then everthing inside of it will be interpreted as CSS code.

<style>
    h1{
        color:red;
        font-family: verdana;
    }
</style>

Although this is not the recommended approach, we'll be using it in our sample files because when you are learning, it is convenient to have the HTML and CSS code together in the same file.

Using a STYLE Attribute

You can actually embed CSS code right inside an HTML element by using a style attribute, like so:

<h1 style="color:red; font-size:30px;">Hello World!</h1>

In this case the value of the style attribute is CSS code. You should avoid this approach because it creates a mess by sprinkling bits of CSS code throughout your HTML. It's generally a good idea to keep all your CSS code together in one place.

Using a Style Sheet

The recommended approach for incorporating CSS code into a web page is to place it in a separate file, and then link to that file from your web page. A CSS file is known as a style sheet and it should have a .css extension. In order to do this, you first create the style sheet (in the video we created a style sheet named test.css). A website might actually use more than one style sheet, so it's common to create a folder for all of them. The folder is usually called styles or css. The next step is to link your web page to the style sheet, and for this you can use a link element, for example:

<link rel="stylesheet" href="../styles/test.css"/>

Notice the attributes that have been added to the link element. The rel attribute indicates that the link is to a style sheet (I believe that rel stands for 'relationship'). And the value of the href attribute is set to a path that leads to the style sheet (if you aren't clear on paths, then you may want to revisit the HTML lesson on hyperlinks).

Linking to a separate file offers a major benefit, which is that you can have all the web pages on your site using the same style sheet. This makes updates extremely easy. You just make a change in the style sheet, and all the pages that link to it will be updated.

This concept of sharing code among files via a link is very important in programming, which is why every programming should understand links and paths. If the path is wrong, the link won't work. I can only imagine how much of my life was spent trying to troubleshoot a problem that was caused by using the wrong path in a link. Clever programmers will learn to look for these mistakes when troubleshooting.

NEXT LESSON: CSS Inheritance and Specificity