Sample chapter taken from “Cascading Style Sheets: Separating Content
from Presentation“, by glasshaus. Reproduced by permission.
The World Wide Web (the Web for short) is a massive media
revolution, producing not only a massive spike in the US and world economies
in the last years of the 20th century, but also empowering individuals and
organizations with self-publishing capabilities and a ready-made world-wide
audience. Where the printing press gave us the ability to record and distribute
information, the Web increased those abilities exponentially, removing the
barrier of the commercial publishing system to the production of self-published
materials.
Due to its revolutionary nature, the Web has been the subject
of massive hype, commercial gold-digging, and genuine advances in human communications;
and not in equal amounts. But in spite of the abuses, the Web has blossomed
as both a mode of self-expression for countless self-publishers, as well as
a viable commercial center and a powerful digital library.
However, the Web is certainly not without its problems.
After enjoying half a decade of optimistic growth, the web economy has been
fed a dose of reality. Gone are the days of the dot com millionaire made over
night with a web server and a good idea. Gone are the days of abundant high-salaried
dot com jobs. These are the days of struggling web businesses, fighting to
find the proper model that works in these uncharted waters of the Web, slashing
costs and cutting payroll.
The economic troubles are not the only challenges facing
the Web; there are also technological hurdles that must be leapt, for in the
Web’s early growth, expediency and pizzazz won over wisdom and solid development
practices. Some of the blocks that were laid in the early explosion of web
growth were faulty at best, and remain unsuitable as foundations for future
building.
Recall that the Web is an interconnected group of computers,
from the army of small iMacs and PCs on the desktops of homes and offices
around the world, to massive web server farms that feed pages to an ever-increasing
audience. On these web servers are documents each
of which can be connected to other documents via hyperlinks. Web surfers use
web browsers, like Netscape’s Navigator, Microsoft’s Internet Explorer, or
the Opera browser, to retrieve and view these web pages from the web servers
that serve them.
As you know, the web pages themselves are constructed with
a markup language called HyperText Markup Language (HTML). Using a markup
language, an author “marks up” a document with structural and other
meta-information right along side the document’s content. As innocuous as
that may sound, HTML is at the center of one of the technological struggles
the Web now faces, a struggle which is quickly reaching a crossroads: is HTML
to be used as a presentation language, used to define
the visual appearance of a web page, or is it to be used as a traditional
markup language, defining the structure of documents and leaving layout
and visual design to a style language. It’s a complicated question, and at
its heart lies the subject of this book: Cascading Style Sheets (CSS).
To understand the difference between “structure” and “presentation”,
consider the following sentence:
“William Faulkner’s Sanctuary is one hell of a scary book.”
Structurally speaking, the word “Sanctuary” is a book title; in
terms of presentation, on the other hand, the word is underlined. This distinction
is lost on many because of the ubiquity of word processing applications
such as MS Word, which blur the line between structure and presentation.
In a word processing application, we don’t select the text “Sanctuary”
and hit the “book title” button. We hit the “U”
button, which underlines it as we wish. In the following sections you’ll
see why marking up text structurally produces more powerful documents.
CSS is a style language that can be used
in conjunction with HTML to define the visual presentation of a web page.
“If that’s the case”, you might ask, “then why is there any
question of using HTML as a presentation language?” The short answer
is that CSS did not exist until 1996, five years after the birth of the Web,
and even now is not fully supported by the dominant web browsers. Thus, web
professionals have taken to twisting HTML to suit their own design and presentation
purposes, misusing the markup language and adding elements to pages that contribute
nothing to the content.
Style languages may also
be used to control more than just the visual presentation of documents; for
instance, aural browsers can use stylesheets to guide inflection and intonation
when reading documents aloud to sight impaired persons. This book will deal
nearly exclusively with stylesheets used for visual browsers, but it is important
to note that the markup practices recommended herein will also allow you to
attach other types of stylesheets to your documents. The Web is bigger than
what we can see.
As we’ll see shortly, this situation has improved dramatically
in recent years, and CSS now represents great hope for the Web’s future.
A Short History of the Web
In order to understand why using CSS is vital to the health
of the Web, one must know a little history. You may be tempted to skip this
section, having probably read similar accounts of the Web’s short life countless
times. But I encourage you not to skip ahead, but to instead read on and think
about the implications of the Web’s short but rapidly evolving past.
In 1990, Tim Berners-Lee released the world’s first web
browser and launched the world’s first web server, on which he published for
discussion the specifications of many of the technologies that run the Web
today over ten years later. His goal in releasing this software was to facilitate
the sharing of research documents amongst scientists. He created an Sgml application that he called Html which was a document format suitable for
transmission over his new protocols.
The truly distinctive element of his whole system was the
hyperlink, which put the “hyper” in HyperText Markup Language. The
hyperlink may not seem all that revolutionary to you now, and in fact even
before the Web it had been around as a concept for decades, and experiments
in hypertext systems were not new; but before Berners-Lee, no hypertext application
had been a part of a network the size of the 1990 Internet, and it was the
combination of the network and hypertext that made his experiment a success.
As you know, the hyperlink’s power is that it allows random
connections between disparate bits of data. It escapes the traditional hierarchical
data storage systems of computers, and allows documents to be “linked”
to one another in arbitrary ways. It mimics the associative nature of the
human brain, which connects memories and thoughts and information through
a complex web of inter-connectedness.
The hypertext’s usefulness is limited to the pool of data
that it links together. Berners-Lee developed a system for linking data from
any computer on the Internet to any other computer on the Internet, and in
so doing maximized the power of hypertext. For this reason, an essential requirement
for the Web as Berners-Lee envisioned it is openness: “I have fought since the beginning of the Web for its openness:
that anyone can read web pages with any software running on any hardware.
This is what makes the Web itself.” (Quote from an email between Tim
Berners-Lee and CNET.) As openness increases, so does the power of hypertext,
and therefore the Web as a whole.
Berners-Lee invented HTML in order to maximize openness.
This simple text document format could be transmitted easily using his new
Internet protocols to any computer platform that implemented those protocols.
Using standard ASCII text as a file format ensured that existing computer
platforms would have no problem handling HTML documents, and choosing to build
HTML as an SGML application, which was a platform neutral system for describing
the contents of a document, created an open environment for platform specific
browser makers.
HTML documents in 1990 were radically different from how
they are today. The familiar look of the Web today, with flashing images,
animations, and multimedia files, was an unimagined thing of the future. In
order to understand how HTML got where it is now, we have to take a closer
look at where it came from.
Where did HTML come from?
As stated above, Berners-Lee based his new markup language
on SGML, which has a wonderful history of its own.
In the late 1960’s Charles Goldfarb left the legal profession
to work with IBM where he established the principles of modern markup languages.
His goal was to create a system that would enable the specification of documents
that could be stored in a database, edited, and output for printing with a
minimum of difficulty. The documents themselves were to be stored without
any presentational information, containing only content and structural information.
His work, together with that of Ed Mosher and Ray Lorie,
resulted in Gml, and was an ambitious effort that overcame incredible obstacles.
The task at hand was to apply his knowledge of computing to the storage, retrieval
and editing of legal documents. As he remembers it:
“That project required integrating a text editing application
with an information retrieval system and a page composition program. The documents
had to be kept in a repository from which they could be selected by queries.
The selected documents could be revised with the text editor and returned
to the database, or rendered for presentation by the composition program.”
As you’ve learned, a markup language is used to markup,
or tag, a document’s elements with information regarding the elements’ structural
position in the document. A page header in a markup document, for example,
might look like this:
<header>On the Nature
of Markup</header>
However, before Gml, markup (then called procedural markup) was application specific – the text editor and the page composition
program of Goldfarb’s project required their own unique markup to process
the documents. What GML did was to establish a uniform set of markup tags.
Documents so marked up could then be “understood” by all
the different applications needed to process the documents. The goal was platform
and application neutrality, a system whereby different applications on different
platforms could share documents freely.
Sgml, the next step in the evolution of markup languages,
pushed Gml even further with the introduction of Dtd, which allowed the creation of new
sets of markup tags for any given set of documents. A validating parser could then read the document type definition,
which defined a specific markup system, and ensure the accuracy of the marked
up document. Applications could use the document type definition to make sense
of the document.
So what does that have to do with HTML, you ask? Well, HTML
is an SGML application, a markup language defined according to the rules of
SGML. As such, it is intended to communicate the structural meaning of HTML
document elements with a set of tags defined in the HTML document type definition.
The following is a simple example of a web page, starting with the document
type declaration (see the “<!DOCTYPE…”) and followed by the
HTML markup.
<!DOCTYPE html PUBLIC
“-//W3C//DTD XHTML 1.0 Transitional//EN”
“DTD/xhtml1-transitional.dtd”>
<html>
<head>
<title>An HTML
document</title>
</head>
<body>
<p>Herein is
the lone content of our web page.</p>
</body>
</html>
As you can see, the content of the page is contained within
a nested series of tags, which provide a structural framework for the content.
The markup of the page is intended to communicate the semantic relationships
of the page’s elements to one another.
In this book, we’ll be using XHTML as our markup language in all examples. XHTML is a reformulation of
the HTML vocabulary as an XML application, which is itself an SGML application.
XML was developed to sit in between HTML and SGML, retaining the simplicity
of the former while providing some of the power and flexibility of the latter.
The Web of the future will rely heavily on XML, and so the W3C has discontinued
the development of HTML, recommending instead the migration to XHTML, which
will allow documents authored today to be forward compatible with the XML
heavy Web of the future.
What Happened to HTML?
As I’ve already mentioned, when the Web was but a toddler,
there was no style language available to web authors to instruct browsers
on how to display the elements of a page. Instead, browsers had internal rules
that governed all presentational aspects of a web page. For instance, a piece
of content marked as a header would be typically rendered in a relatively
large font with bold text, and something tagged as a <blockquote> would usually appear with indented left and right margins.
The user was given access to some of these rules through
the browser’s preferences. For example, a web surfer could select what color
a link should be, and what typeface the browser should use. These preference
settings applied globally, to all web pages, not to specific pages or sites.
However, web authors had no way to control layout or typography;
they were totally at the mercy of the browser’s internal page rendering engine,
and these engines differed from browser to browser. For instance, take the
<em> tag, which is used to markup up a
bit of text intended to be emphasized. Some browsers choose to represent the
<em> element with italicized text,
while others use bolded text.
Now, this situation wasn’t particularly problematic to the
first web audience; the scientists that shared the first web pages were much
more interested in the content of the documents than the typeface and color
with which they were displayed. But, as the Web began to build an audience
that was not exclusively research scientists sharing scientific results, the
desire to control visual design of web pages grew accordingly. Early extensions
to the HTML language, therefore, included <b> and <i> tags, which allowed the author to specify
whether text should be bold or italic, respectively. Such minor additions
were relatively benign, not seriously affecting the structural value of a
document, but many more additions were to come, which would have more problematic
results.
When Netscape introduced its 1.1 version of the popular
Navigator browser, a new element was added to the HTML author’s arsenal: the
<table> element. An HTML <table> is intended to hold tabular data,
with column and row headers organizing a grid of information, like so:
|
Milk |
Eggs |
Chocolate |
Chocolate milk |
Cadbury Creme Eggs |
Flour |
Batter |
Dough |
The <table> tag was a great addition to the
HTML language, especially useful for displaying scientific results data, but
it quickly became an innocent victim in a nefarious plot to twist the usage
of the HTML language, resulting in the dot com collapse of the year 2000,
and the loss of thousands of web related jobs. Well, not really… However,
web authors did see something in the <table> tag that it was not intended for: a <table> could be used to create
multi-column web page layouts.
Tables were quickly put to use controlling page layouts;
instead of containing tabular data, web authors used tables to contain whole
pages. But with no other way to define page layouts, and with an army of web
authors arriving on the burgeoning web design scene without an inkling of
what a markup language is supposed to be, the <table> quickly became the poster child for abused HTML elements.
In addition, Netscape and Microsoft, still today the dominant
web browser makers, engaged in an all out battle to win users to their browser.
As the Web rose to prominence in the computing world, the browser quickly
became one of the most important pieces of software on a computer. Some said
it would replace the OS, others said the Web itself was a new platform. Also,
the dot com explosion of the 1990’s brought commercial interests to the Web
with a force that no well-meaning technologist could combat: the need for
companies to maintain a consistent brand image on their new web sites was
greater than any concern for the integrity of HTML as a markup language. A
better-looking web site was more important than correct markup.
Sensing this need of the commercial web page author to control
page presentation, and using that as a way to attract both developers and
users to their software, both Microsoft and Netscape encouraged the use of
<table> for layout, and introduced a series of HTML extensions such as the abominable <blink> and the obnoxious <marquee>. These elements were, of course,
not universally supported, and represented a willful disregard for HTML as
a structural markup language. The <blink>
element communicates nothing of structural value about the text it
tags; it merely instructs the Netscape browser on how to display it.
Perhaps the worst of all such extensions, however, was the
most egregious <font> element. Although all browsers support
the tag today, which allows a web author to define the color, size and typeface
for text, its use encourages the common thinking that HTML is intended to
communicate document presentation. Combine the <font> element with the <table> element, and the fact that the
once dominant Netscape browser did not carry <font> specifications into <table> elements, and you find the explanation
for the morass of markup, nearly devoid of structural information, that passes
for an HTML document even today. As an example of the muddied markup I am
talking about, I found the following markup within about five minutes of looking
on the home page of a major web site (it has been modified to protect the
guilty):
<TABLE BORDER=0 CELLPADDING=2
CELLSPACING=2>
<TR VALIGN=TOP>
<TD BGCOLOR=#FFFFFF
WIDTH=”33%” ALIGN=LEFT>
<FONT FACE=”Verdana,
Arial, Helvetica, sans-serif” SIZE=1 CLASS=”s1cB”>
<A HREF=”http://example.com”>
<NOBR>
<B>Dow</B>
</NOBR>
</A>
</FONT>
</TD>
<TD BGCOLOR=#FFFFFF
WIDTH=”33%” ALIGN=RIGHT>
<FONT FACE=”Verdana,
Arial, Helvetica, sans-serif” SIZE=1 CLASS=”size1″>
9698.30
</FONT>
</TD>
<TD BGCOLOR=#FFFFFF
WIDTH=”33%” ALIGN=RIGHT>
<FONT FACE=”Verdana,
Arial, Helvetica, sans-serif” SIZE=1 CLASS=”size1″>
<SCRIPT TYPE=”text/javascript”
LANGUAGE=”JavaScript”>
setFontColor(11.21);</SCRIPT>
11.21
</FONT>
</FONT>
</TD>
</TR>
<TR VALIGN=TOP>
<TD BGCOLOR=#FFFFFF
WIDTH=”33%” ALIGN=LEFT>
<FONT FACE=”Verdana,
Arial, Helvetica, sans-serif” SIZE=1 CLASS=”s1cB”>
<A HREF=”http://example.com”><NOBR><B>Nasdaq</B></NOBR></A>
</FONT>
</TD>
<TD BGCOLOR=#FFFFFF
WIDTH=”33%” ALIGN=RIGHT>
<FONT FACE=”Verdana,
Arial, Helvetica, sans-serif” SIZE=1 CLASS=”size1″>
1850.43
</FONT>
</TD>
<TD BGCOLOR=#FFFFFF
WIDTH=”33%” ALIGN=RIGHT>
<FONT FACE=”Verdana,
Arial, Helvetica, sans-serif” SIZE=1 CLASS=”size1″>
<SCRIPT TYPE=”text/javascript”
LANGUAGE=”JavaScript”>
setFontColor(-5.10);</SCRIPT>
-5.10
</FONT>
</FONT>
</TD>
</TR>
<TR VALIGN=TOP>
<TD BGCOLOR=#FFFFFF
WIDTH=”33%” ALIGN=LEFT>
<FONT FACE=”Verdana,
Arial, Helvetica, sans-serif” SIZE=1 CLASS=”s1cB”>
<A HREF=”http://example.com”>
<NOBR>
<B>S&P
500</B>
</NOBR>
</A>
</FONT>
</TD>
<TD BGCOLOR=#FFFFFF
WIDTH=”33%” ALIGN=RIGHT>
<FONT FACE=”Verdana,
Arial, Helvetica, sans-serif” SIZE=1 CLASS=”size1″>
1092.50
</FONT>
</TD>
<TD BGCOLOR=#FFFFFF
WIDTH=”33%” ALIGN=RIGHT>
<FONT FACE=”Verdana,
Arial, Helvetica, sans-serif” SIZE=1 CLASS=”size1″>
<SCRIPT TYPE=”text/javascript”
LANGUAGE=”JavaScript”>
setFontColor(-1.94);</SCRIPT>
-1.94
</FONT>
</FONT>
</TD>
</TR>
<TR VALIGN=BOTTOM>
<TD COLSPAN=3 ALIGN=CENTER>
<FONT FACE=”Verdana,
Arial, Helvetica, sans-serif” SIZE=1
COLOR=#003366 CLASS=”s1cB”>
Quotes delayed
by 20 minutes.
</FONT>
</TD>
</TR>
</TABLE>
Notice that a total of 2454 characters are used to display
a grand total of less than 60 characters worth of actual content. Such is
the state of modern markup without CSS.
In addition to using non-standard tags like the <font> element and abusing tables for page layout purposes, web authors have
attempted to overcome the shortcomings of HTML by placing text in images that
are then loaded into the page via the <img> element, or building whole sites
in proprietary technologies such as Flash, a plugin application that loads
in a browser window. Both of these techniques afford the designer much greater
control over presentation than HTML does – especially typographically speaking,
basically giving free reign on typeface, color, and layout. When compared
to the meager presentation control HTML affords, even when using <font> and <table>, a web site built with images instead of text is indeed very attractive.
However, such practices have negative consequences. They
destroy the structural validity of a web page’s markup. This results in the
following problems:
- Inaccessibility
- Degraded performanc
- Increased production work
Inaccessibility
Something not at all immediately apparent to most web professionals,
even experienced ones, is that the Web’s audience is not limited to users
of Internet Explorer and Netscape Navigator. In addition to these premier
visual browsers, there are a plethora of other visual browsers that have smaller
but not insignificant groups of users. The Opera browser, Konqueror, Icab,
Omniweb, and countless other browsers are used by many web surfers, chosen
because they are typically faster at rendering pages than the big two, have
a smaller disk footprint, or are less prone to security hole exploits.
In addition, the Web has already spread to the TV with the
Webtv browser, and web browsers are now a standard feature on digital phones.
Browsers are currently being built into appliances, so you can shop for groceries
online from your refrigerator, or call up a recipe from an online recipe archive
right in your kitchen. Perhaps most importantly, special software, such as
a screen reader, helps the blind to access web content. With good solid structural
XHTML markup, each of these various Internet devices can have equal access
to your site’s content.
In addition, the US federal government has even taken steps
to ensure the accessibility of all federally run web sites. The site http://www.section508.gov details these federal requirements, and many states are currently
enacting similar legislation to ensure these are fulfilled on their state
run sites. Such guidelines, though unfortunately smacking of bureaucratic
red-tape and regulations, are forward-looking and actually quite in keeping
with the spirit of the Web.
Degraded Performance
Bad HTML practices used to achieve your layout and page
design goals can actually make your pages load more slowly in the browser.
Using <table> and <font> elements or inserting site copy into images adds bulk to each web
page. Not only does that bulk require more time to download, it slows the
browser’s rendering engine down when it tries to display the page. It’s a
double whammy. Nested tables, which were almost a necessity when trying to
achieve complicated table layouts, increase rendering time logarithmically
in many common browsers as tables are added to the markup of a page.
Increased Production Work
Web site maintenance is an often overlooked consideration
in the world of web development and design. All too often, client pressure
to quickly produce a site that looks the same in IE and NN results in negligence
on the part of the web professional, who pushes to complete the work quickly
and easily, often testing the site only in browsers likely to be used by the
client. It is often a difficult task to educate the client on the importance
of any factors other than how the page looks in IE, although the lesson is
sometimes learned later when site maintenance costs accumulate.
The fact is that reliance on HTML presentation hacks can
seriously affect the maintainability of a site; not only does the site risk
future obsolescence as newer browsers are introduced, but simple changes to
a large site can become a nightmare of “search and replace”, with
fingers crossed.
Inserting presentation rules directly into HTML documents
with <font> and <table> tags creates a maintenance headache, as any changes to the site presentation
must be made on each document. Even before the site launches, implementing
client-requested changes to a site under development can be a headache if
a hundred HTML documents need to be changed for simple layout tweaks.
Introduction to Cascading Style Sheets
The full adoption of Cascading Style Sheets for web page
layout and typographical design is the next step in the evolution of the Web.
Tired of abusing HTML by using it to control the presentation of web pages,
web professionals are turning en masse to a technology nearly seven years
old in the hopes of rescuing the Web from fracture, and the Web’s content
from unnecessary obsolescence.
CSS has finally garnered enough support from browser makers,
and generated enough excitement from web professionals to start making a difference
on the Web. With the helpful nudging of advocacy groups like the WaSP, browser makers like Microsoft and Netscape have recently released
versions of their Internet Explorer and Navigator browsers with CSS support
improvements in the order of magnitudes over previous releases. And Opera,
the other main browser maker, has of its own initiative put forth arguably
the most complete CSS implementation in its flagship browser, owing in no
small part to the fact that Håkon Lie, the company’s founder chief engineer,
was a member of the group which issued the first CSS recommendation.
Even with great strides in CSS browser support, the adoption
of CSS by the developer is no simple task, especially for those that have
earned their bread and butter relying on the ubiquitous <table> hack and “single pixel gif” tricks (which use invisible
images inserted in a page’s markup to stretch page elements to the desired
dimensions) to force browsers to present their page designs consistently in
a varied and inconsistent field of browsers. For such a group of wizened developers,
deciding to use CSS is more than a decision to change methods of defining
page presentation. To be successful and rewarding, the use of CSS must be
motivated by a thorough understanding of the deficiencies of the Web as we
know it, as well as the promise that CSS and new design methodologies hold
as we try to push the world’s largest and most important media revolution
forward into the 21st century.
For young developers, the generation of people who are the
first to have grown up with the Web as a household word, we must find ways
to teach proper development practices, lest they continue the unfortunate
trend of the early Web towards the use of proprietary HTML extensions and
invalid markup. The view-source school of web design, once a great boon as
web professionals learned from, shared, and expanded upon the work of their
peers, has become a dangerous teacher. Its classes are filled with bad examples
and sites destined for obsolesce and irrelevance as the Web pushes forward;
creaky old markup and questionable development techniques hinder progress.
That is why this book has been written: to train and educate
the builders of the Web to use the appropriate technologies for the task at
hand, in order that the Web in ten years will be the Web that Tim Berners-Lee
intended when he invented it, and not an ever increasing morass of unstructured
information.
The Birth of CSS
It may seem to you at this point that stylesheets are an
afterthought, a change in plans for the Web. But the world’s first web browser
called “The WorldWideWeb browser” and built by Tim Berners-Lee,
included an internal style language used by the browser when rendering HTML
pages. In fact, many of the first generation of web browsers had their own
style languages, some of which were even considered when the CSS recommendation
was first under development. A style language is a natural, even necessary,
partner for a markup language, for as we know, a markup language is not intended
to define presentation.
However, these early HTML style languages were internal,
used by the browser and not available to the document author. It quickly became
apparent to the Web’s early architects that control of presentation must in
some way be wrested from a browser’s internal presentation rules and handed
to the web author. In 1994, Håkon Lie published the first draft of Cascading
HTML Style Sheets.
As Håkon envisioned it, the style language for the Web must
somehow combine author and user preferences. His proposal accomplished this
with a “cascade” which allowed for multiple sets of style rules
and a well-defined system for determining the weight of competing rules. It
was the cascade that set his style language apart from other style languages
of the day, and made it the natural choice for a presentation language to
accompany HTML.
The World Wide Web Consortium (W3C) was formed in 1994 in
order to establish technical standards for the growth and development of the
Web, and it published the first CSS recommendation in December of 1996, known
as CSS1. In May of 1998, the W3C released CSS2, which improved and expanded
upon the first recommendation. CSS3 is currently under development.
These recommendations, while not actually “standards”,
provide browser makers with the necessary information to implement CSS in
a uniform manner. Internet Explorer version 3 was the first browser to implement
CSS, in August of 1996, before CSS was even an official recommendation. Netscape
followed suit, and since then nearly all web browsers have implemented it.
As you’ll learn, browser implementations of CSS vary widely,
a problem that causes many web professionals to run screaming away from stylesheets
with their hair afire. We hope in this book to keep you from that fate by
presenting CSS as it currently works in modern browsers, advising you where
older browsers may fail, and suggesting where future browsers may improve
on CSS support. In the next section we’ll take a look at CSS as it exists
in its natural environment, the web page.
What is CSS?
CSS at its very core is extremely simple and powerful. It
allows you to attach style rules to HTML markup elements, such as <p> or <a> elements. These rules define the presentational aspects of
the HTML elements to which they apply, such as color or typeface.
Take a look at the following sample
page, which includes style rules embedded in the page markup:
<!DOCTYPE html PUBLIC
“-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”
xml:lang=”en” lang=”en”>
<head>
<title>Ye Olde Cheese
Shop</title>
<style type=”text/css”>
body {
font-family: Verdana,
Arial, sans-serif;
}
a {
color: red;
text-decoration: none;
font-weight: bold;
}
#Header {
position: absolute;
left: 25px;
top: 10px;
}
#MainText {
position: absolute;
left: 225px;
top: 100px;
margin-right: 25px;
}
#SiteNav {
position: absolute;
left: 25px;
top: 100px;
width: 175px;
}
</style>
</head>
<body>
<div id=”Header”>
<h1>Ye Olde Cheese
Shop</h1>
</div>
<div id=”SiteNav”>
<h3>Choose a Cheese</h3>
<ul>
<li><a href=””>Beaufort</a></li>
<li><a href=””>Bleu
d’Auvergne</a></li>
<li><a href=””>Brie
de Meaux</a></li>
<li><a href=””>Brillat
Saverin</a></li>
<li><a href=””>St
Maure de Touraine</a></li>
<li><a href=””>Chabichou
de Poitou</a></li>
<li><a href=””>Camembert</a></li>
<li><a href=””>Cantal
Entre Deux</a></li>
<li><a href=””>Chaource</a></li>
<li><a href=””>Comte</a></li>
<li><a href=””>Crottin
de Chavignol</a></li>
<li><a href=””>Emmenthal</a></li>
<li><a href=””>Epoisses</a></li>
<li><a href=””>Langres</a></li>
<li><a href=””>Mimolette</a></li>
<li><a href=””>Morbier</a></li>
<li><a href=””>Munster</a></li>
<li><a href=””>Picodon</a></li>
<li><a href=””>Pont
l’Eveque</a></li>
<li><a href=””>Reblochon</a></li>
<li><a href=””>Rocamadour</a></li>
<li><a href=””>Roquefort</a></li>
<li><a href=””>St.
Marcellin</a></li>
<li><a href=””>St
Nectaire</a></li>
<li><a href=””>Tomme
de Chevre</a></li>
</ul>
</div>
<div id=”MainText”>
<h2>Cheese: it’s
not just for the French anymore</h2>
<p>Lorem ipsum
dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod
tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad
minim veniam, quis nostrud exercitation ulliam corper suscipit lobortis
nisl ut aliquip ex ea commodo consequat. Duis autem veleum iriure dolor
in hendrerit in vulputate velit esse molestie consequat, vel willum lunombro
dolore eu feugiat nulla facilisis at vero eros et accumsan et iusto odio
dignissim qui blandit praesent luptatum zzril delenit augue duis dolore
te feugait nulla facilisi.</p>
<p>Li Europan
lingues es membres del sam familie. Lor separat existentie es un myth. Por
scientie, musica, sport etc., li tot Europa usa li sam vocabularium. Li
lingues differe solmen in li grammatica, li pronunciation e li plu commun
vocabules. Omnicos directe al desirabilità de un nov lingua franca: on refusa
continuar payar custosi traductores. It solmen va esser necessi far uniform
grammatica, pronunciation e plu sommun paroles.</p>
</div>
</body>
</html>
This page displays as follows:
Now, let’s take a closer look at the markup and style rules.
We’ll be going into much greater detail in future chapters, so don’t worry
if not everything makes sense. It is enough now to get a general sense of
how stylesheets interact with XHTML markup.
The first thing to notice is the <style> element itself:
<style type=”text/css”>
…
</style>
The <style> element appears in the <head> element of an XHTML document. Its
type attribute declares that the style language
is CSS, and overrides the default stylesheet language used by the browser
when rendering stylesheets. Actually, there are no other style languages in
use by browsers today, except for Netscape Navigator 4.x’s proprietary “JavaScript
Stylesheets”, which use the type attribute value “text/javascript”. However, as with many things in CSS, the type attribute looks forward to a time when browsers provide support for
multiple style languages.
Contained within the <style> element are the style rules that define certain presentational aspects
of the page. Each rule contains two main parts: a selector followed by a list of declarations. The selector defines which XHTML page element(s)
the rule applies to, and the declarations define the presentational aspects
that are to be applied to those elements.
The first rule in our sample page (seen below) selects the <body>
element and declares that text within it should be presented with the
typeface. If that font is not installed in the system, then Arial
should be used; if this typeface is not available either, a sans-serif
typeface is to be used.
body {
font-family: Verdana,
Arial, sans-serif;
}
The next rule in our stylesheet declares that all <a> elements are to be displayed with bold,
red text with no text decoration (underlines, overlines, etc.).
a {
color: red;
font-weight: bold;
text-decoration: none;
}
The final three rules in our stylesheet are quite different
from the first two:
#Header {
position: absolute;
left: 25px;
top: 10px;
}
#MainText {
position: absolute;
left: 225px;
top: 100px;
margin-right: 25px;
}
#SiteNav {
position: absolute;
left: 25px;
top: 100px;
width: 175px;
}
Each of these three rules do not apply to all elements of
any one type, such as all links in the preceding example, but instead apply
to elements with a specific id attribute value. The # character is used
to indicate this type of rule, followed by the id attribute value itself. So, the following
rule:
#Header {
position: absolute;
left: 25px;
top: 10px;
}
applies to the following element:
<div id=”Header”>
<h1>Ye Olde Cheese
Shop</h1>
</div>
and instructs the browser on the exact location that the
<div> element should appear on screen.
The example above is of course quite simple, and does not
even really scratch the surface of what CSS is capable of. In subsequent chapters
we’ll explore how CSS gives you powerful typographic control over your pages,
allowing you to specify not only the font, but the relative size, the line
height, and numerous other presentational aspects of your text. You’ll also
learn how to select broad areas or certain specific elements of your document
with a given rule, along with how to use CSS to define complex page layouts.
The Separation of Structure and Presentation
In this chapter I’ve given you a short history of the Web,
told you how using HTML as a presentation language is injurious to your sites
and the Web as a whole, and introduced you to the basics of using CSS for
web page presentation. I want to leave you with perhaps the most important
information so far: the reasons you as a web professional should want CSS.
What will you get out of it?
An important principle that underlies all the arguments
in favor of CSS is referred to as “The Separation of Structure and Presentation”
or sometimes “The Separation of Content and Presentation”.
This separation of markup (structure and content) and style rules (presentation) is
valuable to the web professional in many ways, as you’ll soon see.
Earlier I told you how HTML used
as a presentation language results in several negative consequences, including
decreased accessibility, degraded performance, and increased production work.
Now I’ll detail how “The Separation of Structure and Presentation”,
using sound structural HTML markup with CSS for presentation, results in the
following benefits:
- Increased accessibility
- Improved performance
- Decreased production work
Accessibility
Accessibility is all about making
your web page available to the maximum number of users and Internet devices.
With sound structural markup, your HTML pages are accessible and understandable
to the widest possible audience, including site visitors with older browsers,
next year’s visitors using new browsers that are yet to be released, blind
visitors who rely on screen readers to access your site, and last but not
least, indexing agents.
“What is sound structural markup?”
you ask. Well, let’s take a look at an example of bad markup:
<font size=”5″
face=”Arial” color=”green”>My Page Title</font><br
/><br />
In the above example, the <font> element has been used to give a page header a certain typeface, color,
and size. Two <br elements follow to give the text the proper
bottom margin. This will look as desired in most major browsers today, which
gives the false impression that all is well. In fact, by using the <font> element, which communicates no information
about the text ” My Page Title”
other than presentational directions, you’ve rendered the text less intelligible
to both old browsers, screen readers, and indexing agents.
On the other hand, the following markup communicates a great
deal of information:
By using the <h2> element, you’ve instructed
all devices that parse the HTML that “My Page Title”
is a header. Screen readers can give special emphasis to the text; old, current,
and future browsers can render it appropriately on screen (with or without
further style rules); and indexing agents, such as the spider for search engine
Google that crawls the Web to add pages to the Google database, can give extra
weight to the header text in their search result algorithms, which leads to
your pages appearing higher in the search results for the most relevant search
terms.
“But you’ve removed the presentational cues, and now
the text is no longer green, or displayed with the Arial typeface”, you
say. Adding the following style rule to the document solves this problem:
h2 {
font-family: Arial;
color: green;
font-size: 1.4em;
}
In addition, now that the rule has been declared, all <h2> elements will share the same presentation
without the need to surround each one with extraneous markup. This leads us
to another benefit of the “The Separation of Structure and Presentation”.
Improved Performance
By providing one level of indirection,
or abstraction, CSS embedded in the head of a document streamlines document
markup, improving download times and speeding up page rendering. Instead of
relying on markup to instruct browsers on how to display each separate instance
of an element, CSS allows us to declare a style rule once and have that presentational
cue apply to all such elements. Let’s take the bloated HTML example from early
in this chapter and see how much space we can save by applying CSS and the
principle of the separation of presentation and structure:
<style type=”text/css”>
td {
background: #FFF;
font-family: Verdana,
Arial, Helvetica, sans-serif;
font-size: .6em;
text-align: right;
}
td.left {
text-align: left;
}
a {
font-weight: bold;
}
</style>
<table border=”0″
cellpadding=”2″ cellspacing=”2″>
<tr valign=”top”>
<td width=”33%”
class=”left”>
<a href=”http://example.com”>
<nobr>
Dow
</nobr>
</a>
</td>
<td width=”33%”>
9698.30
</td>
<td width=”33%”>
11.21
</td>
</tr>
<tr valign=”top”>
<td width=”33%”
class=”left”>
<a href=”http://example.com”><nobr>Nasdaq</nobr></a>
</td>
<td width=”33%”>
1850.43
</td>
<td width=”33%”>
-5.10
</td>
</tr>
<tr valign=”top”>
<td width=”33%”
class=”left”>
<a href=”http://example.com”>
<nobr>
S&P
500
</nobr>
</a>
</td>
<td width=”33%”>
1092.50
</td>
<td width=”33%”>
-1.94
</td>
</tr>
<tr valign=”bottom”>
<td colspan=3 align=”center”>
Quotes delayed by
20 minutes.
</td>
</tr>
</table>
I’ve removed all the <font> elements and bgcolor attributes from the table cells, and
replaced those presentation directions with three style rules. In so doing,
I’ve cut the size of the HTML markup down from 2456 characters to 954 characters,
and that’s even after adding in missing quotation marks around attribute values,
which were missing in the original markup. Even after including the style
rules in with the markup, I’ve still cut the size of the file by more than
half to 1169 characters, and the look of the table remains virtually identical
in all major browsers.
In more complex situations, even more file size savings
can be achieved. For instance, advanced CSS rules allow us to group selectors,
so that one rule can apply to multiple elements, like so:
h1, h2, h3, h4, h5, h6
{
font-family: Arial;
color: green;
}
Furthermore, another level of indirection can be added by
using external stylesheets, creating even greater download
time reductions. The examples you’ve seen above have used embedded stylesheets, which are contained within
the <head> element of the page to which they
apply. Using external stylesheets allows you to link a stylesheet to multiple
XHTML pages. This can significantly improve performance on a site, since the
stylesheet needs only to be downloaded once per visitor. It is then stored
in the visitor’s browser cache, and subsequent page loads from the site by
that visitor require only the download of the XHTML markup.
Smaller file sizes and cached external stylesheets not only
mean a speedier site, which makes your visitors happy, but can also result
in lowered hosting costs for you, as your site takes less bandwidth to serve.
In addition to bandwidth savings and the speed increases
your site visitors will enjoy when you use well-structured markup and CSS,
you as a web professional will have at your disposal a powerful style language
that allows much greater control over the appearance of your pages than <font> and <table> elements could ever provide.
As if that wasn’t enough, CSS and solid markup are the foundation
for DHTML, with which you can add dynamic behaviors to your web documents.
With DHTML, JavaScript is used to manipulate page elements and their style
properties to create dynamic pages that can react to user input, animate page
elements, and provide new and innovative interfaces to your site visitors.
We won’t be talking much about DHTML in this book, but the skills you’ll learn
here will set you well on the path to understanding how to build dynamic sites
with DHTML.
Decreased Production Work
It may be hard to believe, but not only does the use of
CSS and sound structural markup improve the experience of your site visitors
and provide you with cost savings and a powerful style language, it actually
makes your job easier as a web professional. By separating presentational
directions from your HTML, especially when using external stylesheets, you
make it easier to build and maintain sites. Your clean markup will be easier
to develop initially, since the job of marking up the information in your
HTML pages can be a discreet task, unfettered with concerns about color and
typeface. Maintaining pages with clean HTML becomes a simple task also, saving
you from the headache of searching through lines of bloated HTML for that
one simple link you want to change.
Redesigning a site also becomes a much simpler task. When
using an external stylesheet for a whole site, redesigning involves changing
only that one document instead of editing each individual HTML page.
All of these improvements, which you gain with the use of
CSS, result in cost savings that make your clients happier, and your pocketbook
fatter.
Summary
CSS is an important part of the future of the Web. It is
unfortunate that a style language was not available to the Web’s early document
authors, as it might have helped change the problematic route that HTML took,
driven by author desire to control page presentation and fueled by short-sighted
browser vendors eager to attract developers to their platform. But CSS is
ready for the masses now, and provides a great improvement to the web professional
in many areas.
In coming chapters, you’ll get a detailed look at the ins
and outs of developing pages with Cascading Style Sheets. You’ll learn good
markup practices, how to control typography, and how to use CSS to layout
pages. When you’ve finished this book, you’ll be prepared to develop the Web
as it was intended to be developed, not only making your job easier and your
clients happier, but also making the Web a better and more useful place.