Monday, September 13, 2010

Adding styles to a web page

The most common (and useful) method of applying CSS rules to a web page is by using
external style sheets. CSS rules are defined in a text document, which is saved with the file
suffix .css. This document is attached to an HTML document in one of two ways, both of
which require the addition of HTML elements to the head section.
The first method of attaching a CSS file is to use a link tag:
<link rel="stylesheet" href="mystylesheet.css" type="text/css"
å media="screen" />
Alternatively, import the style sheet into the style element:
<style type="text/css" media="screen">
/* <![CDATA[ */
@import url(mystylesheet.css);
/* ]]> */
</style>
The second of these methods was initially used to “hide” CSS rules from noncompliant
browsers, thereby at least giving users of such devices access to the website’s content, if
not its design. In some browsers (notably Internet Explorer), however, this can cause a
“flash” of unstyled content before the page is loaded. This flash doesn’t occur when a link
element is also present. In the full site designs in Chapter 10, you’ll note that both methods
are used—@import for importing the main style sheet for screen and link for linking
to a print style sheet.The style tag can also be used to embed CSS directly into the head section of a specific
HTML document, like this:
<head>
<style type="text/css">
/* <![CDATA[ */
p {
color: black;
}
#navigation p {
color: blue;
font-weight: bold;
}
/* ]]> */
</style>
</head>
You’ll find that many visual web design tools create CSS in this manner, but adding rules to
a style element is only worth doing if you have a one-page website, or if you want to
affect tags on a specific page, overriding those in an attached style sheet (see the next section
for more information). There’s certainly no point in adding styles like this to every
page, because updating them would then require every page to be updated, rather than
just an external style sheet.
The third method of applying CSS is to do so as an inline style, directly in an element’s
HTML tag:
<p style="color: blue;">This paragraph will be displayed in blue.</p>
As you can see, this method involves using the style attribute, and it’s only of use in very
specific, one-off situations. There’s no point in using inline styles for all styling on your
website—to do so would give few benefits over the likes of archaic font tags. Inline styles
also happen to be deprecated in XHTML 1.1, so they’re eventually destined for the chop.

No comments:

Post a Comment