Applying CSS
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:
- External style sheets
- Internal (or Embedded) style sheets
- 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:
- To apply the style sheet to multiple media types, separate each media type by a comma e.g.
media="screen,print" - To provide an alternative style sheet, use
rel="alternate stylesheet"and give it a name using thetitleattribute e.g.title="Alt 1". Not all browsers support alternate style sheets. Surprised?
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
- W3C's CSS v2.1 Specification