style (HTML element)
Example
This page-specific
style is embedded using the style
element:
<style type="text/css">
h2 {color:#000;}
</style>
- Type
- head element
- Contains
- CSS style declarations only
- Contained by
head
Description
Styles
can be applied in CSS at various levels. The first is to link to a style
sheet using the link element. The
next level is to embed a set of style rules at page level by placing them
within a style element situated inside the head. (The other methods, to complete the
picture, are to create inline styles using the style attribute, and user
style sheets, which reside on the user’s hard drive.)
While this is not The SitePoint CSS Reference, it’s worth noting that as you apply a CSS style at each level in the order stated above, assuming the same selector syntax is used in each case, the more specific or lower-level style will override the style set at the higher level.
It’s possible to add comments within the style
element, but note that the HTML comment syntax <!--
--> isn’t used—the correct syntax is /* Comment goes
here */. In an XHTML document that’s served as XML (which uses
the "application/xhtml+xml" MIME type), the contents of
the style element should be identified as being
character data:
<style type="text/css"><![CDATA[
body {margin:0;}
⋮
//]]></style>
Refer to the description of script for more information about comment syntax and the parsing of character data.
Use This For …
You’re most likely to
use the style element to override the styles set in a
linked style sheet, like so:
<link rel="stylesheet" href="basic.css"/>
which contains the selector h2 {color:#066;}
⋮
<style type="text/css">
/* override color set in main.css for this page only*/
h2 {color:#000;}
</style>
It wouldn’t matter if the
style block came first, and was followed by the linked
style sheet. Regardless of the order in which the styles are set, the
declaration in the style block trumps the identical one inside the linked
.css file.
However, you don’t have to use
style as an override facility alone—some people prefer
to embed the style information on each page using a server-side include,
as this approach ensures that all the style information is present and
correct, and avoids the danger that a link to the style information may
break. Note that this approach precludes you from gaining the benefit of
having the content cached—a benefit you’d enjoy if the style sheet data
were contained in an external style sheet.
Compatibility
| IE | 5.5 | Full |
|---|---|---|
| 6.0 | Full | |
| 7.0 | Full | |
| Firefox | 1.0 | Full |
| 1.5 | Full | |
| 2.0 | Full | |
| Safari | 1.3 | Full |
| 2.0 | Full | |
| 3.0 | Full | |
| Opera | 9.2 | Full |
| 9.5 | Full |
Every browser listed supports this element type.
User-contributed notes
There are no comments yet.
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.

