HTML and CSS Reference
In-Depth Information
style
The
style
element contains style information applicable to the current document. In HTML, this is almost
always written in CSS. Other style languages could be used for other types of structured documents, but in
HTML—and as far as we're concerned for this topic—CSS is the only style language that matters.
The optional
type
attribute indicates the content type of the enclosed style data, which is
text/css
for
CSS, and browsers will assume that content type if the
type
attribute is omitted. The entire contents of the
style
element are hence written in the CSS language; the
style
element can't contain any HTML, so no
nested elements are allowed and comments inside a
style
element must be CSS comments, not HTML
comments.
Listing 3-4 shows an example of a simple style sheet enclosed in a
style
element.
Listing 3-4.
CSS rules embedded in a
style
element
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Power Outfitters Superhero Costume and Supply Co.</title>
<style type="text/css">
body { background-color: ivory; color: navy; }
h1 { font-size: 1.6em; color: crimson; }
</style>
</head>
<body>
<h1>Welcome, Heroes!</h1>
<p>Power Outfitters offers top of the line merchandise at
rock-bottom prices for the discerning costumed crime-fighter.</p>
</body>
</html>
Because this style information is included as part of the HTML document, it's known as an
embedded style
sheet
, or sometimes an
internal style sheet
. Style sheets embedded in
style
elements are most useful for
one-off, standalone web pages where those style rules don't need to be shared by any other documents.
Otherwise, for websites consisting of numerous pages that should share common styles, it's much more
practical to link to a separate external style sheet by way of a
link
element.
A single document can have any number of
style
elements, and like the
link
element, an optional
media
attribute can indicate the specific media for which those styles are intended. Also like the
link
element,
the
style
element's
media
attribute can carry a media query, though older browsers may not support it.
When the
media
attribute is absent, the browser will use the enclosed styles for all media by default (the
same as including
media="all"
).
The scoped Attribute
Ordinarily, a
style
element can only appear within the
head
element, and placing a
style
element
anywhere else in the document isn't valid. But that could change in HTML5 with the introduction of the
scoped
attribute. This Boolean attribute, when present, allows a
style
element to appear outside the