4.4 Linking CSS to HTML

CSS code can be linked to HTML code in one of three ways:

External CSS:
 
The CSS code can be in a separate file and the HTML code can include a link element within its head element that specifies the location of the CSS code file. 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.

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.footer {
                font-style: italic;
            }
        </style>
    ...

This approach is not recommended because any reuse of the CSS code with other HTML code requires copying the CSS code (which violates the DRY principle).

Inline CSS:
 
It is also possible to include CSS code within the style attribute of an HTML element. An example is shown below:

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

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

Paul Murrell

Creative Commons License
This document is licensed under a Creative Commons Attribution-Noncommercial-Share Alike 3.0 License.