4.3 Linking CSS to HTML

CSS code can be linked to HTML code in one of three ways. These are described below in increasing order of preference.

Inline CSS:
 
The simplest approach is to include CSS code within the style attribute of an HTML element. An example is shown below:

<p style="font-style: italic">

Here, CSS is used to control the appearance of text within this paragraph only.

This approach is actively discouraged because it leads to many copies of the same CSS code within a single piece of HTML code.

Embedded CSS:
 
It is also possible to include CSS code within a style element within the head element of HTML code. An example of this is shown below:

<html>
    <head>
        <style>
            p {
                font-style: italic;
            }
        </style>
    ...

In this case, the appearance of text within all paragraphs is controlled with a single CSS rule.

This approach is better because rules are not attached to each individual HTML element. However, this is still not ideal because any reuse of the CSS code with other HTML code requires copying the CSS code (which violates the DRY principle).

External CSS:
 
The third approach is to write CSS code in a separate file and refer to the CSS file from the HTML code, using a link element within the head element. An example is shown below:

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

This line would go within a file of HTML code and it refers to CSS code within a file called csscode.css.

This approach allows, for example, control over the appearance of text within all paragraphs for multiple HTML files at once.

Paul Murrell

Creative Commons License
This work is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 New Zealand License.