Applying CSS

Date Published:
Last updated:

Back

You don't need me to tell you that Cascading Style Sheets are great, so let's get to the point. How can you use them? There are three methods:

  1. External style sheets
  2. Internal (or Embedded) style sheets
  3. Inline Styles

The order is important; it represents the order of the cascade (styles are applied in order of 1, then 2, then 3). For example, if you set the colour of paragraphs to black (p{ color: black; }) in an external style sheet and use an internal style sheet to display the paragraphs in blue, the external style will be overwritten, resulting in blue paragraphs.

So without further ado and like a typical Hollywood producer I'll stick to the standard formula and simply list the ways below.

External style sheets

To attach an external stylesheet, you use the <link> tag, in the <head> of the document.

<link rel="stylesheet" type="text/css" media="screen" href="/path/to/css/filename.css" />

Notes:

Internal (or Embedded) style sheets

You use <style> tags to enclose internal styles. These are placed in the <head> section of the page.

<style type="text/css">p { color: #f00; }</style>

Inline styles

Inline styles are applied by using the style attribute on an HTML element. This method is not recommended as you're losing the efficiency of a single style sheet and all other CSS benefits; you're better off using an appropriate class or id.

<p style="color:#f00;">Some important text displayed in red.</p>

@import

Oh yeah, and then there's @import. The @import directive can be used in external or internal style sheets only and must appear at the start of the style sheet, before any other CSS rules to work correctly. As its name implies, an external CSS file will be imported into the current style sheet.

<style type="text/css">@import url("/path/to/css/filename.css") screen;p { color: #f00; }</style>

Further reading and sources