Linking CSS to a Web Document
We can use any of three methods to specify CSS styling rules for elements in an HTML document, but only one method to specify CSS rules for XML documents. We can use all four methods with XHTML documents that are served as XML. XHTML served as HTML is HTML as far as browsers are concerned, so only the three HTML methods can be used in that case. See Differences Between HTML and XHTML for details about the different ways in which you can serve XHTML.
The methods are:
- Place the rules in a separate, external style sheet that’s
referenced by a
linkelement or an@importrule in a style element (HTML, XHTML). - Place the rules within an separate, internal style sheet within a
styleelement (HTML, XHTML). - Place the rules in inline CSS specified in a
styleattribute of a markup tag (HTML, XHTML). - Place the rules in a separate, external style sheet referenced by a processing instruction (or PI) (XML).
Separate style sheets—both external and internal—can be targeted to one or more output media. External style sheets can be specified as alternative, which means that they’re not applied by default, but can be enabled by users in browsers that support alternative style sheets.
We specify the output media using the predefined media types shown in Media Types.
| Media Type | Description |
|---|---|
"all" |
applies to all media |
"Braille" |
Braille/tactile feedback devices |
"embossed" |
paged Braille printers |
"handheld" |
handheld devices |
"print" |
paged media and print preview mode on the screen |
"projection" |
projected presentation (used by Opera in full-screen mode) |
"screen" |
color computer screens |
"speech" |
speech synthesizers (see the note below) |
"tty" |
media with a fixed-pitch character grid |
"tv" |
television-type devices |
Using one or more external style sheets is generally considered to be the best practice, as it enforces the desirable separation between content and presentation.
Should each style sheet be specific to one output medium, or should you
have a single style sheet and use @media at-rules to
specify styles for different output media? The answer to that question
depends, primarily, on how differently the content will be presented in
different media. Style sheets for "screen" and
"projection" media can often be combined, while style
sheets for "print" or "handheld"
usually benefit from being kept separate.
An internal style sheet can sometimes be justified on a page which has presentational needs that are very different from the rest of the site. It could also be used, along with one or more external style sheets, for styling special elements that only occur on one page.
It can be useful to keep your CSS in an internal style sheet during the initial development phase, to avoid problems that can arise when style sheets are cached by the browser. Once the design is completed, you can move the CSS to an external style sheet.
Inline styles should normally be avoided, since they tie presentation
to content in the same unfortunate way as do presentational HTML elements
such as the deprecated <font> and
<center> elements.
Aural style sheets (media="speech") are not
formally specified in CSS2.1. The specification reserves the speech
media type, but says nothing about which properties apply to it and
which don’t. Therefore, aural style sheets will not be covered in this
reference.
Referencing an External Style Sheet Using a
link Element or @import
At-rule
Here’s an example of an external style sheet reference
that uses a link element:
<link rel="stylesheet" type="text/css" href="/style.css"
media="screen">
The link element,
which must reside within the head element of an HTML
document, links an external style sheet to the document. Multiple,
comma-separated media types can be specified in the
media attribute, for example,
media="screen,projection". If it’s omitted, this
attribute defaults to media="screen", according to
the HTML4 specification, but in reality, browsers seem to apply
media="all" if the attribute is
omitted.
Here’s an example of a style sheet reference that uses an
@import
at-rule:
<style type="text/css"> @import url(/style.css); </style>
The style element, like the
link element, must reside within the
head element.
Relative URIs in the
href attribute or @import
rule are relative to the HTML document that contains the link. (When
@import is used inside an external style sheet,
relative URIs are relative to the importing style sheet.)
The
link element can also be used to link to an
alternative style sheet:
<link rel="alternate stylesheet" type="text/css"
href="/contrast.css" media="screen" title="High contrast">
This
alternative style sheet, which is disabled by default, can be enabled by
the user if the browser supports alternative style sheets. All style
sheets with the same title attribute will be
enabled or disabled as a group. Alternative style sheets are mutually
exclusive, so enabling one group will automatically disable all other
groups.
The CSS specifications use the term “alternate” instead of
“alternative.” The keyword used in the rel
attribute must also be "alternate".
A style sheet that’s linked with
rel="stylesheet" but lacks a
title attribute, like the first example in this
section, is known as a persistent style sheet. It
will always be applied—even if an alternative style sheet is enabled by
the user.
A style sheet that’s linked with
rel="stylesheet", and for which a
title attribute has been specified, is known as a
preferred style sheet. It will be applied unless
the user has enabled an alternative style sheet.
Let’s take a look at a more complex example:
<link rel="stylesheet" type="text/css"
href="/base.css" media="all">
<link rel="stylesheet" type="text/css"
href="/def_layout.css" media="screen" title="Default">
<link rel="stylesheet" type="text/css"
href="/def_colour.css" media="screen" title="Default">
<link rel="alternate stylesheet" type="text/css"
href="/alt_layout.css" media="screen" title="Custom">
<link rel="alternate stylesheet" type="text/css"
href="/alt_colour.css" media="screen" title="Custom">
<link rel="stylesheet" type="text/css"
href="/print.css" media="print">
Here,
base.css is a persistent style sheet, as it doesn’t
have a title attribute; it will always be applied
for all media types, since it has the attribute
media="all".
By default, def_layout.css and def_colour.css will also be applied for screen media, since they’re preferred style sheets.
If the user selects Custom style sheets in the browser, as depicted in Figure 1, def_layout.css and def_colour.css will be disabled, and alt_layout.css and alt_colour.css will be enabled.
When printing, or in print preview,
print.css will be applied since it has the attribute
media="print". Note that
base.css will also be applied since it specifies
media="all". The other four style sheets will not
be applied here, however, since they specify only screen media.
We can use the alternative style sheet feature to offer multiple viewing options from which the user can make a selection. In Eric Meyer’s Complex Spiral Demo, the user is able to select from one of many available alternative style sheets, as depicted in Figure 2.
Using an Internal Style Sheet
The
style element, which must reside within the
head element of an HTML document, specifies an internal
style sheet which will only apply to elements in the enclosing
document:
<style type="text/css" media="screen,projection">
⋮ CSS rules…
</style>
The type attribute is
required, and should have the value "text/css" which
denotes CSS styles. As in the case of external style sheets, the
media attribute defaults to
"screen" if you omit it, according to the HTML4
specification, but in reality, browsers seem to apply
media="all" if the attribute is
omitted.
Pre-HTML4 browsers don’t support the
<style> element—they’ll render the element’s content as
text. As a special case, an SGML comment surrounding the content in its
entirety will be ignored in CSS-compatible browsers. Note, however, that
this applies only to HTML. It doesn’t apply to XHTML served as XML—there,
such a comment will be treated as a comment, effectively hiding all the
CSS.
The practice of commenting out the content of
<style> elements is archaic and unnecessary, since very
few pre-HTML4 browsers are in regular use these days. It’s harmless in
HTML, but must be avoided in XHTML—even if served as text/html—to ensure
that such a document will still work when served as XML.
Here’s an example of an internal style sheet in HTML, which is hidden from ancient browsers:
<style type="text/css" media="screen,projection">
<!--
⋮ CSS rules…
-->
</style>
Using Inline Styles
The following inline
CSS will make the font size of an unordered list 120%
of what it would normally be. It will also make the text and the list
bullet points dark green:
<ul style="font-size:120%; color:#060">
⋮ list items…
</ul>
Using style attributes
creates a strong coupling between the content and the presentation, which
is usually undesirable.
Inline CSS is more limited than internal or external style sheets. It’s not possible to specify a media type, so style attributes will apply for all media types. Also, you can’t specify inline CSS rules for pseudo-classes or pseudo-elements.
If you use
inline CSS, the HTML specification states that you must declare
the style language. You can do so using a HTTP header or an equivalent
<meta> element:
<meta http-equiv="Content-Style-Type" content="text/css">
In
reality, browsers don’t care because the HTML specification also states
that the style content type defaults to "text/css" if
it’s not specified in a <meta> element or a
Content-Style-Type HTTP header.
Yes, it may
seem that the statements “you must declare the style language” and “the
style content type defaults to "text/css" if not
specified” are mutually exclusive, but the intent was only to provide a
safety net. The specification recommends that authoring tools
automatically generate the style sheet language information in order to
avoid forcing user agents to rely on the default value. The effectiveness
of this recommendation remains to be seen.
Referencing an External Style Sheet Using an XML PI
In XML documents, including XHTML served as XML, an external style sheet can be referenced using a processing instruction (PI). Such processing instructions are normally part of the XML prologue, coming after the XML declaration, but before the doctype declaration (if there is one) and the root element’s start tag.
This example shows an XML prologue with a persistent style sheet (base.css), a preferred style sheet (default.css), and an alternative style sheet (custom.css):
<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet type="text/css" href="/base.css"?>
<?xml-stylesheet type="text/css" href="/default.css"
title="Default"?>
<?xml-stylesheet type="text/css" href="/custom.css"
title="Custom" alternate="yes"?>
The CSS specifications use the term “alternate” instead of
“alternative.” The attribute name in a PI must be
alternate.
Differences Between the Methods
In addition to the differences that exist in the ways the style sheets or CSS rules are specified in the markup, there are a few other differences that we may need to consider, depending on which method we choose:
- An external style sheet can’t contain SGML comments
(
<!-- … -->) or HTML tags (including<style>and</style>). Nor can it use SGML character references (such as©) or character entity references (such as©). If you need to use special characters in an external style sheet, and they can’t be represented through the style sheet’s character encoding, specify them with CSS escape notation. - The content type of the
styleelement type in HTML is CDATA, which means that character references (numeric character references or character entity references) in an internal style sheet aren’t parsed. If you need to use special characters in an internal style sheet, and they can’t be represented with the document’s character encoding, specify them with CSS escape notation. In XHTML, the content type is #PCDATA, which means that character references are parsed, but only if the document’s served as XML. - Unlike in
styleelements, character references are parsed instyleattributes, even in HTML.
User-contributed notes
- ID:
- #5
- Date:
- Fri, 01 Feb 2008 20:42:20 GMT
- Status:
- This note has not yet been confirmed for accuracy and relevance.
When typing in the code for the examples of Style Sheets, it would have been better to use the correct colour for each element.
Anyone ( a newbie) trying to follow all the other reams of text and trying to understand CSS, would at least find something they could relate to when then trying to execute said code in Web designing software (Dreamweaver for example).
Susie
- ID:
- #4
- Date:
- Sat, 05 Jan 2008 23:37:48 GMT
"Place the rules in a separate, internal style sheet within a style element. (HTML, XHTML)"
If the styles are in the page mark up then they are neither seperate to the page nor in a sheet as such.
The styles are grouped together in one specific place within the page identified by style tags.
"Place the rules in inline CSS specified in a style attribute of a markup tag. (HTML, XHTML)
Place the rules in a separate, external style sheet referenced by a processing instruction (or PI). (XML) " - do beginners really understand inline and style attributes when neither has yet been explained in this document at this stage.
Can't there be examples of how a specific tag can have a style applied to it within the page mark up e.g. center, color.
- ID:
- #3
- Date:
- Thu, 06 Dec 2007 21:20:01 GMT
In my browser (IE 6) the heading "using an internal stylesheet during development" hides the first line of text in that box.
- ID:
- #2
- Date:
- Thu, 06 Dec 2007 16:47:28 GMT
- Status:
- This note has not yet been confirmed for accuracy and relevance.
When you mention XHTML, do you mean vanilla XHTML 1.0? Since the "style attribute" isn't always directly available and in some cases neither is the <style> - as by that, I mean as default modules - for certain versions of XHTML.
Add a note
To post a note on this topic, please log in with your SitePoint username and password. If you don't have an account yet, you can create a new account for free.
