Attaching CSS to Your Document

The CSS we create will act as a style sheet for our web pages. This is what will control the type, color, layout and even interactive pieces. In order for our HTML pages to make use of the CSS rules, we need to make sure that our HTML page references, or attaches, them in some way.

There are three common ways to attach your stylesheets:

External Styles

The best method for attaching your CSS style sheets is to use external styles. With this method, you will write all your CSS in a separate file with a .css extension. You can then link to the CSS file from each of your HTML pages.

In the example below, we're linking to a CSS document called styles.css.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8"/>
  <title>External Style Sheet Example</title>
  
  <link rel="stylesheet" href="styles.css" media="screen">
</head>

External stylesheets use the <link> tag inside the head element.

rel
The rel attribute explains the relation the link has to our document. The value in this case will always be stylesheet, since that is what we're creating a link to.
href
The href attribute is the link to our stylesheet. This works exactly the same as the href used in a tags.
media
The media attribute describes what type of media our stylesheets should apply to. There are a number of possible values, including both screen and print. You will most often use screen.

Embedded / Internal Styles

You can also add CSS styles to the top of your HTML page, inside the head element.

<html lang="en">
<head>
  <meta charset="utf-8"/>
  <title>Embedded / Internal Stylesheets Example</title>
  
  <style>                
     p {                 
        color: deeppink; 
     }                   
  </style>       
</head>

This is a great way to quickly test a new style on your page. Reserve internal styles for testing and experimenting with new CSS rules.

Inline Styles

The final method is to add CSS styles inline with your HTML.

To do this, you just have to use the style attribute and add the CSS declaration as the attribute value.

<p style="color: deeppink">This paragraph will be "deep pink".</p>

While this is very easy, it's also not very extensible.

For example, to change all the paragraphs to red, we'd have to add the style attribute to each paragraph on in our HTML document.

<!-- Example of bad code. Don't do this -->
<p style="color: deeppink">This paragraph will be "deep pink".</p>
<p style="color: deeppink">This another paragraph with "deep pink".</p>
<p style="color: deeppink">This is yet another paragraph with "deep pink".</p>
<p style="color: deeppink">This is a lot of redundant CSS, which also means a lot of room for errors.</p>

Generally, using inline styles are considered bad form. Don't do this.

Which Method is Best?

External Style Sheets.