The Essential Guide To HTML5 And CSS3 Web Design

Guide%20To%20HTML5%20and%20CSS3

User Manual:

Open the PDF directly: View PDF PDF.
Page Count: 510 [warning: Documents this large are best viewed by clicking the View PDF Link!]

US $34.99
Mac/PC compatible
www.apress.com
SHELVING CATEGORY
WEB DESIGN/HTML
The Essential Guide to
HTML5 and CSS3 Web Design
The Essential Guide to HTML5 and CSS3 Web Design contains everything you need to
design great websites that are standards-compliant, user-friendly, and aesthetically pleas-
ing. It has been fully revised from its critically acclaimed first edition and now includes
the new features and best practices of HTML5 and CSS3.
Authors Craig Grannell, Victor Sumner, and Dionysios Synodinos start you off with a
brief introduction to web design before diving into HTML5 and CSS3 basics, code reuse,
and other best practices. Then they focus on the most important aspects of a successful
website: typography, images, navigation, tables, layouts, forms and feedback (including
ready-made PHP scripts), browser quirks, hacks, and bugs.
Throughout, engaging case studies help you gain invaluable firsthand experience with
important design elements, including all the most popular website archetypes: a blog,
a storefront, a corporate homepage, and an online gallery. You’ll also appreciate the
detailed reference appendixes covering HTML, CSS, color references, entities, and more.
You’ll find The Essential Guide to HTML5 and CSS3 Web Design invaluable at any stage of
your career. If you’re just starting out, this helpful guide quickly teaches you the basics.
If you’re an experienced developer, it will serve as your ideal reference on techniques,
attributes, and other details you may not have used yet.
RELATED TITLES
The basics of HTML5 and CSS3 web design
The newest standards implemented in Internet Explorer, Firefox, Opera, Safari, and Chrome
Effective layouts, tables, images, navigation, forms, and typography
Cross-browser issues, including quirks, bugs, and hacks in all the major browsers
Approaches for user-friendly and accessible websites
Real-world examples of different styles of web front ends
GRANNELL
SUMNER
SYNODINOS
HTML5 and CSS3 Web Design
ft
.
7
f
'
£
y
L
:
BC3
ESSENTIAL
IdlJIJÿftl
iTi
:;.]!
o
1
i
§1:;
0
II
II
I I
IKIIIII
i
II
I
HU1!
iH
J1
ij
RP[!
B
msam
II
ill
u
illl
III
rfS
.
.in
%*
.....
r
•.in
R
7
£X-
BBS
111
Hi
MjjTJB
www.freepdf-books.com
For your convenience Apress has placed some of the front
matter material after the index. Please use the Bookmarks
and Contents at a Glance links to access them.
www.freepdf-books.com
iv
Contents at a Glance
About the Authors .................................................................................................... xiii
About the Technical Reviewer................................................................................. xiv
About the the Cover Image Designer....................................................................... xv
Acknowledgments .................................................................................................... xvi
Introduction.............................................................................................................. xvii
Chapter 1: An Introduction to Web Design ............................................................... 1
Chapter 2: Web Page Essentials .............................................................................. 29
Chapter 3: Working With Type.................................................................................. 63
Chapter 4: Working With Images............................................................................ 119
Chapter 5: Using Links and Creating Navigation ................................................. 145
Chapter 6: Tables: How Nature (and the W3C) Intended ..................................... 227
Chapter 7: Page Layouts with CSS ........................................................................ 249
Chapter 8: Getting User Feedback......................................................................... 307
Chapter 9: Dealing with Browser Quirks ............................................................... 343
Chapter 10: Putting Everything Together.............................................................. 357
Appendix A: An HTML5 reference.......................................................................... 387
Appendix B: Web Color Reference ........................................................................ 437
Appendix C: ENTITES reference ............................................................................ 441
Appendix D: CSS Reference................................................................................... 459
Index.......................................................................................................................... 485
www.freepdf-books.com
xvii
Introduction
The Web is an ever-changing, evolving entity, and it’s easy to get left behind. As designers and writers, we
see a lot of books on web design, and although many are well written, few are truly integrated, modular
resources that anyone can find useful in their day-to-day work. Most web design books concentrate on a
single technology (or, commonly, a piece of software), leaving you to figure out how to put the pieces
together.
This book is different
The Essential Guide to HTML5 and CSS3 Web Design provides a modern, integrated approach to web
design. Each of the chapters looks at a specific aspect of creating a web page, such as formatting type,
working with images, creating navigation, and creating layout blocks. In each case, relevant technologies
are explored in context and at the appropriate times, just like in real-world projects; for example, markup is
explored along with associated CSS and JavaScript, rather than each technology being placed in separate
chapters, and visual design ideas are discussed so you can get a feel for how code affects page layouts.
Dozens of practical examples are provided, which you can use to further your understanding of each
subject. This highly modular and integrated approach means you can dip in and out of the book as you
need, crafting along the way a number of web page elements that you can use on countless sites in the
future.
Because the entire skills gamut is covered—from foundation to advanced—this book is ideal for beginners
and longtime professionals alike. If you’re making your first move into standards-based web design, the
“ground floor” is covered, rather than an assumption being made regarding your knowledge. However,
contemporary ideas, techniques, and thinking are explored throughout, ensuring that the book is just as
essential for the experienced designer wanting to work on CSS layouts or for the graphic designer who
wants to discover how to create cutting-edge websites.
This book’s advocacy of web standards, usability, and accessibility with a strong eye toward visual design
makes it of use to technologists and designers alike, enabling everyone to build better websites. For those
moments when a particular tag or property value slips your mind, this book provides a comprehensive
reference guide that includes important and relevant HTML5 elements and attributes, HTML5 entities, web
colors, and CSS 3 properties and values.
Code Examples
Remember that you can also download files associated with this book from www.apress.com—just find the
book and follow its instructions to access downloads and other associated resources.
To make it easier to work through the exercises, each one has an introductory box that lists where you can
find any required files and the completed files within the downloadable file archive. A short overview of
what you’ll learn is also included.
www.freepdf-books.com
1
Chapter 1
An Introduction to Web Design
In this chapter:
Introducing the Internet and web design
Working with web standards
Working with HTML
Understanding and creating CSS rules
Creating web page boilerplates
www.freepdf-books.com
Chapter 1
2
Organizing web page content
A brief history of the Internet
Even in the wildest dreams of science-fiction and fantasy writers, few envisioned anything that offers the
level of potential that the Internet now provides for sharing information on a worldwide basis. For both
businesses and individuals, the Internet is now the medium of choice, largely because it enables you to
present your wares to the entire world on a 24/7 basis. But the technology’s origins were more ominous
than and very different from the ever-growing, sprawling free-for-all that exists today.
In the 1960s, the American military was experimenting with methods by which the U.S. authorities might
be able to communicate in the aftermath of a nuclear attack. The suggested solution was to replace point-
to-point communication networks with one that was more akin to a net. This meant information could find
its way from place to place even if certain sections of the network were destroyed. Despite the project
eventually being shelved by the Pentagon, the concept itself lived on, eventually influencing a network that
connected several American universities.
During the following decade, this fledgling network went international and began opening itself up to the
general public. The term Internet was coined in the 1980s, which also heralded the invention of
Transmission Control Protocol/Internet Protocol (TCP/IP), the networking software that makes possible
communication between computers running on different systems. During the 1980s, Tim Berners-Lee was
also busy working on HTML, his effort to weld hypertext to a markup language in an attempt to make
communication of research between himself and his colleagues simpler.
Despite the technology’s healthy level of expansion, the general public remained largely unaware of the
Internet until well into the 1990s. By this time, HTML had evolved from a fairly loose set of rules—browsers
having to make assumptions regarding coder intent and rendering output—to a somewhat stricter set of
specifications and recommendations. This, along with a combination of inexpensive hardware, the advent
of highly usable web browsers such as Mosaic (see the following image), and improved communications
technology, saw an explosion of growth that continues to this day.
Initially, only the largest brands dipped their toes into these new waters, but soon thousands of companies
were on the Web, enabling customers all over the globe to access information and, later, to shop online.
Home users soon got in on the act, once it became clear that the basics of web design weren’t rocket
science and that, in a sense, everyone could do it—all you needed was a text editor, an FTP client, and
some web space. Designers soon got in on the act, increasingly catered for by new elements within HTML;
Cascading Style Sheets (CSS), which took a while to be adopted by browsers but eventually provided a
means of creating highly advanced layouts for the Web; and faster web connections, which made media-
rich sites accessible to the general public without forcing them to wait ages for content to download.
Therefore, unlike most media, the Web is truly a tool for everyone, and in many countries, the Internet has
become ubiquitous. For those working in a related industry, it’s hard to conceive that as recently as the
mid-1990s relatively few people were even aware of the Internet’s existence!
www.freepdf-books.com
An Introduction to Web Design
3
So, from obscure roots as a concept for military communications, the Internet has evolved into an essential
tool for millions of people, enabling them to communicate with each other, research and gather
information, telecommute, shop, play games, and become involved in countless other activities on a
worldwide basis.
Why create a website?
Before putting pen to paper (and mouse to keyboard), it’s important to think about the reason behind putting
a site online. Millions already exist, so why do you need to create one yourself? Also, if you’re working for
a company, perhaps you already have plenty of marketing material, so why do you need a website as
well?
I should mention here that I’m certainly not trying to put you off—far from it. Instead, I’m trying to reinforce
the point that planning is key in any web design project, and although some people swear that “winging it”
is the best way to go, most such projects end up gathering virtual dust online. Therefore, before doing
anything else, think through why you should build a website and what you’re trying to achieve.
Companies and individuals alike have practical and commercial reasons for setting up a website. A
website enables you to communicate with like-minded individuals or potential clients on a worldwide basis.
If you’re a creative talent of some kind, you can use a website to showcase your portfolio, offering online
photographs, music tracks for download, or poetry. If you fancy yourself as a journalist, a blog enables you
to get your opinion out there. If you own or work for a business, creating a website is often the most
www.freepdf-books.com
Chapter 1
4
efficient means of marketing your company. And even if you just have a hobby, a website can be a great
way of finding others who share your passion—while you may be the only person in town who likes a
particular movie or type of memorabilia, chances are there are thousands of people worldwide who think
the same, and a website can bring you all together. This is perhaps why the paper fanzine has all but died,
only to be reborn online, where development costs are negligible and worldwide distribution is a cinch.
In practical terms, a website exists online all day, every day (barring the odd hiccup with ISPs), which
certainly isn’t the case with printed media, which is there one minute and in the recycle trash the next.
Distribution is less expensive than sending out printed material—a thousand-page website can be hosted
for $10 per month or less, but sending a thousand-page document to one person (let alone a thousand or
several thousand) may cost more than that. Likewise, development (particularly corrections and updates)
is often significantly cheaper, too. For example, if you want to rework a print brochure, you have to
redesign it and then reprint it. Reworking a section of a website often means swapping out a few files,
which is efficient and affordable. So, for large companies and individuals alike, the ability to have relevant
information online in a form that can often be updated in mere minutes, thereby keeping all interested
parties up-to-date, is hard to resist!
Audience requirements
This book centers on the design and technology aspects of web design, but close attention must always
be paid to your potential audience. It’s no good forcing design ideas that result in inappropriate visuals,
unusable navigation to all but the most technically minded of people, and huge download times on your
site’s unsuspecting visitors.
Prior to creating a site, you must ascertain what your audience wants and expects in terms of content,
design, and how the site will work (by way of talking to the relevant people, and also, if your budget allows,
by using surveys and focus groups). You don’t have to take all of your audience’s ideas into account (after
all, many will be contradictory), but be mindful of common themes and ensure they’re not ignored.
Technical considerations must be researched. If you’re targeting designers, you can be fairly sure that a
large proportion of the audience will be using monitors set to a high resolution and millions of colors, and
you can design accordingly. If your site is targeting mobile users, be mindful that it will be displayed on a
wide range of devices. From tablets and smartphones with high-resolution Retina or PenTile technology
displays to those with low-resolution LCD displays, mobile devices come in all shapes, sizes, and
capabilities.
Determining the web browsers your audience members use is another important consideration. Although
use of web standards (used throughout this book) is more likely to result in a highly compatible site,
browser quirks still cause unforeseen problems; therefore, always check to see what browsers are popular
with a site’s visitors, and ensure you test in as many as you can. Sometimes you won’t have access to
such statistics, or you may just be after a “sanity check” regarding what’s generally popular. A
couple of useful places to research global web browser statistics are
www.w3schools.com/browsers/browsers_stats.asp and www.upsdell.com/BrowserNews/. Note, though,
that any statistics you see online are effectively guesswork and are not a definitive representation of the
www.freepdf-books.com
An Introduction to Web Design
5
Web as a whole; still, they do provide a useful, sizeable sample that’s often indicative of current browser
trends.
Although you might be used to checking browser usage and then, based on the results, designing for
specific browsers, we’ll be adhering closely to web standards throughout this book. When doing this, an
“author once, work anywhere” approach is feasible, as long as you’re aware of various browser quirks
(many of which are explored in Chapter 9). Of course, you should still always ensure you test sites in as
many browsers as possible, just to make sure everything works as intended.
Web design overview
Web design has evolved rapidly over the years. Initially, browsers were basic, and early versions of HTML
were fairly limited in what they enabled designers to do. Therefore, many older sites on the Web are plain
in appearance. Additionally, the Web was originally largely a technical repository, which is the reason for
the boring layouts of many sites in the mid-1990s; after all, statistics, documentation, and papers rarely
need to be jazzed up, and the audience didn’t demand such things anyway.
As with any medium finding its feet, things soon changed, especially once the general public flocked to the
Web. It was no longer enough for websites to be text-based information repositories. Users craved—
demanded, even—color! Images! Excitement! Animation! Interaction! Even video and audio managed to
get a foothold as compression techniques improved and connection speeds increased.
The danger of eye candy became all too apparent as the turn of the century approached: every site, it
seemed, had a Flash intro, and the phrase “skip intro” became so common that it eventually spawned a
parody website.
These days, site design has tended toward being more restrained, as designers have become more
comfortable with using specific types of technologies for relevant and appropriate purposes. Therefore,
you’ll find beautifully designed HTML- and CSS-based sites sitting alongside highly animated Flash efforts.
Also, with the increasing popularity of JavaScript and the introduction of CSS Transitions and HTML5
Canvas, Flash appears to be on the way out because Adobe has recently discontinued support for Flash
on mobile devices.
Of late, special emphasis is being placed on usability and accessibility, and in the majority of cases,
designers have cottoned to the fact that content must take precedence. However, just because web
standards, usability, and accessibility are key, that doesn’t mean design should be thrown out the window.
As we’ll see in later chapters, web standards do not have to come at the expense of good design—far from
it. In fact, a strong understanding of web standards helps improve websites, making it easier for you to
create cutting-edge layouts that work across platforms and are easy to update. It also provides you with a
method of catering for obsolete devices.
www.freepdf-books.com
Chapter 1
6
Note: If you’re relatively new to web design, you may be wondering about the best
platform and software for creating websites. Ultimately, it matters little which platform
you choose, as long as you have access to the most popular browsers for testing
purposes (a list that I’d now include Apple’s Safari in, alongside Chrome, Internet
Explorer, Firefox, and Opera). Regarding software, there’s an overview in Appendix E,
but this isn’t an exhaustive guide, so do your own research and find software to your
liking.
Why WYSIWYG tools aren’t used in this book
With lots of software available and this book being design-oriented, you might wonder why I’m not using
WYSIWYG web design tools. This isn’t because I shun such tools—it’s more that in order to best learn
how to do something, you need to start from scratch, with the foundations. Many web design applications
make it tempting to “hide” the underlying code from you, and most users end up relying on the graphical
interface. This is fine until something goes wrong and you don’t know how to fix it.
Removing software from the equation also means we concentrate on the underlying technology that drives
web pages, without the distraction of working out which button does what. It also ensures that the book will
be relevant to you, regardless of what software you use or your current skill level. Therefore, I suggest you
install a quality text editor to work through the exercises or set your web design application to use its code
view. Once you’re familiar with the concepts outlined in this book, you can apply them to your work,
whatever your chosen application for web design. This level of flexibility is important, because you never
know when you might have to switch applications—something that’s relatively painless if you know how to
design for the Web and understand technologies like CSS and HTML.
Introducing HTML5
The foundation of the majority of web pages is HyperText Markup Language, commonly known by its
initials, HTML. A curious facet of the language is that it’s easy to pick up the basics—anyone who’s
computer literate should be able to piece together a basic page after learning some tags—but it has
enough flexibility and scope to keep designers interested and experimenting, especially when HTML is
combined with Cascading Style Sheets (CSS), which we’ll discuss later in this chapter.
The HTML5 syntax is designed to be simpler, more flexible, developer-friendly, and backward-compatible
than HTML4 and XHTML. HTML5 introduces new features such as animation, offline capabilities, audio,
advanced graphics, typography, transitions, and more, which yields a new class of web standards and
replaces the need for proprietary technologies, like Flash and native mobile platforms.
www.freepdf-books.com
An Introduction to Web Design
7
Introducing the concept of HTML tags and elements
HTML documents are text files that contain tags, which are used to mark up HTML elements. These
documents are usually saved with the .html file extension, although other extensions like .htm can be
used.
The aforementioned tags are what web browsers use to display pages, and assuming the browser is well
behaved (most modern ones are), the display should conform to standards as laid out by the World Wide
Web Consortium (W3C), the organization that develops guidelines and specifications for many web
technologies.
Note: The W3C website is found at www.w3.org. The site offers numerous useful tools,
including validation services against which you can check your web pages.
HTML tags are surrounded by angle brackets—for instance, <p> is a paragraph start tag. It’s good practice
to close tags once the element content or intended display effect concludes, and this is done with an end
tag. End tags are identical to the opening start tags but with an added forward slash: /. A complete HTML
element looks like this:
<p>Here is a paragraph.</p>
This element consists of the following:
Start tag: <p>
Content: Here is a paragraph.
End tag: </p>
Note: HTML doesn’t have a hard-and-fast rule regarding the case of tags. If you look at
the source code of HTML pages on the Web, you may see lowercase tags, uppercase
tags, or, in the case of pages put together over a period of time, a mixture of the two.
That said, it’s still good practice with any markup language to be consistent, regardless
of whether the rules are more flexible.
Nesting tags
There are many occasions when tags must be placed inside each other; this process is called nesting.
One reason for nesting is to apply basic styles to text-based elements. Earlier, you saw the code for a
paragraph element. We can now make the text bold by surrounding the element content with a strong
element:
<p><strong>Here is a paragraph.</strong></p>
www.freepdf-books.com
Chapter 1
8
You might be used to using the bold element to make text bold, but it is a physical
element that only amends the look of text rather than also conveying semantic meaning.
Logical elements, such as strong, convey meaning and add styling to text and are
therefore preferred. These will be covered in Chapter 3.
Note that the strong tags are nested within the paragraph tags (<p></p>), not the other way around. That’s
because the paragraph is the parent element to which formatting is being applied. The paragraph could be
made bold and italic by adding another element, emphasis (<em></em>), as follows:
<p><strong><em>Here is a paragraph.</em></strong></p>
In this case, the strong and em tags could be in the opposite order, because they’re at the same level in
the hierarchy. However, you must always close nested tags in the reverse order to that in which they’re
opened, as shown in the previous code block; otherwise, some browsers may not display your work as
intended. For instance, the following should be avoided:
<p><strong><em>Here is a paragraph.</strong></em></p>
As previously mentioned, it’s good practice to close tags in HTML—even though it’s not a requirement for
all elements, being sloppy in this area can lead to errors. Take a look at the following:
<p><strong><em>Here is a paragraph.</strong></p>
Here, the emphasis element isn’t closed, meaning subsequent text-based content on the page is likely to
be displayed in italics—so take care to close all your tags.
Web standards and HTML
HTML5 is an updated version of the HTML specification that has been around since 1997 and many of its
features are already supported in today’s browsers. The changes in HTML5 include a focus on semantic
markup like the addition of the <header>, <footer>, <section>, and <article> elements and also the
addition of the <canvas> element for displaying advanced interactive graphics and the <video> element for
displaying video. Websites like html5please.com, caniuse.com, and of coarse the WC3 working draft
(http://dev.w3.org/html5/html4-differences/) are great resources for finding out what has changed, what is
new, or what is supported in each browser.
HTML5 markup can be defined in whatever way you want it to be. Uppercase, lowercase, quoted,
unquoted, self-closing or not—it’s your choice. The ultimate goal is semantic markup, ensuring the
elements you choose and the style of your markup define the meaning of your content as closely as
possible.
Evolution is another aspect that we have to deal with. Just as the survival of the fittest removes some
species from nature, so too are tags (and attributes) unceremoniously dumped from the W3C
specifications. Such tags and attributes are referred to as deprecated, meaning they are marked for
removal from the standard and may not be supported in future browsers. In the case of HTML5 obsolete
tags and attributes are still supported because of HTML5’s backward-compatibility, it is still recommended
www.freepdf-books.com
An Introduction to Web Design
9
that you do not use such tags and attributes because new implementations of browsers may choose not to
support them.
Semantic markup
In the previous few subsections, you may have noticed specific elements being used for specific things.
This is referred to as semantic markup and is a very important aspect of modern web design. Plenty of
HTML elements exist, and each one has a clearly defined purpose (although some have more than one
use). Because of the flexibility of markup languages, it’s often possible to “wrongly” use elements, bashing
your page into shape by using elements for design tasks they’re not strictly suited for and certainly weren’t
originally designed for.
During the course of this book, we’ll talk about semantics a fair amount. Ultimately, good semantic design
enables you to simplify your markup and also provides the greatest scope for being able to style it with
CSS (see the following section). By thinking a little before you code and defining your content with the
correct markup, you’ll end up with cleaner code and make it much easier for yourself in the long run when
it comes to adding presentation to your content.
Introducing CSS
CSS is the W3C standard for defining the visual presentation for web pages. HTML was designed as a
structural markup language, but the demands of users and designers encouraged browser manufacturers
to support and develop presentation-oriented tags. These tags “polluted” HTML, pushing the language
toward one of decorative style rather than logical structure. Its increasing complexity made life hard for
web designers, and source code began to balloon for even basic presentation-oriented tasks. Along with
creating needlessly large HTML files, things like font tags created web pages that weren’t consistent
across browsers and platforms, and styles had to be applied to individual elements—a time-consuming
process.
The concept behind CSS was simple yet revolutionary: remove the presentation and separate design from
content. Let HTML deal with structure, and use CSS for the application of visual presentation.
The idea caught on albeit slowly. The initial problem was browser support. At first, most browsers
supported only a small amount of the CSS standard—and badly at that. But Internet Explorer 5 for Mac
made great strides with regard to CSS support, and it was soon joined by other browsers fighting for the
crown of standards king. These days, every up-to-date browser supports the majority of commonly used
CSS properties and values, and more besides.
Another problem has been educating designers and encouraging them to switch from old to new methods.
Benefits constantly need to be outlined and proven, and the new methods taught. Most designers these
days style text with CSS, but many still don’t use CSS for entire web page layouts, despite the inherent
advantages in doing so. This, of course, is one of the reasons for this book: to show you, the designer,
how CSS can be beneficial to you—saving you (and your clients) time and money—and to provide
examples for various areas of web page design and development that you can use in your sites.
www.freepdf-books.com
Chapter 1
10
In this section, we’ll look at separating content from design, CSS rules, CSS selectors and how to use
them, and how to add styles to a web page.
Separating content from design
Do you ever do any of the following?
Use tables for website layout
Hack Photoshop documents to bits and stitch them back together in a web page to create
navigation elements and more
Get frustrated when any combination of the previous leads to unwieldy web pages that are a pain
to edit
If so, the idea of separating content from design should appeal to you. On one hand, you have your HTML
documents, which house content marked up in a logical and semantic manner. On the other hand, you
have your CSS documents, giving you sitewide control of the presentation of your web page elements
from a single source. Instead of messing around with stretching transparent GIFs and combining and
splitting table cells, you can edit CSS rules to amend the look of your site, which is great for not only those
times when things just need subtle tweaking but also when you decide everything needs a visual overhaul.
After all, if presentation is taken care of externally, you can often just replace the CSS to provide your site
with a totally new design.
Designers (and clients paying for their time) aren’t the only ones to benefit from CSS. Visitors will, too, in
terms of faster download times but also with regard to accessibility. For instance, people with poor vision
often use screen readers to surf the Web. If a site’s layout is composed of complex nested tables, it might
visually make sense; however, the underlying structure may not be logical. View the source of a document,
and look at the order of the content. A screen reader reads from the top to the bottom of the code and
doesn’t care what the page looks like in a visual web browser. Therefore, if the code compromises the
logical order of the content (as complex tables often do), the site is compromised for all those using screen
readers.
Accessibility is now very important in the field of web design. Legislation is regularly passed to strongly
encourage designers to make sites accessible for web users with disabilities. It’s likely that this trend will
continue, encompassing just about everything except personal web pages. (However, even personal
websites shouldn’t be inaccessible.)
The rules of CSS
Style sheets consist of a number of rules that define how various web page elements should be displayed.
Although sometimes bewildering to newcomers, CSS rules are simple to break down. Each rule consists of
a selector and a declaration. The selector begins a CSS rule and specifies which part of the HTML
document the rule will be applied to. The declaration consists of a number of property/value pairs that set
specific properties and determine how the relevant element will look. In the following example, p is the
selector, and everything thereafter is the declaration:
www.freepdf-books.com
An Introduction to Web Design
11
p {
color: blue;
}
As you probably know, p is the HTML tag for a paragraph. Therefore, if we attach this rule to a web page
(see the section “Adding styles to a web page” later in this chapter for how to do so), the declaration will be
applied to any HTML marked up as a paragraph, thereby setting the color of said paragraphs to blue.
Note: CSS property names are not case sensitive, but it’s good to be consistent in web
design—it’s highly recommended to always use lowercase.
When you write CSS rules, you place the declaration within curly brackets: {}. Properties and values are
separated by a colon (:), and property/value pairs are terminated by a semicolon (;). Technically, you don’t
have to include the final semicolon in a CSS rule, but most designers consider it good practice to do so.
This makes sense—you may add property/value pairs to a rule at a later date, and if the semicolon is
already there, you don’t have to remember to add it.
If we want to amend our paragraph declaration and define paragraphs as bold, we can do so like this:
p {
color: blue;
font-weight:bold;
}
Note: You don’t have to lay out CSS rules as done in this section; rather, you can add
rules as one long string. However, the formatting shown here is more readable in print.
Note that in the files available for download, the formatting is changed slightly again: the
property/value pairs and closing curly bracket are both tabbed inward, enabling rapid
vertical scanning of a CSS document’s selectors.
Types of CSS selectors
In the previous example, the most basic style of selector was used: an element selector. This defines the
visual appearance of the relevant HTML tag. In the sections that follow, we’ll examine some other regularly
used (and well-supported) CSS selectors: class, ID, grouped, and contextual.
Class selectors
In some cases, you may want to modify an element or a group of elements. For instance, you may want
your general website text to be blue, as in the examples so far, but some portions of it to be red. The
simplest way of doing this is by using a class selector.
In CSS, a class selector’s name is prefixed by a period (.), like this:
.warningText {
color: red;
www.freepdf-books.com
Chapter 1
12
}
This style is applied to HTML elements in any web page the style sheet is attached to using the class
attribute, as follows:
<h2 class="warningText">This heading is red.</h2>
<p class="warningText">This text is red.</p>
<p>This is a paragraph, <span class="warningText">and this text is
red</span>.</p>
If you want a make a class specific to a certain element, place the relevant HTML tag before the period in
the CSS rule:
p.warningText {
color: red;
}
If you used this CSS rule with the HTML elements shown previously, the paragraph’s text would remain
red, but not the heading or span, because of the warningText class now being exclusively tied to the
paragraph selector only.
Usefully, it’s possible to style an element by using multiple class values. This is done by listing multiple
values in the class attribute, separated by spaces:
<p class="warningText hugeText">
The previous example’s content would be styled as per the rules .warningText and .hugeText.
ID selectors
ID selectors can be used only once on each web page. In HTML, you apply a unique identifier to an HTML
element with the id attribute:
<p id="footer">&copy; 200X The Company. All rights reserved.</p>
To style this element in CSS, precede the ID name with a hash mark (#):
p#footer {
padding: 20px;
}
In this case, the footer div would have 20 pixels of padding on all sides.
Essentially, then, classes can be used multiple times on a web page, but IDs cannot. Typically, IDs are
used to define one-off page elements, such as structural divisions, whereas classes are used to define the
style for multiple items.
Grouped selectors
Should you want to set a property value for a number of different selectors, you can use grouped
selectors, which take the form of a comma-separated list:
www.freepdf-books.com
An Introduction to Web Design
13
h1, h2, h3, h4, h5, h6 {
color: green;
}
In the preceding example, all the website’s headings have been set to be green. Note that you’re not
restricted to a single rule for each element—you can use grouped selectors for common definitions and
separate ones for specific property values, as follows:
h1, h2, h3, h4, h5, h6 {
color: green;
}
h1 {
font-size: 1.5em;
}
h2 {
font-size: 1.2em;
}
Note: If you define a property value twice, browsers render your web element depending
on each rule’s position in the cascade. See the section “The cascade” later in the
chapter for more information.
Contextual selectors
This selector type is handy when working with advanced CSS. As the name suggests, contextual selectors
define property values for HTML elements depending on context. Take, for instance, the following
example:
<p>I am a paragraph.</p>
<p>So am I.</p>
<div id="navigation">
<p>I am a paragraph within the navigation div.</p>
<p>Another paragraph within the navigation div.</p>
</div>
You can style the page’s paragraphs as a whole and then define some specific values for those within the
navigation div by using a standard element selector for the former and a contextual selector for the latter:
p {
color: black;
}
#navigation p {
color: blue;
font-weight: bold;
}
www.freepdf-books.com
Chapter 1
14
As shown, syntax for contextual selectors (#navigation p ) is simple—you just separate the individual
selectors with some whitespace. The two rules shown previously have the following result:
The p rule colors the web page’s paragraphs black.
The #navigation p rule overrides the p rule for paragraphs within the navigation div, coloring
them blue and making them bold.
By working with contextual selectors, it’s possible to get very specific with regard to styling things on your
website; we’ll be using these selectors regularly.
Pseudo-selectors
This selector is defined with a colon preceding them. The most recognizable pseudo-selector would be
hover used with links. For example, if you wanted to change a link’s text color when your mouse hovers
over it, you would define the following in your style sheet as follows:
a:hover {
color: black;
}
Pseudo-selectors allow you to style your content dynamically and are incredibly powerful when combined
with contextual and id selectors.
There are multiple different kinds of pseudo-selectors including structural, target, UI element states,
negation, and links.
Attribute selectors
Attribute selectors allow you to target any element based on their attributes. Consider the following code:
<a href="http://www.apress.com">I am a link.</a>
Say you wanted to add the Apress logo before every link to Apress.com. You could update your markup
with a class attribute to allow you to target each Apress link. This would be tedious, and you would have to
remember to do this to every Apress link you add to your site. An easier option would be to use attribute
selectors.
Using an attribute selector, you could target all Apress links and add a logo like the following:
a[href$='apress.com'] {
content: url(logos/apress.png);
}
Note: There are other types of selectors used for specific tasks. These will be covered
as relevant throughout the book.
www.freepdf-books.com
An Introduction to Web Design
15
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">
Alternatively, import the style sheet into the style element:
<style type="text/css" media="screen">
@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">
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 worth doing only 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
www.freepdf-books.com
Chapter 1
16
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.
The cascade
It’s possible to define the rule for a given element multiple times: you can do so in the same style sheet,
and several style sheets can be attached to an HTML document. On top of that, you may be using
embedded style sheets and inline styles. The cascade is a way of dealing with conflicts, and its simple rule
is this:
The value closest to the element in question is the one that is applied.
In the following example, the second font-size setting for paragraphs takes precedence because it’s
closest to paragraphs in the HTML:
p {
font-size: 1.1em;
}
p {
font-size: 1.2em;
}
Subsequently, paragraphs on pages the preceding rule is attached to are rendered at 1.2em. If a similar
rule were placed as an embedded style sheet below the imported/linked style sheet, that rule would take
precedence, and if one were applied as an inline style (directly in the relevant element), then that would
take precedence over all others.
Note that it’s possible to import or link multiple style sheets in a web page’s head section.
The cascade principle still applies; in other words, any rules in a second attached style
sheet override those in the one preceding it.
CSS uses the concept of inheritance. A document’s HTML elements form a strict hierarchy, beginning with
html, and then branching into head and body, each of which has numerous descendant elements (such as
title and meta for head, and p and img for body). When a style is applied to an element, its descendants—
those elements nested within it—often take on CSS property values, unless a more specific style has been
applied. However, not all CSS style properties are inherited. See the CSS reference section of this book
for more details.
The CSS box model explained
The box model is something every designer working with CSS needs a full understanding of in order to
know how elements interact with each other and also how various properties affect an element.
Essentially, each element in CSS is surrounded by a box whose dimensions are automated depending on
the content. By using width and height properties in CSS, these dimensions can be defined in a specific
manner.
www.freepdf-books.com
An Introduction to Web Design
17
You can set padding to surround the content and add a border and margins to the box. A background
image and background color can also be defined. Any background image or color is visible behind the
content and padding but not the margin. The effective space an element takes up is the sum of the box
dimensions (which effectively define the available dimensions for the box’s contents), padding, border, and
margins. Therefore, a 500-pixel-wide box with 20 pixels of padding at each side and a 5-pixel border will
actually take up 550 pixels of horizontal space (5 + 20 + 500 + 20 + 5).
Note that in some cases, margins between two elements “collapse,” leading to only the
larger margin value being used.
© Jon Hicks (www.hicksdesign.co.uk)
Creating boilerplates
Every web page looks different, just as every book or magazine is different from every other one.
However, under the hood there are often many similarities between sites, and if you author several, you’ll
soon note that you’re doing the same things again and again. You can find many ready-made boilerplates
online. One of the most popular ones is the HTML5 Boilerplate (html5boilerplate.com). This is a great
starting point for any project you want to start. It includes many of the techniques discussed throughout
www.freepdf-books.com
Chapter 1
18
this book such as cross-browser compatibility, mobile browser optimizations, progressive enhancement
and graceful degradation, and more.
While the HTML5 Boilerplate is a great place to start, it is important to learn how to create your own
boilerplates from scratch—starting points for all of your projects.
In the download files, available from the Downloads section of the friends of Apress website
(www.apress.com), there are two boilerplates folders: basic-boilerplates and advanced-boilerplates. In
basic-boiler plates , the basic.html web page is a blank HTML5 document, and in advanced-
boilerplates, extended.html adds some handy structural elements that provide a basic page structure
that’s common in many web pages, along with some additions to the head section. (The former is used as
a quick starting point for many of the tutorials in this book. The latter is perhaps a better starting point for a
full website project.) The CSS-with-ToC.css document in advanced-boilerplates uses CSS comments to
create sections in the document to house related CSS rules. This is handy when you consider that a CSS
document may eventually have dozens of rules in it—this makes it easier for you to be able to find them
quickly.
CSS comments look like this: /* this is a comment */ . They can be single-line or multiple-line. In the
advanced CSS boilerplate, a multiline comment is used for an introduction and table of contents:
/*
STYLE SHEET FOR [WEB SITE]
Created by [AUTHOR NAME]
[URL OF AUTHOR]
ToC
1. defaults
2. structure
3. links and navigation
4. fonts
5. images
Notes
*/
Each section of the document is then headed by a lengthy comment that makes it obvious when a section
has begun:
/* --------- 1. defaults --------- */
* {
margin: 0;
padding: 0;
}
body {
}
www.freepdf-books.com
An Introduction to Web Design
19
As you can see, property/value pairs and the closing curly bracket are indented by two tabs in the
document (represented by two spaces on this page), which makes it easier to scan vertically through
numerous selectors. (Note that for the bulk of this book, the rules aren’t formatted in this way, because
indenting only the property/value pairs differentiates them more clearly in print; however, the download
files all have CSS rules indented as per the recommendations within this section.) Comments can also be
used for subheadings, which I tend to indent by one tab:
/* float-clearing rules */
.separator {
clear: both;
}
Although the bulk of the style sheet’s rules are empty, just having a boilerplate to work from saves plenty
of time in the long run, ensuring you don’t have to key in the same defaults time and time again. Use the
one from the download files as the basis for your own, but if you regularly use other elements on a page
(such as pull quotes), be sure to add those, too; after all, it’s quicker to amend a few existing rules to
restyle them than it is to key them in from scratch.
Tip: Along the same lines as boilerplates, you can save time by creating a snippets
folder on your hard drive. Use it to store snippets of code—HTML elements, CSS rules,
and so on—that you can reuse on various websites. Many applications have this
functionality built in, so make use of it if your preferred application does.
To show you the power of CSS, we’re going to work through a brief exercise using the boilerplates
mentioned earlier. Don’t worry about understanding everything just yet, because all of the various
properties and values shown will be explained later in the book.
Creating, styling, and restyling a web page
Required files basic.html and CSS-default.css from the basic-boilerplates folder
What you’ll learnHow to create, style, and restyle a web page
Completed files creating-and-styling-a-web-page.html, creating-and-styling-a-web-page.css,
creating-and-styling-a-web-page-2.html, and creating-and-styling-a-web-page-2.css,
in the chapter 1 folder
1. Copy basic.html and CSS-default.css to your hard drive and rename them creating-and-styling-a-
web-page.html and creating-and-styling-a-web-page.css.
2. Attach the style sheet. Type Creating and styling a web page in the title element to give the page
a title, and then amend the @import value so that the style sheet is imported:
<link rel="stylesheet" href="creating-and-styling-a-web-page.css">
3. Add some content. Within the wrapper div, add some basic page content, as shown in the
following code block. Note how the heading, paragraph, and quote are marked up using a
www.freepdf-books.com
Chapter 1
20
heading element (<h1></h1>), paragraph element (<p></p>), and block quote element
(<blockquote></blockquote>), rather than using styled paragraphs for all of the text-based
content. This is semantic markup, as discussed briefly earlier in the chapter.
<div id="wrapper">
<h1>A heading</h1>
<p>A paragraph of text, which is very exciting&mdash;something
that will live on through the generations.</p>
<blockquote>
<p>&ldquo;A quote about something, to make
people go "hmmmm" in a thoughtful manner.&rdquo;</p>
<cite>An inspirational book title.</cite>
</blockquote>
<p>Another paragraph, with equally exciting text; in fact, it&rsquo;s
so exciting, we're not sure it&rsquo;s legal to print.</p>
</div>
Note: The items with ampersands and semicolons, such as &mdash; and &rdquo;, are
HTML entities—see Appendix C for more details.
4. Edit some CSS. Save and close the web page and then open the CSS document. Amend the
body rule within the defaults section of the CSS. This ensures the text on the page is colored
black and that the page’s background color is white. The padding value ensures the page content
doesn’t hug the browser window edges.
body {
font: 62.5%/1.5 Verdana, Arial, Helvetica, sans-serif;
color: #000000;
background: #ffffff;
padding: 20px;
}
5. Style the wrapper. Add the following property values to the #wrapper rule to define a fixed width
for it and then center it (via the margin property’s auto value).
#wrapper {
font-size: 1.2em;
line-height: 1.5em;
margin: 0 auto;
width: 500px;
}
6. Style the text. Add the h1 rule as shown, thereby styling the level-one heading:
h1 {
font: 1.5em/1.8em Arial, sans-serif;
text-transform: uppercase;
}
www.freepdf-books.com
An Introduction to Web Design
21
7. Add the blockquote and blockquote p rules as shown. The former adds margins to the sides of
the block quote, thereby making the text stand out more, while the latter (a contextual selector)
styles paragraphs within block quotes only, making them italic and larger than standard
paragraphs. Once you’ve done this, save your files and preview the web page in a web browser;
it should look like the following image. (Don’t close the browser at this point.)
blockquote {
margin: 0 100px;
}
blockquote p {
font-style: italic;
font-size: 1.2em;
}
8. Duplicate creating-and-styling-a-web-page.css and rename it creating-and-styling-a-web-page-
2.css. Open creating-and-styling-a-web-page.html, and amend the link value, linking to the newly
created CSS document:
<link rel="stylesheet" href="creating-and-styling-a-web-page-2.css">
9. Open creating-and-styling-a-web-page-2.css, and switch the values of color and background in
the first body rule.
body {
font: 62.5%/1.5 Verdana, Arial, Helvetica, sans-serif;
color: #ffffff;
background: #000000;
padding: 20px;
}
10. Replace the text-transform property/value pair from the h1 rule with color: #bbbbbb;. For the
blockquote rule, make the following amendments, which add a border to the left and right edges,
and some horizontal padding around the block quote’s contents.
blockquote {
margin: 0 100px;
border-left: 3px solid #888888;
border-right: 3px solid #888888;
padding: 0 20px;
}
www.freepdf-books.com
Chapter 1
22
11. Finally, amend the blockquote p rule as shown:
blockquote p {
font-weight: bold;
font-size: 1.0em;
}
Refresh the web page in the browser, and you should see it immediately change, looking like that shown in
the following image. Effectively, nothing in the web page was changed (you could have overwritten the
rules in creating-and-styling-a-web-page.css rather than creating a duplicate style sheet); instead, the
web page’s design was updated purely by using CSS. (Note that in the download files, there are two sets
of documents for this exercise—one with the design as per step 7, and the other as per step 11, the latter
of which has the -2 suffix added to the HTML and CSS document file names.)
Although this was a very basic example, the same principle works with all CSS-based design. Create a
layout in CSS and chances are that when you come to redesign it, you may not have to change much—or
any—of the underlying code. A great example of this idea taken to extremes is css Media Queries
(www.mediaqueri.es), whose single web page is radically restyled via dozens of submitted CSS
documents.
www.freepdf-books.com
An Introduction to Web Design
23
Working with website content
Before we explore how to create the various aspects of a web page, we’re going to briefly discuss working
with website content and what you need to consider prior to creating your site. Technology and design
aren’t the only factors that affect the success of a website. The human element must also be considered.
Most of the time, people use the Web to get information of some sort, whether for research purposes or
entertainment. Typically, people want to be able to access this information quickly; therefore, a site must
be structured in a logical manner. It’s imperative that a visitor doesn’t spend a great deal of time looking for
information that should be easy to find. Remember, there are millions of sites out there, and if yours isn’t
up to scratch, it’s easy for someone to go elsewhere.
Note: There are exceptions to the general rule of a website having a structured and
logical design—notably sites that are experimental in nature or the equivalent of online
art, thereby requiring exploration. In these cases, it may actually be detrimental to
present a straightforward and totally logical site, but these cases are strictly a minority.
www.freepdf-books.com
Chapter 1
24
In this section, we’ll look specifically at information architecture and site maps, page layout, design
limitations, and usability.
Information architecture and site maps
Before you begin designing a website, you need to collate and logically organize the information it’s going
to contain. A site map usually forms the basis of a site’s navigation, and you should aim to have the most
important links immediately visible. What these links actually are depends on the nature of your website,
but it’s safe to say that prominent links to contact details are a common requirement across all sites. A
corporate website may also need prominent links to products, services, and a press area. The resulting
site map for a corporate site might resemble the following illustration.
Here, the boxed links serve as the primary navigation and are effectively sections of the website.
Underneath each boxed link is a list of subcategories or pages housed within that section. With this
structure, it’s easy for a newcomer to the site to work out where information is located. When working on
site maps, try talking to people who might be interested in the site to get their reaction to your organization
of the content. When working for a client, ensure that they sign off on the site map and that you get
feedback on the site map from people at all levels in the company and, if possible, from the company’s
customers. In all cases, seek the opinions of both the technically minded and the relative computer
novices, because each may have different ideas about how information should be structured. After all,
most web designers are technically minded (or at least well versed in using a computer), and they often
forget that most people don’t use the Web as regularly as they do. In other words, what seems obvious to
you might not be to the general public.
For larger sites, or those with many categories, site maps can be complex. You may have to create
several versions before your site map is acceptable. Always avoid burying content too deep. If you end up
with a structure in which a visitor has to click several times to access information, it may be worth
reworking your site’s structure.
Basic web page structure and layout
Once you’ve sorted out the site map, avoid firing up your graphics package. It’s a good idea to sketch out
page layout ideas on paper before working on your PC or Mac. Not only is this quicker than using graphics
software, but it also allows you to compare many ideas side by side. At this stage, you shouldn’t be too
www.freepdf-books.com
An Introduction to Web Design
25
precious about the design—work quickly and try to get down as many ideas as possible. From there, you
can then refine your ideas, combine the most successful elements of each, and then begin working on the
computer.
Although the Web has no hard-and-fast conventions, themes run throughout successful websites, many of
which are evident in the following image of a version of my Snub Communications homepage.
www.freepdf-books.com
Chapter 1
26
A website’s navigation should be immediately accessible—you should never have to scroll to get to it. It’s
also a good idea to have a masthead area that displays the organization’s corporate brand (or, if it’s a
personal site, whatever logo/identity you want to be remembered by, even if it’s only a URL).
The homepage should include an introduction of some sort that briefly explains what the site is about, and
it should have some pull-ins to other areas of the site. These pull-ins could be in the form of news items
that link to recent product launches, completed projects, and so on.
Most websites require a method for people to contact the site owner, and at least one clear link to a
contact page is essential.
Avoid constantly changing the design throughout the site. In print, this sometimes works well and provides
variation within a book or magazine. Online, people expect certain things to be in certain places.
Constantly changing the position of your navigation, the links themselves, and even the general design
and color scheme often creates the impression of an unprofessional site and makes it harder to use.
Ultimately, however your site ends up, and whatever your design, you need to ensure your creation is as
usable as possible. A good checklist—even if the points may seem entirely obvious—is as follows:
Is the site easy to navigate?
Is it easy for users to locate content on each page?
Is it easy for users to find what they need on the site?
Are download times kept to a minimum?
Is the site suitable and relevant for its target audience?
Does the site use familiar conventions?
If you can answer yes to all these things, then you should be on the right track!
www.freepdf-books.com
An Introduction to Web Design
27
Note: Regarding conventions, it’s important not to go overboard. For example, some
web gurus are adamant that default link colors should always be used. I think that’s
sweet and quaint but somewhat archaic. As long as links are easy to differentiate from
other text and styled consistently throughout the site, that’s what matters.
Limitations of web design
Depending on your viewpoint, the inherent limitations of the Web are either a challenge or a frustration.
Print designers often feel the latter and consider themselves hampered by the Web when compared to the
relative freedom of print design. While print designers define the material their designs are displayed on,
the Web comes in all shapes and sizes, from the tiny screen of a mobile phone to large, 1080p high-
resolution displays. A web designer must consider each display resolution their site might be viewed on
and also remember that browsers have different levels of support and implementations of HTML
standards.
Columns take on a different role online compared to in print, because they’re primarily used to display
several areas of content with the same level of prominence. You don’t use columns online to display
continuous copy, unless you use just one column. If you use several columns, the visitor has to constantly
scroll up and down to read everything.
There are other limitations when it comes to rendering text online. There are few web standard fonts
(detailed in Chapter 3); serifs, which work well on paper, don’t work so well online, and reading text on-
screen is already harder than reading print, so complex page backgrounds should be avoided. HTML5
provides the ability to embed fonts into your page, but this again has its own set of limitations; browser
providers implement this each using a different format and you must make considerations for older
browsers and mobile browsers that do not support this powerful feature.
And then there are issues like not knowing what an end user’s setup is and therefore having to consider
monitor resolution and color settings, what browser is being used, and even the various potential setups of
web browsers, not to mention mobile web browsers that offer their own set of limitations. Do you go for a
liquid design, which stretches with the browser window; a fixed design, which is flanked by blank space at
larger monitor resolutions; or a responsive design, which adapts to the available screen dimensions?
Don’t worry, this isn’t a pop quiz. These are questions that will be answered in this book, but I mention
them now to get you thinking and realizing that planning is key with regard to web design. Because this is
largely a book about concepts, ideas, and techniques, we won’t return to talk about planning very much,
which is why I’m drumming it in at this early stage.
www.freepdf-books.com
Chapter 1
28
Also, don’t get disheartened by the previous limitations spiel. The Web is a truly magnificent medium, and
for every downside there’s something amazing to counter it. So what if the resolution is low? Nowhere else
can you so effortlessly combine photography, video, sound, and text. Sure, it’s all well and good to read a
magazine, but the Web enables interaction, and navigation can be nonlinear, enabling you to link words
within specific pieces to other articles on your website or elsewhere on the Internet. Don’t get me wrong:
the Web is a great thing. If it weren’t, I wouldn’t be interested in it, wouldn’t be designing for it, and wouldn’t
be writing this book.
www.freepdf-books.com
29
Chapter 2
Web Page Essentials
www.freepdf-books.com
Chapter 2
30
In this chapter:
Creating HTML5 documents
Understanding document type definitions
Using meta tags
Attaching external documents
Working with the body section
Using CSS for web page backgrounds
Commenting your work
Starting with the essentials
You might wonder what’s meant by this chapter’s title: web page essentials. This chapter will run through
everything you need to do with a web page prior to working on the layout and content, including creating
the initial documents, attaching external documents to HTML files, and dealing with the head section of the
web page. Little of this is a thrill with regard to visual design, which is why many designers ignore the
topics we’ll cover or stick their fingers in their ears, hum loudly, and wish it would all go away (and then
probably get rather odd looks from nearby colleagues). However, as the chapter’s title states, everything
we’ll be talking about is essential for any quality web page, even if you don’t see exciting things happening
visually.
This chapter also explores web page backgrounds, which, although they should be used sparingly and
with caution, often come in handy. It’s worth bearing in mind that some aspects discussed here will crop up
later in the book. For example, CSS techniques used to attach backgrounds to a web page can be used to
attach a background to any web page element (be that a div, table, heading, or paragraph). But before we
get into any CSS shenanigans, we’ll put our CSS cheerleading team on hold and look at how to properly
construct an (X)HTML document.
HTML vs. XHTML
The HTML5 specification defines an abstract language for describing documents and applications and
defines some APIs for interacting with what is known as the DOM HTML (or “the DOM” for short). There
are various concrete syntaxes for this language, and two are HTML and XHTML
HTML (or HTML5) is the format suggested for most authors. It is compatible with most legacy web
browsers. If a document is transmitted with an HTML MIME type, such as text/html, then it will be
processed as an HTML document by web browsers.
XHTML (or XHTML5) is an application of XML. When a document is transmitted with an XML MIME type,
such as application/xhtml+xml, then it is treated as an XML document by web browsers, to be parsed by
an XML processor. Authors are reminded that the processing for XML and HTML differs; in particular, even
www.freepdf-books.com
Web Page Essentials
31
minor syntax errors will prevent a document labeled as XML from being rendered fully, whereas they
would be ignored in the HTML syntax.
Essentially, an XHTML5 page is a simple HTML5 document that has the following:
HTML doctype/namespace: The <!DOCTYPE html> definition is optional, but it would be useful
for preventing browser quirks mode.
XHTML well-formed syntax:
XML MIME type: application/xhtml+xml. This MIME declaration is not visible in the source
code, but it would appear in the HTTP Content-Type header that could be configured on the
server.
Default XHTML namespace: <html xmlns="http://www.w3.org/1999/xhtml">.
It has been argued that the strict coding requirements of XHTML identify the structure of a document more
clearly than HTML. In HTML, a browser assumes the location of a missing end tag to be the start tag of the
next block element. In the example, <br /> is rendered after the paragraph in the XHTML document and as
part of the paragraph in the HTML document.
It is recommended to use HTML and not XHTML, especially for beginners since the syntax can be more
forgiving. Note that some server-side technologies might still favor XHTML output.
Document defaults
Both in HTML5 and in XHTML5, a blank document looks like the following code:
<!DOCTYPE html >
<html lang="en">
<head>
<title></title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
</head>
<body>
</body>
</html>
There are other character sets in use, too, for the likes of Hebrew, Nordic, and Eastern
European languages, and if you’re using them, the charset value would be changed accordingly.
Although www.iana.org/assignments/character-sets provides a thorough character set listing and
www.czyborra.com/charsets/iso8859.html contains useful character set diagrams, it’s tricky to wade
through it all, so listed here are some common values and their associated languages:
ISO-8859-1 (Latin1): Western European and American, including Afrikaans, Albanian, Basque,
Catalan, Danish, Dutch, English, Faeroese, Finnish, French, Galician, German, Icelandic, Irish,
Italian, Norwegian, Portuguese, Spanish, and Swedish.
ISO-8859-2 (Latin2): Central and Eastern European, including Croatian, Czech, Hungarian, Polish,
Romanian, Serbian, Slovak, and Slovene.
www.freepdf-books.com
Chapter 2
32
ISO-8859-3 (Latin3): Southern European, including Esperanto, Galician, Maltese, and Turkish.
(See also ISO-8859-9.)
ISO-8859-4 (Latin4): Northern European, including Estonian, Greenlandic, Lappish, Latvian, and
Lithuanian. (See also ISO-8859-6.)
ISO-8859-5: Cyrillic, including Bulgarian, Byelorussian, Macedonian, Russian, Serbian, and
Ukrainian.
ISO-8859-6: Arabic.
ISO-8859-7: Modern Greek.
ISO-8859-8: Hebrew.
ISO-8859-9 (Latin5): European. Replaces Icelandic-specific characters with Turkish ones.
ISO-8859-10 (Latin6): Nordic, including Icelandic, Inuit, and Lappish.
For an overview of the ISO-8859 standard, see http://en.wikipedia.org/wiki/ISO_8859.
DOCTYPE declarations explained
The <!DOCTYPE> prolog identifies the type and version of HTML or XHTML in which the document is
coded. In technical terms, <!DOCTYPE> specifies the type of document and the DTD that validates the
document. The W3C provides a free online service at http://validator.w3.org/ that you can use to validate
your documents.
All HTML and XHTML code should be validated. This verifies the code contains no coding errors. If there
are errors, CSS selectors may fail to select elements as expected or may even select elements
unexpectedly.
There are benefits to using XHTML. Validated XHTML documents are well-formed and have unambiguous
structure. You can also use Extensible Stylesheet Language (XSLT) and XML Query Language (XQuery)
processors to extract content and rearrange documents.
In the HTML4 era, there were two additional varieties of DOCTYPEs: strict and transitional. Strict
removes all presentational elements and attributes, and transitional allows them. We do not recommend
presentation elements and attributes, but the strict DOCTYPE may be too strict for some needs. For
example, it prohibits the start attribute in ol and the value attribute in li, which are the only available means
to control the numbering of an ordered list. The XHTML strict DOCTYPE also prohibits iframe.
The head section
The head section of a web page contains metadata content that sets up the presentation or behavior of the
rest of the content, that sets up the relationship of the document with other documents, or that conveys
other “out-of-band” information.
www.freepdf-books.com
Web Page Essentials
33
Page titles
Many designers are so keen to get pages online that they forget to provide a title for each page. Titles are
added using the title element, as follows:
<title>Pro HTML5 and CSS3 Design</title>
The title is usually shown at the top of the browser window (and sometimes within the active tab, if
you’re using a browser that has a tabbed interface); the results of the previous code block are shown
in the following image.
By default, web design software (for example, Adobe Dreamweaver) usually does one of the following
things with regard to the title element:
Adds no content
Sets the title element’s content as “Untitled Document”
Sets the title element’s content as the application’s name
The first of these results in no title being displayed for the web page and is invalid XHTML, while the
second means your page joins the legions online that have no title. The third option is just as bad: using
your web page to advertise the application you used to create it. Therefore, add a title to every web page
you create; in fact, make it one of the first things you do so you don’t forget.
With regard to the content of your web page titles, bear in mind that this is often the most prominent thing
returned in search engine results pages. Keep titles clear, concise, and utterly to the point. Use too many
words, and the title will be clipped; use too few (or try to get arty with characters), and you may end up with
something that stumps search engines and potential visitors, too.
Generally speaking, for the homepage at least, it’s good to include the name of the site or organization,
followed by an indication of the site’s reason for existence (and author or location, if relevant). For
www.freepdf-books.com
Chapter 2
34
instance, as shown in the following image, the InfoQ title includes the organization’s name, followed by its
mission statement.
Some designers use the same title throughout their site. This is a bad idea—web page titles are used as
visual indicators by visitors trawling bookmarks or their browser’s history. This is why some tend to use
titles as a breadcrumb navigation of sorts, showing where a page sits within the website’s hierarchy, like
this:
<title>Company name - Services - Service name</title>
meta tags and search engines
The Web was once awash with tips for tweaking meta tags. This was because although these tags are
primarily there to provide information about the document, they were initially what most search engines
used to categorize web pages and return results. It didn’t take long for the shortfalls in the system to
become apparent and for designers to abuse them, so many meta tags are today considered redundant.
Generally, search engines now trawl the content of the web page (including the contents of the title
element), trying to match a user’s search with the most important content on the page. This is why strong
use of semantic markup is essential—by correctly utilizing headings, paragraphs, and other structural
elements for text and by avoiding overuse of images for text content, modern search engines get a better
handle on your content and can therefore, in theory, return more accurate results to users.
Tagging and other forms of metadata are also becoming an increasingly popular search engine aid, for
both internal search engines—those within the site itself—and for the search engines that return results
from the whole of the Internet. Both are a means of adding information to a website to aid users. Visual
tags may show a number of keywords associated with a blog posting, for example, enabling a user to see
whether something interests them by the size of the word; search engines will latch onto the keywords and
the content of the piece itself. Metadata enables you to “embed” information in the page, aiding all manner
of devices and potentially creating networks and links to like information. A form of metadata—
microformats—is explored in Chapter 8.
Despite this, it’s still worth being mindful of meta tags when creating web pages, for those search engines
that still make use of them—just be aware that they’re not nearly as important as they once were (with the
possible exception of description).
Keywords and descriptions
Unless you’re totally new to web design, it’s likely you’ll be aware of the keywords and description meta
tags:
www.freepdf-books.com
Web Page Essentials
35
<meta name="keywords" content="keywords, separated, by, commas" />
<meta name="description" content="A short description about the Web
site" />
The first of these tags, keywords, should contain a set of comma-separated tokens, each of which is a
keyword relevant to the page that users might type into a search engine to find your site. Because of
abuse (websites including thousands of words in the meta tag content in order to try to create a catchall in
search engine results pages), such lists are rarely used these days. Instead, search engines tend to look
at the entire content of a page to determine its relevance to someone’s search. If you choose to include
this element in your web page, 30 or fewer words and short phrases are sufficient.
The contents of the description’s content attribute are returned by some search engines in a results page
along with the web page’s title. As with the title, keep things succinct; otherwise, the description will be
cropped. Most search engines display a maximum of 200 characters, so 25 well-chosen words are just
about all you can afford.
revisit-after, robots, and author
Other meta tags also use name and content attributes. These tags assist search engines. In the following
example, the first tag provides an indication of how often they should return (useful for regularly updated
sites), and the second tag states whether the page should be indexed.
<meta name="Revisit-After" content="30 Days" />
<meta name="robots" content="all,index" />
The content attribute of the robots meta tag can instead include the values noindex and none, in order to
block indexing, and follow or nofollow, depending on whether you want search engine robots to follow
links from the current page.
The author meta tag is of less use to search engines and typically includes the page author’s name and
home URL. Designers sometimes use it as a means to declare the author’s name and details, but it has
little use beyond that.
Attaching external documents
A web page—as in the (X)HTML document—is primarily designed to contain content that is structured in
markup. Presentation should be dealt with via external CSS documents, and behavior should be dealt with
via external scripting documents. Although it is possible to work with the likes of JavaScript and CSS within
an HTML document, this goes against the modular nature of good web design. It’s far easier to create,
edit, and maintain a site if you work with separate files for each technology. (The exception is if your “site”
is only a single page, therefore making it sensible to include everything in a single document.)
As already mentioned, HTML documents are text files that are saved with the suffix .html (or .htm). CSS
and JavaScript files are also text documents, and their file suffixes are .css and .js, respectively. When
you start a project, having already set the relevant DOCTYPE and added meta tags, it’s a good idea to create
blank CSS and JavaScript files and to attach them to your web page so you can then work on any element
as you wish.
www.freepdf-books.com
Chapter 2
36
Attaching external CSS files: the link method
In the previous chapter, you were shown how to attach CSS to a web page (see the section “Adding styles
to a web page” in Chapter 1); we’ll briefly recap the process here. There are two methods of attaching an
external CSS file: the link method and the @import method.
The link tag specifies a relationship between the linked document and the document it’s being linked to.
In the context of attaching a CSS file, it looks something like this:
<link rel="stylesheet" href="stylesheet.css" />
Possible attributes include the following:
rel: Defines the relation from the parent document to the target
href: The location of the target file
type: The MIME type of the target document
media: The target medium of the target document
The title attribute is also occasionally used with the link element, either to provide additional
information or to be used as a “hook” for the likes of a style sheet switcher (see
www.alistapart.com/stories/alternate/ for more information). Any style sheet lacking a title attribute
(and a rel value of style sheet) is persistent—always affecting a document. These are by far the most
common types of style sheets. A preferred style sheet also takes a title along with the rel attribute, and
only one such style sheet can be used at a time—typically the first, with subsequent ones ignored. On
pages that offer alternate style sheets (typically via a style switcher), the persistent styles are always used,
and the first preferred is the additional default; the preferred styles, however, can be swapped out by
selecting an alternative style sheet. (Note that in Firefox, you should avoid adding a title attribute to any
style sheet for print, because otherwise the content may not print.)
In the previous example, the media attribute is set to all, specifying that this style sheet is intended for all
devices. But it’s feasible to attach multiple style sheets to a web page and set the media attribute of each
one to a different type. For instance, in the following example, two CSS files are attached, one for screen
and the other for printed output:
<link rel="stylesheet" href="stylesheet.css" type="text/css"
media="screen" />
<link rel="stylesheet" href="printcss.css" type="text/css"
media="print" />
There are other media types, including aural, braille, projection, and tv, but few are supported well.
However, in Chapter 10, we’ll look at style sheets for print, which is one of the alternatives to screen that is
supported reasonably well in mainstream browsers.
Attaching CSS files: the @import method
A problem with the link method in the past was that obsolete browsers saw the style sheet but didn’t
understand it. This could result in garbled layouts—and often in unusable websites for those unfortunate
www.freepdf-books.com
Web Page Essentials
37
enough to have to deal with such arcane web browsers. The solution was to hide the CSS from such
browsers by using a command that they don’t understand and so would ignore. This was often referred to
as the @import method.
As shown in the following example, the style element is used to do this:
<style type="text/css" media="all">
@import url(stylesheet.css);
</style>
It is recommended to avoid using the @import method, especially since it might lead to
performance issues in high-traffic sites (http://www.stevesouders.com/blog/2009/04/09/dont-use-import/
www.stevesouders.com/blog/2009/04/09/dont-use-import/) and with mobile users.
The CSS specifications permit the use of the style sheet location as a quoted string
instead of enclosing it in url(). The method shown here is more commonly supported,
though.
Attaching CSS files: media queries
CSS has long supported media-dependent style sheets tailored for different media types. For example, a
document may use sans-serif fonts when displayed on a screen and serif fonts when printed. screen and
print are two media types that have been defined.
In the old days of HTML4, this could be written as follows:
<link rel="stylesheet" type="text/css" media="screen" href="sans-serif.css">
<link rel="stylesheet" type="text/css" media="print" href="serif.css">
With CSS3, media queries extend the functionality of media types by allowing more precise labeling of
style sheets. A media query consists of a media type and zero or more expressions that check for the
conditions of particular media features. By using media queries, presentations can be tailored to a specific
range of output devices without changing the content itself. A media query is a logical expression that is
either true or false. A media query is true if the media type of the media query matches the media type of
the device where the user agent is running, and all expressions in the media query are true.
Here are a few examples:
<--! Devices of a certain media type (‘screen’) with certain feature (it must be a color
screen)-->
<link rel="stylesheet" media="screen and (color)" href="example.css" />
<!-- The same media query written in an @import-rule in CSS -->
@import url(color.css) screen and (color);
A shorthand syntax is offered for media queries that apply to all media types; the keyword all can be left
out (along with the trailing and). In other words, the following are identical:
@media (orientation: portrait) { … }
@media all and (orientation: portrait) { … }
www.freepdf-books.com
Chapter 2
38
This way, designers and developers can create more complex queries that map their specific needs, like
this one:
@media all and (max-width: 698px) and (min-width: 520px), (min-width: 1150px) {
body {
background: #ccc;
}
}
There is a long list of media features that includes the following:
width and device-width
height and device-height
orientation
aspect-ratio and device-aspect-ratio
color and color-index
monochrome (if not a monochrome device, equals 0)
resolution
scan (describes the scanning process of output devices set to tv)
grid (specifies whether the output device is grid or bitmap)
Attaching favicons and JavaScript
Favicons are those little icons you often see in your browser’s address bar. They are attached using the
link method discussed earlier, although you need to include only three attributes: rel, href, and type. The
type value can change depending on the file type of your favicon. For example, image/png is fine if you’ve
used a PNG.
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon"/>
These days, favicons are almost ubiquitous, and they provide users with an additional visual clue to a
site’s identity. Although not particularly useful on their own, they can be handy when trawling through a
large bookmarks list—you can look for the icon rather than the text. However, don’t rely on them instead of
a good web page title—they should merely be an additional tool in your arsenal. By default web browsers
will search for a favicon.ico file in the root of a site, even if there is no link tag present.
Attaching a JavaScript file to a web page is similarly painless. You do so via the script element, as
follows:
<script src="javascriptfile.js"></script>
JavaScript can be dynamically loaded in a page using a variety of techniques that are
used in libraries called script loaders. These libraries bring performance improvements,
such as nonblocking loading, but are beyond the scope of this book.
www.freepdf-books.com
Web Page Essentials
39
Checking paths
When working with external files, ensure paths between files are complete and don’t become broken as
files are moved around; otherwise, your web page may lose track of the CSS and JavaScript, affecting its
display and functionality. If you’re using document-relative links (that is, links relative to the current
document), remember to amend paths accordingly.
Here are a few examples of paths:
Path Type What it means
myfile.css Relative path. Look for the file in the same
folder as the file that imports it.
/script/myscript.js Relative path. Look for the file in the folder
scripts, which is in the same
root folder as the file that
imports it.
http://www.mysite.com/style.css Absolute path. Look for the file in this location.
/css/style.css Absolute path. Look for the file in the folder
css, which is right under the
root of the website.
The body section
The body element is used to define the body of a web page, and it contains the document’s content.
Technically the body tag is optional in HTML5 because HTML5 doesn’t require the html, head, and body
tags (browsers add them if missing). It is generally good practice to use the body element and avoid
having content placed outside of it.
Although the body element has a number of possible attributes that can be included in its start tag, mostly
for defining ids and classes, they should be avoided. This is because such things should be dealt with
using CSS, which enables you to define values on a sitewide basis, rather than having to do so for each
page.
Content margins and padding in CSS
Page margins and padding are easy to define using CSS. By setting these values once in an external file,
you can update settings sitewide by uploading an amended style sheet rather than every single page on
your site that has an amended body tag.
Furthermore, in terms of page weight, CSS is more efficient. If using old methods, to cater for all browsers,
you set the following body attributes:
<body marginwidth="0" marginheight="0" topmargin="0" leftmargin="0"
bottommargin="0" rightmargin="0">
www.freepdf-books.com
Chapter 2
40
The equivalent in CSS is the following:
body {
margin: 0;
padding: 0;
}
If a CSS setting is 0, there’s no need to state a unit such as px or em.
The reason both margin and padding are set to 0 is because some browsers define a default padding
value. Therefore, even if you set all body margins to 0, there would still be a gap around your page content.
Setting both the margin and padding to 0 in the body rule ensures that all browsers display your content
with no gaps around it.
Zeroing margins and padding on all elements
Although the previous block of code is clean and efficient, it isn’t something we use in our websites. The
reason for this is that browsers place default (and sometimes varying) margins around various elements
other than the page’s body, too. Therefore, our CSS boilerplates always include the following:
* {
margin: 0;
padding: 0;
}
The selector * is the universal selector, and the declaration therefore applies to all elements on the web
page. In other words, add this rule to your CSS, and all default margins and padding for all elements are
removed, enabling you to start from scratch in all browsers and define explicit values for those elements
that need them.
Another way to makes browsers render all elements more consistently and in line with modern
standards is to use a CSS reset kit. Some of the more popular ones are Eric
Meyer's (http://meyerweb.com/eric/tools/css/reset/) and Yahoo’s YUI 2 CSS Reset
(http://developer.yahoo.com/yui/reset/). The goal of a reset style sheet is to reduce browser
inconsistencies in things such as default line heights, margins and font sizes of headings, and so on.
An alternative to reset.css is normalize.css (http://necolas.github.com/normalize.css/), which normalizes
styles for a wide range of HTML elements and corrects bugs and common browser inconsistencies. Users
can just you the full normalize.css file or customize it to suit their needs.
Working with CSS shorthand for boxes
Both of the previous two code examples use CSS shorthand, and this is something that is useful to get to
grips with in order to create the most efficient and easy-to-update CSS. The previous example showed
how to set all margins and padding values to 0, and this was done in shorthand instead of writing out every
single value. How CSS shorthand works for boxes is like this:
A single value (margin: 10px;): This is applied to all edges.
www.freepdf-books.com
Web Page Essentials
41
Two values (margin: 10px 20px;): The first setting (10px) is applied to the top and bottom edges.
The second setting (20px) is applied to both the left and right edges (20px each, not in total).
Three values (margin: 10px 20px 30px; ): The first setting (10px) is applied to the top edge. The
second setting (20px) is applied to both the left and right edges. The third setting (30px) is applied
to the bottom edge.
Four settings (margin: 10px 20px 30px 40px; ): Settings are applied clockwise from the top (in
other words, top: 10px; right: 20px; bottom: 30px; left: 40px).
Shorthand’s benefits become obvious when comparing CSS shorthand with the equivalent properties and
values written out in full. For instance, the following shorthand:
#box {
margin: 0;
padding: 0 100px;
}
looks like this when written out in full:
#box {
margin-top: 0;
margin-right: 0;
margin-bottom: 0;
margin-left: 0;
padding-top: 0;
padding-right: 100px;
padding-bottom: 0;
padding-left: 100px;
}
Whether you use shorthand is up to you. Some designers swear by it and others because of it. Some web
design applications have options to “force” shorthand or avoid it entirely. We reckon it’s a good thing: CSS
documents are usually more logical and shorter because of shorthand. But if you don’t agree, feel free to
keep on defining margins and padding as relevant for every edge of every element.
Setting a default font and font color
As mentioned earlier, the body start tag was historically used to house attributes for dealing with default
text and background colors, link colors, and background images. In CSS, link styles are dealt with
separately (see Chapter 5). We’ll look at how to apply backgrounds later in this chapter.
At this point, it’s worth noting that, when working with CSS, the body selector is often used to set a default
font family and color for the website. We’ll discuss working with text in more depth in the next chapter, but
for now, check out the following CSS:
body {
font-family: Verdana, Arial, Helvetica, sans-serif;
color: #000000;
background-color: #ffffff;
}
www.freepdf-books.com
Chapter 2
42
This is straightforward. The font-family property sets a default font (in this case, Verdana) and fallback
fonts in case the first choice isn’t available on the user’s system. The list should end with a generic family,
such as sans-serif or serif, depending on your other choices. The fonts are separated by commas in the
list, and if you’re using multiple-word fonts, they must be quoted ("Courier New", not Courier New).
The color property’s value defines the default color of text throughout the site. In the preceding example,
its value is #000000, which is the hexadecimal (hex) value for black (when defining colors in CSS, it’s most
common to use hex values, although you can use comma-separated RGB values if you want).
The color red can be specified in different ways:
color: red (color name)
color: #ff0000 (hex)
color: rgb(255,0,0) (RGB value)
It’s also advisable where possible to add a background color for accessibility; in this case, the background
color is #ffffff—hex for white.
Although it’s possible to set a default size (and other property values) for text in the body
declaration, we’ll leave that for now and instead explore how best to do so in the
following chapter
Web page backgrounds
Web page backgrounds used to be commonplace, but they became unpopular once designers figured out
that visitors to web pages didn’t want their eyes wrenched out by gaudy tiled background patterns. With
text being as hard to read on-screen as it is, it’s adding insult to injury to inflict some nasty paisley mosaic
background (or worse) on the poor reader, too.
But, as affordable monitors continue to increase in size and resolution, designers face a conundrum. If
they’re creating a liquid design that stretches to fit the browser window, text can become unreadable,
because the eye finds it hard to scan text in wide columns. And if they’re creating a fixed-width design,
large areas of the screen often end up blank. It’s for the latter design style that backgrounds can be useful,
both in drawing the eye to the content and providing some visual interest outside of the content area.
Like most things related to design, the use and style of backgrounds is subjective, but some rules are
worth bearing in mind. The most obvious is that a background should not distract from your content. If
you’re using background images, keep them simple, and when you’re using color, ensure that the contrast
and saturation with the page’s background color is fairly low but that the contrast with the text content over
the background is very high. Also, unless you’re using a subtle watermark, it’s generally bad form to put
complex images underneath text (a soft gradient or simple geometric shape can sometimes be OK,
however). Also, because backgrounds are typically ancillary content, they should not significantly increase
the loading time of the page.
www.freepdf-books.com
Web Page Essentials
43
Web page backgrounds in CSS
Backgrounds are added to web page elements using a number of properties, as described in the sections
that follow.
background-color
This property sets the background color of the element. In the following example, the page’s body
background color has been set to #ffffff (which is hex for white):
body {
background-color: #ffffff;
}
background-image
This property sets a background image for the relevant element:
body {
background-image: url(background_image.jpg);
}
By using this CSS, you end up with a tiled background, as shown in the following image.
background-repeat
The properties explored so far mimic the range offered by deprecated HTML attributes, but CSS provides
you with control over the background’s tiling and positioning. The background-repeat property can take
four values, the default of which is repeat, creating the tiled background just shown.
If background-repeat is set to no-repeat, the image is shown just once, as in the following illustration.
www.freepdf-books.com
Chapter 2
44
If this property is set to repeat-x, the image tiles horizontally only.
And if the property is set to repeat-y, the image tiles vertically only.
background-attachment
This property has two possible values: scroll and fixed. The default is scroll, in which the background
works as normal, scrolling with the rest of the page. If you set the value to fixed, the background image
remains stationary while the remainder of the page scrolls.
www.freepdf-books.com
Web Page Essentials
45
background-position
This property’s values set the origin of the background by using two values that relate to the horizontal and
vertical positions. The default background-position value is 0 0 (the top left of the web page).
Along with keywords (center, left, and right for horizontal positioning; center, top, and bottom for
vertical positioning), you can use percentages and pixel values. It’s possible to use a combination of
percentages and pixel sizes, but you cannot mix keywords with either. Therefore, it’s recommended that
designers stick with using percentages and pixel values—after all, keyword positioning can be emulated
with numbers anyway (left top being the same as 0 0, for instance). When setting values, they should
always be defined in the order horizontal-vertical.
When using keywords, it’s also recommended to use the order horizontal-vertical, because both
percentage- and pixel-based background positioning use this order, and it’s simpler to remember a single
rule. In the following example, the background would be positioned on the left of the web page and
positioned in the vertical center of the content:
body {
background-image: url(background_image.gif);
background-repeat: no-repeat;
background-position: left center;
}
Again, when using percentages or pixel values, the first value relates to the horizontal position, and the
second relates to the vertical. So, to create the equivalent of the keyword example, you’d use the following
CSS:
body {
background-image: url(background_image.gif);
background-repeat: no-repeat;
background-position: 0 50%;
}
Note, however, when using background-position with the body element, that browsers disagree slightly on
where the background should be positioned vertically if the page content isn’t taller than the viewing area.
Internet Explorer and Safari assume the body is the full view area height when there’s no content, thereby
setting an image with a background-position value of 50% 50% directly in the center of the viewing area.
Firefox and Opera instead assume the body has an effective height of 0, thereby placing the background
vertically at the top of the view area (in fact, you see only the bottom half). For consistency across
browsers in this case, you can define both background-position and background-attachment (as fixed),
although this means the background will not scroll with the page content.
CSS shorthand for web backgrounds
As when defining margins and padding, you can use shorthand for web background values, bundling them
into a single background property, although it’s worth stating that the shorthand value overrides any
previous settings in a CSS file for individual background properties. (For instance, if you use individual
settings to define the background image and then subsequently use the shorthand for setting the color, the
background image will most likely not appear.)
www.freepdf-books.com
Chapter 2
46
When using shorthand, you can set the values in any order. Here’s an example:
body {
background: #ffffff url(background_image.gif) no-repeat fixed 50%
10px;
}
Generally speaking, it’s best to use shorthand over separate background properties—it’s quicker to type
and easier to manage. You also don’t have to explicitly define every one of the values; if you don’t, the
values revert to their defaults. Therefore, the following is acceptable:
body {
background: #ffffff url(background_image.gif) no-repeat;
}
Because the background-attachment value hasn’t been specified, this background would scroll with the
page, and because the background-position value hasn’t been defined, the background would be
positioned at 0%, 0%—the top left of the browser window.
Gradients
A gradient is an image that smoothly fades from one color to another. These are commonly used for subtle
shading in background images, buttons, and many other things. They can be used anywhere an image
can, such as in the background-image or list-style-image properties.
.fancybox {
background: linear-gradient(white, gray);
}
A linear gradient is created by specifying a gradient-line and then several colors placed along that line. The
image is constructed by creating an infinite canvas and painting it with lines perpendicular to the gradient-
line, with the color of the painted line being the color of the gradient-line where the two intersect. The first
argument to the function specifies the gradient-line, which gives the gradient a direction and determines
how color-stops are positioned.
Here are some examples:
linear-gradient(white, gray);
linear-gradient(to bottom, white, grey);
linear-gradient(180deg, white, grey);
In a radial gradient, rather than colors smoothly fading from one side of the gradient box to the other as
with linear gradients, they instead emerge from a single point and smoothly spread outward in a circular or
elliptical shape.
A radial gradient is specified by indicating the center of the gradient and the size and shape of the ending
shape. Color stops are given as a list, just as for linear-gradient(). Starting from the center and progressing
toward the ending shape, concentric ellipses are drawn and colored according to the specified color stops.
Here are some examples:
www.freepdf-books.com
Web Page Essentials
47
radial-gradient(yellow, green);
radial-gradient(ellipse at center, yellow 0%, green 100%);
In addition to the linear-gradient() and radial-gradient() functions, this spec defines repeating-linear-
gradient() and repeating-radial-gradient()functions.
Web page background ideas
Before finishing up this section on web page backgrounds, we’ll run through some examples that show the
CSS and the result, along with the background image used. The files within the basic-boilerplates folder
can be used as starting points for web pages and CSS documents. The images used in each case are in
the chapter 2 folder of the download files, and they should be placed in the same folder as the HTML and
CSS documents, unless you amend path values accordingly.
Rename the files as appropriate for each example, ensuring you import the relevant CSS file via the HTML
document’s @import line.
For the HTML document, add several paragraphs within the existing div element that has an id value of
wrapper, as in the following code block (which, for space reasons, shows only a single truncated
paragraph—add more than this!):
<div id="wrapper">
<p>...</p>
</div>
In CSS, there are also some common elements to add to the boilerplate. For the #wrapper rule, add some
padding to ensure the content within doesn’t hug the box’s edges, and add a background rule to color the
box’s background white. Also, the width value defines the width of the box’s content, while the margin
settings center the box horizontally. (The method will be discussed further in other chapters, but by setting
0 auto as the margin values, vertical margins are removed and horizontal margins are set to auto, which
center the box horizontally in the browser window.)
#wrapper {
padding: 18px;
background: #ffffff;
width: 500px;
margin: 0 auto;
}
Note that in the download files, in order to keep things modular, there are two #wrapper rules in the CSS,
and that’s what’s assumed in the previous code block. However, if you prefer, add the property/value pairs
from the previous code block to the style sheet’s existing #wrapper rule. The same is true for many of the
rules, such as the body rules in the following sections.
Adding a background pattern
The following CSS can be used to add a patterned, tiled background to your web page:
www.freepdf-books.com
Chapter 2
48
body {
background: #ffffff url(background-tile.gif);
}
The following screenshot shows a page with a diagonal cross pattern, although you could alternatively use
diagonal stripes, horizontal stripes, squares, or other simple shapes.
Note that if you remove many of the paragraphs from the web page, the white
background color ends with the content, since in CSS a container’s size by default only
stretches to that of its content.
Drop shadows
The following image shows a page with a content area and drop shadow.
www.freepdf-books.com
Web Page Essentials
49
This effect was achieved by creating the depicted background image and tiling it vertically. In the body rule,
the position was set to 50% 0 in order to position the background centrally on the horizontal axis. The
background color of the web page is the same as the solid background on the image itself, so the image
and color seamlessly blend.
body {
background: #878787 url(background-drop-shadow.gif) 50% 0 repeat-y;
}
Regarding the white area of the image, this is 536 pixels wide. This is because the wrapper div’s width
was earlier set to 500 pixels, and its padding value was set to 18 pixels. As you will remember from the
box model information from the previous chapter, padding is added to the dimensions of a box, so the
overall width taken up by the wrapper div is 536 pixels (18 + 500 + 18 = 536).
A drop shadow that terminates with the content
In the previous example, the white background of the content area is part of the image. Therefore, if you
remove most of the paragraphs in that example, the background stays as it is, tiling vertically to the height
of the viewing area. Using a different method, you can instead have the background terminate with the
content.
Some additional markup is needed, because of this method requiring two background images: one for the
wrapper div (because, as per the white background in the “Adding a background pattern” section, you
want the content area’s background to stop when the content runs out) and one for a shadow for the
bottom edge of the wrapper div (otherwise, the shadows at the side will just stop dead, resulting in
something like what’s shown in the following image).
www.freepdf-books.com
Chapter 2
50
In terms of markup, add an empty div, as shown in the following code block:
? accumsa'n eu, blandit sed, blandit a, eros.</p>
<div class="contentFooter"><!-- x --></div>
</div>
</body>
</html>
In CSS, for the drop shadows flanking the content area to stop where the content does, they need to be
assigned to the wrapper div, not the web page’s body. Therefore, you need to amend the body rule,
removing the link to a background but retaining the color setting:
body {
background: #878787;
}
The #wrapper rule needs updating in two ways. First, the new background image needs to be applied to
the div—hence the new background property/value pair. However, because the drop shadows are now
shown within the wrapper div, it needs to take up more horizontal space. Since the dimensions of the
div’s content don’t need changing, this is achieved by increasing the horizontal padding value. Also,
because padding at the foot of the div is no longer required (the contentFooter div effectively takes care
of padding at the bottom of the content area), the bottom padding value needs to be set to 0. These
padding values are done in shorthand, as per the method outlined in the “Working with CSS shorthand for
boxes” section earlier in this chapter.
#wrapper {
padding: 18px 36px 0;
background: url(background-drop-shadow-2.gif) 50% 0 repeat-y;
width: 500px;
margin: 0 auto;
}
Finally, the contentFooter div needs styling. Its height is defined on the basis of the height of the
background image (which is a slice of the Photoshop document shown in the following image). The
background is applied to the div in the same way as in previous examples.
One major change, however, is the use of negative margins. The contentFooter div is nested within the
wrapper, which has 36 pixels of horizontal padding. This means that the contentFooter div background
doesn’t reach the edges of the wrapper div by default, leaving whitespace on its left and right sides. By
using margins equal to the negative value of this padding, the div can be “stretched” into place.
www.freepdf-books.com
Web Page Essentials
51
.contentFooter {
height: 20px;
background: url(background-drop-shadow-2-footer.gif) 50% 0;
margin: 0 -36px;
}
As you can see, the horizontal value for margin is -36px, the negative of the horizontal padding value
assigned to #wrapper. The addition of all these new rules results in the following image (which also shows
the Photoshop image and exported GIF that makes up the background).
An alternate method for getting this effect would be to place the contentFooter div outside of the wrapper
and then use the same method of aligning it:
.contentFooter {
width: 500px;
height: 20px;
background: url(background-drop-shadow-2-footer.gif) 50% 0;
padding: 0 36px;
margin: 0 auto;
}
To ensure the background of the wrapper joins up with the shadow on the contentFooter div, a single
pixel of bottom padding needs to be applied to the #wrapper rule:
#wrapper {
padding: 18px 36px 1px;
background: url(background-drop-shadow-2.gif) 50% 0 repeat-y;
width: 500px;
margin: 0 auto;
}
www.freepdf-books.com
Chapter 2
52
CSS3 shadows
The box-shadow property attaches one or more drop shadows on a box. The
property is a comma-separated list of shadows, each specified by two to four
length values, an optional color, and an optional insetkeyword.
div {
width: 150px;
height: 150px;
border:5px solid blue;
background-color:orange;
margin: 30px;
color: blue;
text-align: center;
}
#box1 {
box-shadow: rgba(0,0,0,0.4) 10px 10px;
}
#box2 {
box-shadow: rgba(0,0,0,0.4) 10px 10px 0 10px
}
#box3 {
box-shadow: rgba(0,0,0,0.4) 10px 10px inset
}
Plain image gradients
Tiled gradient images can be used to add depth and visual interest, without sapping resources (the
example’s image is less than 2 KB in size). The depicted example is based on the page from the “Drop
shadows” section. The changes are an amendment to the background pair in the #wrapper rule, tiling the
gradient image horizontally on the wrapper’s background, and new padding settings, so the text doesn’t
appear over the gradient.
#wrapper {
padding: 36px 18px 18px;
background: #ffffff url(background-gradient.gif) repeat-x;
width: 500px;
margin: 0 auto;
}
www.freepdf-books.com
Web Page Essentials
53
Watermarks
Although it’s common for sites to be centered in the browser window, many designers choose left-aligned
sites that cling to the left edge of the browser window. Both design styles are perfectly valid, but in an era
of rapidly increasing monitor resolutions, you can end up with a lot of dead space to the side of a fixed-
width left-aligned design. And while some of you might be saying, “Well, create flexible-width designs,
then!” some designs aren’t suited to that, and text-heavy sites tend to work better with fairly narrow text
columns, since most users find it hard to read very wide blocks of text.
All of this brings us to the final example in this chapter, which shows how to create watermarks for a web
page. In the following screenshot, the wrapper div is to the left, with a background image to the right of
this area.
www.freepdf-books.com
Chapter 2
54
To achieve this effect, the margin property/value pair in the #wrapper rule has been removed, and the
following rule has been added:
body {
background: #878787 url(background-watermark-large.gif) no-repeat
536px 0;
}
As mentioned earlier in the chapter, this assumes you’re adding a second body rule. You
can, however, just add the background property/value pair to the existing body rule in the
style sheet.
The image used is a transparent GIF, so the background color setting was made a medium-gray
(#878787). The reasoning behind using a transparent GIF is explained in Chapter 4, but it relates to web
browsers sometimes interpreting colors differently from graphics packages. Therefore, it’s often easier to
make the flat background color of a graphic transparent and then use the web page background color in
place of it.
The repeat setting is set to no-repeat, because we don’t want the image to tile. Finally, the background’s
position is set to 536px 0 . The 0 setting means it hugs the top of the browser window, while the 536px
setting means the image is placed at 536 pixels from the left. This is because the content area was earlier
defined as 500 pixels wide with 18 pixels of padding, and 18 + 500 + 18 = 536.
As mentioned earlier, backgrounds can be added to any web page element. For instance, you can add a
watermark to the wrapper div by using the following CSS:
#wrapper {
padding: 18px;
www.freepdf-books.com
Web Page Essentials
55
background: #ffffff url(background-watermark.gif) no-repeat 20px
20px;
width: 500px;
}
This adds the background-watermark.gif image to the background of the content div and positions it 20
pixels from the top and 20 pixels from the left. Again, no-repeat is used to stop the image from tiling.
In either case for the watermark backgrounds, the images scroll with the page content. However,
watermarks can also work well as fixed backgrounds—this can be achieved by adding the fixed value to
the background property in the body and #wrapper rules.
CSS3 patterns
The CSS3 gradient features that are described earlier are powerful enough to produce beautiful patterns.
Web designer Lea Verou has assembled a nice CSS3 patterns gallery from many contributors
(http://lea.verou.me/css3patterns).
www.freepdf-books.com
Chapter 2
56
Closing your document
At the start of this chapter, we examined basic HTML and XHTML documents. Regardless of the
technology used, the end of the document should look like this:
</body>
</html>
There are no variations or alternatives. A body end tag terminates the document’s content, and an html
end tag terminates the document. No web page content should come after the body end tag, and no HTML
content should come after the html end tag (whitespace is fine, and it’s common practice with server-side
technologies to put functions after the html end tag—just don’t put any HTML there).
Also, you must only ever have one body and one head in an HTML document, as well as a single html start
tag and a single html end tag.
This is important stuff to bear in mind, and even if you think it’s obvious, there are millions of pages out
there—particularly those that utilize server-side includes and server-side languages—that include multiple
body tags and head tags, have content outside the body tag, and have HTML outside the html tag.
Don’t do this in your own work.
www.freepdf-books.com
Web Page Essentials
57
Naming your files
Each designer has their own way of thinking when it comes to naming files and documents. Personally, we
like to keep document names succinct but obvious enough that we can find them rapidly via a trawl of the
hard drive. Certain conventions, however, are key: all file names should avoid illegal characters (such as
spaces), and it’s good to be consistent throughout your site. We find that naming files in lowercase and
replacing spaces with hyphens—like-this-for-example.html—works well.
Web designers have historically used underscores in place of spaces, but that causes
problems with some search engines, some of which run-in keywords, effectively
considering the words within the file name as one string. This doesn’t happen with
hyphens
Commenting your work
The rules for HTML, CSS, and JavaScript comments are simple, but the actual characters used are
different in each case.
HTML comments begin with <!-- and end with --> and can run over multiple lines, as follows:
<!-- this is a comment in HTML -->
<!--
Multiple-line
HTML
comment
-->
In XHTML, double hyphens should not occur within the comment itself. Therefore, the following is not valid
XHTML:
<!-- This is invalid -- as is the comment below -->
<!--------------------------------------------------------->
The multiple-hyphen comment is commonly used by designers who favor hand-coding to separate large
chunks of code within a document. When working in XHTML, you can replace the hyphens with a different
character:
<!--oooooooooooooooooooooooooooooooooooooo-->
<!--================================-->
CSS comments were covered in the “Creating boilerplates” section of Chapter 1, but we’ll briefly look
through them again; they’re opened with /* and closed with */ and, like HTML comments, can run over
multiple lines, as shown here:
/* This is a comment in CSS */
/*
Multiple-line
CSS
www.freepdf-books.com
Chapter 2
58
comment
*/
Multiple-line comments in JavaScript are the same as in CSS, but single-line comments are placed after
double forward slashes:
// This is a single-line JavaScript comment.
Don’t use comments incorrectly. CSS comments in an HTML document won’t be problematic from a
rendering standpoint—but they will be displayed. HTML comments in CSS can actually cause a CSS file to
fail entirely.
Note: Along with enabling you to comment your work, comments can be used to disable
sections of code when testing web pages.
Quickly testing your code
You can easily test your HTML/CSS ideas with JsFiddle (http://jsfiddle.net), which includes an online editor
for snippets build from HTML, CSS, and JavaScript. The code can then be shared with others, embedded
in a blog, and so on.
www.freepdf-books.com
Web Page Essentials
59
A similar service that focuses more on CSS development is Dabblet (http://dabblet.com).
www.freepdf-books.com
Chapter 2
60
Web page essentials checklist
Congratulations—you made it to the end of this chapter! We’re aware that some of this one was about as
much fun as trying to work out complex quadratic equations in your head, but as mentioned at the start,
you need to know this stuff. Imagine designing a site and it suddenly not working the way you thought it
would. It looks fine in your web design package and also in some web browsers, but it starts falling apart in
others. Just removing an XML declaration might be enough to fix the site.
If you take the elements of this chapter and form them into a simple checklist, you won’t have to risk
displaying those wonderful “Untitled Documents” to the entire world (or inadvertently advertising the
package you used to create the page). To make your life easier, you can refer to this checklist:
1. Ensure the relevant DOCTYPE declaration and namespace are in place.
2. Remove the XML declaration if it’s lurking.
www.freepdf-books.com
Web Page Essentials
61
3. Add a title tag and some content within it.
4. Add a meta tag to define your character set.
5. If required, add keywords and description meta tags.
6. Attach a CSS file (or files).
7. Attach a JavaScript file (or files).
8. If your web editor adds superfluous body attributes, delete them.
9. Ensure there are no characters prior to the DOCTYPE declaration or after the html end tag.
10. Ensure no web page content appears outside the body element.
www.freepdf-books.com
63
Chapter 3
Working With Type
In this chapter:
Working with semantic markup
Defining font colors, families, and other styles
Understanding web-safe fonts
Creating drop caps and pull quotes
Rapidly editing styled text
Working to a grid
Creating and styling lists
www.freepdf-books.com
Chapter 3
64
An introduction to typography
Words are important—not just what they say but how they look. To quote Ellen Lupton, from her book
Thinking with Type, “Typography is what language looks like.” Language has always been symbolic,
although the origins of such symbols (of certain letterforms relating to, for example, animals) has largely
been lost in written English; instead, we now have rather more abstract symbols designed for repetition on
the page or screen.
However, from the early calligraphy that was created by hand through the movable type (invented in
Germany by Johannes Gutenberg during the 15th century) that enabled mass-production printing via
molded letterform casts to the most advanced desktop-publishing software available today, the ultimate
aim of type has been one of record and information provision. In other words, type is important from a
design standpoint because it needs to record whatever information is being written about, and that
information needs to be easily retrievable by anyone who wants to understand it.
Like all aspects of design, typography has massively evolved over the years, particularly over the past
couple of decades, where computers have enabled designers to more rapidly experiment with lettering.
Despite this, many conventions formed much earlier still have a part to play:
Myriad fonts exist, and each one has a different look and therefore a different “feel.” You need to
choose the most appropriate one for your purpose. (This is further complicated by there being
only a certain number of web-safe fonts, as you’ll learn later.)
Headings, strap-lines/stand-firsts (the introductory line that introduces a piece of text, commonly
used in editorial articles), and crossheads (short subheadings that break up areas of body copy)
should stand out, and the prominence of each piece of text should be related to its level of
importance (in other words, a crosshead shouldn’t be more prominent than a main heading).
Footnotes often use text smaller than the main body copy text to signify their lesser significance
to the main text, but nonetheless they provide useful supplementary information.
Decorative elements can be used to draw the reader’s attention to specific
parts of the text. Drop caps and initials—large initial letters, flamboyant in
classical typography, but typically more restrained in modern work (see
right)—enable a reader to rapidly navigate to the beginning of a piece of
text. Pull quotes—quotes from the main body of the text, displayed in
large lettering outside of context—are often used in magazine articles to
draw a reader’s attention to a particular article, highlighting particularly interesting quotes or
information.
Spacing is just as important as content. Kerning—the spacing between letter pairs—can be
increased to add prominence to a heading. Leading—the amount of added vertical spacing
between lines of text—can also be adjusted. Increasing leading from its default can make text
more legible. In books, a baseline grid is often employed, ensuring that text always appears in the
same place on each page. This means that the text on the opposite side of the paper doesn’t
appear in the gaps between the lines on the page you’re reading. Baseline grids often make for
www.freepdf-books.com
Working With Type
65
extremely pleasing vertical rhythm and are regularly used in print publications; they’re infrequently
used online but can nonetheless be of use, making a page of text easier to read and navigate.
Columns sometimes make a page easier to read, and this technique is routinely used by
newspapers and magazines. Online, the recent ability to autoflow columns of text makes de facto
text columns possible. This is impractical because not every browser supports it yet and because
columns force users to scroll repeatedly, but the reasoning behind columns is still handy to bear
in mind. Generally, it’s considered easier to read text that has fairly narrow columns (although not
too narrow—if there are too few characters, reading and comprehension slow down). Text that,
for example, spans the entire width of a 23-inch monitor rapidly becomes tiring to read. There are
no hard-and-fast rules when it comes to line length, although some go by the “alphabet-and-a-
half” rule (39 characters per line), some advocate the “points-times-two” rule (double the point
size and use the number for the number of characters), and others recommend a dozen or so
words (or about 60 characters).
A few highly useful online resources for web typography can be found at the following locations:
The Elements of Typographic Style Applied to the Web: www.webtypography.net/
Five Simple Steps to Better Typography: www.markboulton.co.uk/journal/comments/five-
simple-steps-to-better-typography/
Five Simple Steps to Designing Grid Systems: www.markboulton.co.uk/journal/comments/five-
simple-steps-to-designing-grid-systems/
When it comes to web design, some conventions are used, and others are ignored. In fact, while web
designers take the utmost care to get layouts right, scant few give the same thought to text, merely
choosing a font and arbitrarily setting other values, if they set them at all. Once, this could be excused, but
CSS has enabled web type to come a long way, and although the same degree of control as print-based
type isn’t possible, you can do a lot more than just choose your preferred font for headings and body copy.
www.freepdf-books.com
Chapter 3
66
In this chapter, we’ll take a look at the various components available when working on web-based type
(including elements and CSS properties) and provide some exercises, the results from which you can use
for the basis of your own sites’ type. As a final note in this introduction, it’s also worth mentioning spelling
and grammar. Both of these are clearly way outside the scope of this book, but they’re things designers
tend to overlook. A site with a lot of grammatical and spelling errors, especially in larger text (such as
headings and pull quotes), looks unprofessional. If in doubt when working on sites, consult (or get your
client to consult) a copywriter.
Note: There are a couple of books worth digging out for more information on typography
and language. A decent primer on type design is Helen Lupton’s Thinking with Type. For
an entertaining (if not entirely accurate) history of the English language, read Bill
Bryson’s The Mother Tongue.
Styling text the old-fashioned way (or, why we hate
font tags)
Styling text online used to be all about font tags. When Netscape introduced the font element—complete
with size and color attributes—web designers wept tears of joy. When Microsoft announced it would go
further, adding a face attribute (enabling you to specify the font family), web designers were giddy with
anticipation. But things didn’t go according to plan. Page sizes bloated as designers created pages filled
with fonts of myriad sizes and colors. Web users looked on aghast, wondering whether giant, orange body
copy was really the way to go and whether it was worth waiting twice as long for such abominations to
download.
More important, it became apparent that font tags caused problems, including the following:
Inconsistent display across browsers and platforms
The requirement for font tags to be applied to individual elements
Difficulty ensuring fonts were consistent sitewide, because of having to style individual elements
HTML geared toward presentation rather than logical structure
Large HTML documents because of all the extra elements
In addition, working with font tags is a time-consuming, boring process, and yet some (although, thankfully,
increasingly few) web designers remain blissfully ignorant of such problems. In my opinion, if font tags
weren’t HTML elements, I’d suggest they be taken out back and shot. Today, there is no reason
whatsoever to stick with them. Text can be rapidly styled sitewide with CSS, and, as you’ll learn later in
this chapter, CSS provides you with a greater degree of control than font tags ever did. More crucially, font
tags encourage badly formed documents, with designers relying on inline elements to style things like
headings, when there are perfectly good HTML elements better suited to that purpose.
www.freepdf-books.com
Working With Type
67
HTML should be reserved for content and structure, and CSS for design. Web pages should be composed
of appropriate elements for each piece of content. This method of working, called semantic markup, is what
we’re going to discuss next.
A new beginning: semantic markup
Essentially, semantic markup means “using the appropriate tag at the relevant time,” and well-formed
semantic markup is an essential aspect of any website. The following is an example of the wrong way of
doing things—relying on font tags to create a heading and double line breaks (<br /><br />) for separating
paragraphs:
<font size="7" color="red" face="Helvetica">Article heading</font>
<br /><br />
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed aliquet
elementum erat. Integer diam mi, venenatis non, cursus a,
hendrerit at, mi.
<br /><br />
Quisque faucibus lorem eget sapien. In urna sem, vehicula ut, mattis
et, venenatis at, velit. Ut sodales lacus sed eros.
Tags should always relate to the content so that if the styling is removed, there is always an indication of
what role each element plays within the document structure and hierarchy—for instance, there would be
no visual clues as to the importance of the heading. Also, the use of double line breaks (<br /><br />)
instead of paragraph tags means the “paragraphs” cannot be styled in CSS, because there’s nothing to
inform the web browser what the content actually is.
Instead, the example should be marked up like this:
<h1>Article heading</h1>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Sed
aliquet elementum erat. Integer diam mi, venenatis non, cursus
a, hendrerit at, mi.</p>
<p>Quisque faucibus lorem eget sapien. In urna sem, vehicula ut,
mattis et, venenatis at, velit. Ut sodales lacus sed eros.</p>
Here, the heading is marked up with the relevant tags, and paragraph elements are used instead of double
line breaks. This means the page’s structural integrity is ensured, and the markup is logical and semantic.
If the attached CSS styles are removed, the default formatting still makes obvious to the end user the
importance of the headings and will visually display them as such.
In this section, we’ll look at how to mark up paragraphs and headings, explore logical and physical styles,
and discuss the importance of well-formed semantic markup.
Paragraphs and headings
With words making up the bulk of online content, the paragraph and heading HTML elements are of
paramount importance. HTML provides six levels of headings, from h1 to h6, with h1 being the top-level
www.freepdf-books.com
Chapter 3
68
heading. The adjacent image shows how these headings, along with a paragraph, typically appear by
default in a browser.
<h1>Level one heading</h1>
<h2>Level two heading</h2>
<h3>Level three heading</h3>
<h4>Level four heading</h4>
<h5>Level five heading</h5>
<h6>Level six heading</h6>
<p>Default paragraph size</p>
By default, browsers put margins around paragraphs and headings.
This can vary from browser to browser, but it can be controlled by
CSS. Therefore, there’s no excuse for using double line breaks to
avoid default paragraph margins affecting web page layouts.
Despite the typical default sizes, level-five and level-six headings
are not intended as “tiny text” but as a way to enable you to
structure your document, which is essential, because headings help
with assistive technology, enabling people who are visually disabled
to efficiently surf the Web.
In terms of general usage, it’s generally recommended to stick to
just one h1 element per sectioning element, used for the section’s
primary heading. As discussed in Chapter 2, a sectioning element is
an <article>, <nav>, <section>, or <aside>. The next level down—and the first level in a sidebar—would be
h2, and then h3, and so on. Take care not to use too many heading levels, though; unless you’re working
on complex legal documents, you really shouldn’t be getting past level four. If you are, look at restructuring
your document.
Logical and physical styles
Once text is in place, it’s common to add inline styles, which can be achieved by way of logical and
physical styles. Many designers are confused by the difference between the two, especially because
equivalents (such as the logical strong and physical b) tend to be displayed the same in browsers. The
difference is that logical styles describe what the content is, whereas physical styles merely define what
the content looks like. This subtle difference is more apparent when you take into account things like
screen readers.
In the markup, I like to <em>emphasize</em> things; a screen reader emphasizes the text surrounded by
the em tags. However, replace the em tags with i tags, and the screen reader won’t emphasize the word,
although in a visual web browser the two pieces of markup will almost certainly look identical.
Styles for emphasis (bold and italic)
Physical styles enable you to make text <b>bold</b> and <i>italic</i>, and these are the most commonly
used inline physical styles. However, logical styles are becoming much more widespread (the majority of
web design applications, such as Dreamweaver, now default to logical styles rather than physical ones).
www.freepdf-books.com
Working With Type
69
Typically, <strong>strong emphasis</strong> emboldens text in a visual web browser, and
<em>emphasis</em> italicizes text.
Deprecated and nonstandard physical styles
Many physical elements are considered obsolete, including the infamous blink (a Netscape innovation”
used to flash text on and off, amusingly still supported in Firefox). Some physical styles are deprecated: u
(underline) and s (strikethrough; also strike) have CSS equivalents using the text-decoration property (text-
decoration: underline, and text-decoration: line-through, respectively).
The small element
The small element is used to decrease the size of inline text (even text defined in pixels in CSS). An
example of the use of small might be in marking up text that is semantically small print.
Note, however, that the change in size depends on individual web browsers, so it’s important that you
define specific values in CSS for the small element when used in context.
Subscript and superscript
This leaves two useful physical styles. The first, sub, renders as text subscript text. The second, sup,
renders text as superscript text, respectively. These are useful for scientific documents, although there is a
drawback: characters are displayed at the same size, defined by the browser. You can get around this by
using a CSS tag selector and defining a new font size for each element. The following code shows how to
do this, and the accompanying screenshot shows a default sup element (at the top of the image) and a
CSS-styled sup element (at the bottom) in use.
sup {
font-size: 70%;
}
Logical styles for programming-oriented content
Several logical styles do similar jobs, are programming-oriented, and are usually displayed in a
monospace font:
<code>Denotes a code sample.</code>
<kbd>Indicates text entered by the user.</kbd>
<samp>Indicates a programming sample.</samp>
The var element also relates to programming, signifying a variable. However, it is usually displayed in
italics.
www.freepdf-books.com
Chapter 3
70
Block quotes, quote citations, and definitions
The blockquote element is used to define a lengthy quotation and must be set within a block-level element.
Its cite attribute can be used to define the online location of quoted material. See the “Creating drop caps
and pull quotes using CSS” section for more on using this element.
Note that some web design applications—notably, early versions of Dreamweaver—used the
blockquote element to indent blocks of text, and this bad habit is still used by some designers.
Don’t do this. If you want to indent some text, use CSS.
For shorter quotes that are inline, the q element can be used. This is also supposed to add language-
specific quotes before and after the content between the element’s tags. These quotes vary by browser—
Firefox and Internet Explorer add “smart” quotes; Safari, Chrome, and Opera add “straight” quotes.
Finally, to indicate the defining instance of a term, you use the dfn element. This is used to draw attention
to the first use of such a term and is also typically displayed in italics.
Abbreviations
Abbreviations assist with accessibility, enabling you to provide users with full forms of abbreviations and
acronyms by way of the title attribute:
<abbr title="Cascading Style Sheets">CSS</abbr>
This has two uses. For one, it allows users with disabilities (using screen readers) to access the full form of
the words in question. But anyone using a visual web browser can access the information, too, because
title attribute contents are usually displayed as a tooltip when you hover your mouse over elements they’re
used on.
To further draw attention to an abbreviation or acronym, style the tag in
CSS (using a tag selector), thereby making all such tags consistent across
an entire website. The following code is an example of this, the results of
which are shown in the example to the right (including the tooltip triggered
by hovering over the abbr element, which has a title attribute).
abbr {
border-bottom: 1px dotted #000000;
background-color: yellow;
}
Note: You can provide an additional aid to users by setting cursor to help in CSS for abbr
elements. This changes the cursor to a question mark while hovering over the element.
www.freepdf-books.com
Working With Type
71
Elements for inserted and deleted text
The del and ins elements are used, respectively, to indicate deleted text and inserted text, typically in a
manner akin to the tracking features of word-processing packages, although they do not include the
tracking functionality. The del element usually appears in strike-through format, whereas ins usually
appears underlined. Both accept cite and datetime attributes. The former enables you to define a URL that
explains why text was inserted or deleted; the latter enables you to define the time and date that the text
was amended—see the <ins> and <del> entries in Appendix A for accepted formats.
Note that these elements cannot be nested inside each other, for obvious reasons. The following is an
example of their use:
<p>I <del>deleted this</del> and then <ins>inserted this</ins>.</p>
The default style of the ins element can prove problematic online. Because links are underlined by default,
users may attempt to click text marked up as inserted text and wonder why nothing happens. It’s a good
idea to amend the tag’s visual appearance by changing the underline color. This can be done by removing
the default underline and replacing it with a bottom border, like so:
ins {
text-decoration: none;
border-bottom: 1px solid red;
}
The bottom border resembles an underline, although it appears lower than the default underline, which
further differentiates inserted text from hypertext links.
The importance of well-formed markup
Many logical styles are rarely used online, because they look no different from text marked up using the
likes of the i element. However, as mentioned earlier, physical appearance alone misses the point of
HTML. Always using the most appropriate relevant element means that you can later individually style
each element in CSS, overriding the default appearance if you want. If the likes of citations, defining
instances, and variables are all marked up with i instead of cite, dfn, and var, there’s no way of
distinguishing each type of content and no way of manipulating their appearance on an individual basis.
Well-formed markup involves more than ensuring visual flexibility, though. Use of the cite tag, for instance,
enables you to manipulate the Document Object Model (DOM) to extract a bibliography or list of quotations
from a page or even a full website. The ability to style logical tags like this with CSS is likely to be of
increasing rather than diminishing importance.
The importance of end tags
While we’re on the subject of well-formed markup, we’ll revisit the importance of end tags. As mentioned
earlier, XHTML demands that all tags be closed. Most browsers let you get away with ignoring some end
tags, though, such as on paragraphs. Some designers may still have bad habits from working with HTML,
www.freepdf-books.com
Chapter 3
72
for which many end tags are optional. Omit many others at your peril. For instance, overlook a heading
element end tag, and a browser considers subsequent content to be part of the heading and displays it
accordingly. As shown in the following image, two paragraphs are displayed as a heading because the
earlier heading element lacks an end tag.
A similar problem occurs when you accidentally omit end tags when using logical and physical elements.
For instance, forget to close an emphasis element, and the remainder of the web page may be displayed
in italics.
Note: Some designers when hand-coding create both start and end tags at the same
time and then populate the element with content, ensuring end tags are not forgotten.
Styling text using CSS
HTML is intended as a structural markup language, but the Web’s increasing popularity meant it got
“polluted” with tags designed for presentation. This made HTML more complex than it needed to be, and
such tags soon became a headache for web designers trying to style page elements, such as text. In the
bad ol’ days (the end of the 1990s), you’d often see source code like this:
<font face="Helvetica" size="3" color="#333333"> This markup is
<font size="+3"><small>really </small></font>bad, but it was sort of
the norm in the 1990s.</font>
WYSIWYG tools would insert new tags to override previous ones, adding to the page weight and making it
tough to ensure visual consistency sitewide. By and large, CSS eradicates these problems and enables far
more control over text, as you’ll see in the following sections.
This is a boon for graphic designers who used to loathe HTML’s lack of typographical control. However,
the level of freedom evident in print design still isn’t quite so on the Web. Restrictions imposed by
browsers and the screen must be taken into account, such as it being harder to read type on-screen than
in print. This is largely related to resolution. Even magazines with fairly low-quality print tend to be printed
at around 200 dpi or more—more than twice the resolution of a typical monitor. This means that very small
www.freepdf-books.com
Working With Type
73
text (favored by many designers, who think such small text looks neat) becomes tricky to read on-screen,
because there aren’t enough pixels to create a coherent image.
I’ll note restrictions such as this at appropriate times during this section on styling text with CSS, thereby
providing advice on striking a balance between the visual appearance and the practicality of web-based
text.
Defining font colors
In CSS, the color property value defines the foreground color of the relevant CSS element, which for text
sets its color. This can be set using hex, keywords, RGB, or RGBA. The following examples show each
method in turn, and all have the same result: setting paragraphs to black.
p {
color: #000000;
}
p {
color: black;
}
p {
color: rgb(0,0,0);
}
p {
color: rgba(0,0,0,1);
}
Declaring colors using RGB is rare in web design—hex is most popular, especially because CSS supports
so few keywords (see the section “Working with hex” in Chapter 4).
Remember to test your choices on both Windows and Mac, because there are differences in the default
color space for each platform. In general terms, the Mac default display settings are brighter (or Windows
is darker, depending on your outlook on life); if you use subtle dark tones on the Mac or very light tones on
Windows, the result might be tricky to view on the other platform.
It is also a good idea to test on as many different monitors and devices available to you. While your site
might display perfectly on an LCD monitor, it might not on a CRT. Smartphones and tablets are also
becoming increasingly popular for viewing websites, and they have drastically different display
technologies.
This should cause few problems with text, but some designers insist on rendering text with very little
contrast to the background color, and this ends up being even harder to read on a different platform or
monitor from the one on which it was created.
The main tip to keep in mind for color with regard to web-based text is simple: always
provide plenty of contrast so that your text remains readable.
www.freepdf-books.com
Chapter 3
74
Defining fonts
The font-family property enables you to specify a list of font face values, starting with your preferred first
choice, continuing with alternates (in case your choice isn’t installed on the user’s machine), and
terminating in a generic font family, which causes the browser to substitute a similar font (think of it as a
last resort).
selector {
font-family: preferred, "alterate 1", "alterate 2", generic;
}
The most common generic font family names are serif and sans-serif, although when you’re using
monospace fonts (such as Courier New), you should end your list with monospace.
Multiple-word font family names must be quoted (such as "Trebuchet MS" and "Times New Roman"). You
can use single or double quotes—just be consistent. Single-word font family names should never be
quoted. Examples of font-family in use are as follows:
h1 {
font-family: Arial, Helvetica, sans-serif;
}
p {
font-family: Georgia, "Times New Roman", Times, serif;
}
pre {
font-family: Courier, "Courier New", Monaco, monospace;
}
Note: pre is the element for preformatted text, used to display monospace text in an
identical fashion to how its formatted in the original HTML document. It’s commonly
used for online FAQs, film scripts, and the like.
Web-embedded fonts and web-safe fonts
Print designers have a world of fonts at their disposal, and now with the ability to embed any font you want
into your website, web designers do as well. There is hope that web-embedded fonts will soon abolish the
use of regular system fonts, which will enable a web designer to choose any typeface or font style they
want. While all major browsers support embedding fonts, they don’t all do it in the same way. It is
important to include web-safe fonts as a fallback to keep your design consistent and prevent the layout of
your design from breaking for mobile and older versions of major browsers. Web-safe fonts are fonts that
are common across different operation systems such as Mac OS X, Windows, and Linux.
Over the next few pages, I’ll provide an overview of different available fonts for the Web, but there are
some handy online references that you should also bookmark. A page comparing fonts common to
the Mac and Windows is available at www.ampsoft.net/webdesign-l/WindowsMacFonts.html, and
www.codestyle.org/css/font-family/sampler-Monospace.shtml details available monospace fonts for
various systems.
www.freepdf-books.com
Working With Type
75
Embedding web fonts
Embedding web fonts allows web designers to use local or remotely hosted fonts in their designs without
requiring the user to download the font. Using web-embedded fonts is easy and can be done by using the
following CSS syntax:
@font-face {
font-face: ‘webfont’;
src: url(‘http://./’) format(‘frmt’)
}
selector {
font-family: webfont;
font-size: 22pt;
}
Since each major browser implements embedding web fonts using different formats, five different formats
need to be included to ensure your font is displayed correctly across each browser. These formats are
TrueType, OpenType, Embedded OpenType, Web Open Font Format, and SVG fonts. The bulletproof
CSS syntax looks like this:
@font-face {
font-family: Graublauweb;
src: url('Graublauweb.eot'); /* IE9 Compatibility Modes */
src: url('Graublauweb.eot?') format('eot'), /* IE6-IE8 */
url('Graublauweb.woff') format('woff'), /* Modern Browsers */
url('Graublauweb.ttf') format('truetype'), /* Safari, Android, iOS */
url('Graublauweb.svg#svgGraublauweb') format('svg'); /* Legacy iOS */
}
Just like in print design, there are a number of commercial, freeware, and open source fonts, which can be
embedded in your web design. Two great resources for free fonts are www.webfonts.info/ and
www.google.com/webfonts.
As time goes on, legacy browsers and browsers that do not support web fonts will disappear, but until
then, falling back to web-safe system fonts is key to having your website support these browsers.
Sans-serif fonts for the Web
Arial is a common font choice, largely because of its dominance on Windows. Its poor design makes it
unreadable at small sizes and a poor choice for body copy, although it can be of use for headings. Mac
users should be wary of choosing Helvetica—it’s an excellent font, but it’s not generally shipped with
Windows. Although you can specify fallback fonts in CSS, again, there’s little point in making your first
choice something that the majority of people won’t see.
Note: Despite its lack of penetration on Windows, Helvetica is often used as a fallback
sans-serif font, because of its prevalence on Linux.
www.freepdf-books.com
Chapter 3
76
Better choices for body copy are Verdana or Trebuchet MS. The former is typically a good choice,
because its spacious nature makes it readable at any size. Its bubbly design renders it less useful for
headings, though. Trebuchet MS is perhaps less readable, but it has plenty of character and is sometimes
an interesting alternative, simply because it isn’t used all that much online.
In recent times, Lucida variants have become popular, because of Apple using it not only as the default
font in Mac OS X but also on its website. Despite Lucida Grande not being available for Windows, Lucida
Sans Unicode is common and similar enough to be used as a first fallback. Usefully, Lucida is common on
UNIX systems, meaning that sites using Lucida variants can look fairly similar textwise across all three
major operating systems. Another pairing—albeit one that’s less common—is Tahoma and Geneva, so
use those with care, providing more generic fallbacks.
See the following images for a comparison of several sans-serif fonts on Mac (left) and Windows (right).
Serif fonts for the Web
Although popular in print, serif fonts fare less well online. If using serifs, ensure you render them large
enough so that they don’t break down into an illegible mess. Georgia is perhaps the best available
web-safe serif, especially when used at sizes equivalent to 12 pixels and bigger, and it can be more
suitable than a sans-serif if you’re working with traditional subject matter or if you’re attempting to emulate
print articles (such as in the following screenshot of the online column Revert to Saved; www.
reverttosaved.com).
www.freepdf-books.com
Working With Type
77
The other commonly available serif font, Times New Roman (Times being a rough equivalent on Linux
systems), is inferior to Georgia but worth using as a fallback. Like Arial, its popularity is the result of its
prevalence as a system font.
Elsewhere, Palatino is fairly common—installed by default on Windows (as Palatino Linotype) and
available on Mac systems that have Classic or iWork installed. Mac owners with Office will also have the
virtually identical Book Antiqua. That said, if using these fonts, you’ll still need to fall back to safer serifs, as
mentioned earlier.
See the following illustration for a comparison of serif fonts on Mac (left) and Windows (right).
www.freepdf-books.com
Chapter 3
78
Fonts for headings and monospace type
The remaining “safe” fonts are typically display fonts (for headings) or monospace fonts for when each
character needs to be the same width—for example, when adding code examples to a web page.
Arial Black and Impact are reasonable choices for headings, although they must be handled with care. The
bold version of Impact looks terrible (and isn’t displayed at all in some browsers), and some browsers by
default render headings in bold, so this must be overridden in CSS. Often, large versions of fonts
mentioned in the previous two sections are superior.
Courier New is more useful and a good choice when you need a monospace font. Note that falling back to
Courier for Linux is recommended. The pairing of Lucida Console (Windows) and Lucida Sans Typewriter
or Monaco (Mac) may also be suitable for monospace work, if you’re looking for a less “computery” feel.
Few other fonts are worth a mention, barring perhaps Comic Sans MS, which is inexplicably popular with
novice web designers. To give the font its due, it is readable, but its quirky and unprofessional nature
makes it unsuitable for most purposes (even comic artists eschew it in favor of personalized fonts).
The following image shows several of the fonts mentioned in this section, again with Mac versions on the
left and Windows versions on the right.
www.freepdf-books.com
Working With Type
79
Mac vs. Windows: anti-aliasing
When choosing fonts, it’s worth noting that they look different on Mac and Windows. On Macs all browsers
use the system default rendering engine called Core Text to render anti-alias on-screen text. On Windows,
Internet Explorer 8 smooths type via the font-smoothing technology ClearType, while Internet Explorer 9
and 10 use the DirectWrite rendering engine
For body copy, font smoothing (or not) isn’t a major problem; although some prefer aliased text and some
prefer anti-aliased, both are fine, as long as the font size is large enough. However, when it comes to
rendering large text—such as for headings—aliased text is significantly less visually pleasing.
Note: Aliased text is a simplified version of the original font, reduced to pixels made up
of red, green, and blue subpixels. Anti-aliased text attempts to emulate the soft curves of
the original font by introducing gray or colored pixels at the edges.
www.freepdf-books.com
Chapter 3
80
Although arguments rage regarding which is the best method of displaying fonts on-screen, this is a moot
point for web designers, because you don’t control the end user’s setup and therefore must be aware of
each possibility.
Using images for text
Limitations imposed by how different browsers render both embedded and web-safe fonts lead some
designers to seek out alternative methods of creating online type. It’s common to use graphics (mostly
GIFs, but sometimes Flash, because of its vector-based, scalable nature) for text. If you have to follow a
corporate design style under pain of death, the ability to use graphics can be a lifesaver—after all, most
browsers happily render images, and they can be marked up within heading elements, so you can control
things like margins via CSS and also retain the structural integrity of your document.
However, graphical text has its share of problems:
Some browsers do not enable you to resize graphical text in a browser.
Because the Web is low-resolution, when a page is printed out, graphical text looks pixelated and
of poor quality.
Although GIF-based text tends to be small in terms of file size, it’s still larger than HTML-based
text.
People using alternate browsers, such as screen readers, cannot “see” graphical text (although
you can use the alt attribute to compensate).
Graphical text cannot be copied and pasted.
Graphical text cannot be read by search engines.
Graphical text is a pain to update. To change a word, you must rework the original image and
export and upload it, and if the image size has changed, you must edit the appropriate HTML
documents and upload those, too.
In my opinion, graphics should be used as a last resort. A company’s style can be made apparent by the
use of a corporate logo and other imagery rather than by the use of a font. Also, never, ever render body
copy as an image. There are many sites out there with body copy rendered as images, and quite frankly,
every one of them makes me want to scream. Such sites are often full of typos (perhaps because
amending them requires the entire graphic to be reworked, reexported, and uploaded again), cannot be
printed at quality, and cannot be copied to a text editor. Some suggest this means the site’s text is
“secure.” But this goes against one of the fundamental benefits of the Web: that people can share
information and that it can be easily copied and sent on to others. Sure, this presents copyright
implications, but everything online is subject to copyright anyway. Also, plenty of sites commit the cardinal
sin of rendering things like contact details as a graphic—I’m sure their customers very much appreciate
having to type such things out by hand rather than just being able to copy them into their digital address
books.
www.freepdf-books.com
Working With Type
81
Image-replacement techniques
If you need a greater degree of typographical control over a portion of text, such as the site’s main
heading, there is an option that enables you to include an image and also enable the text to remain in
place, which is useful for users surfing the Web with screen readers. This is generally known as image
replacement. Note that the technique should be used with care and sparingly—even from a basic practical
standpoint, it doesn’t make a great deal of sense to set all of your headings as images, simply because it
takes time to create and export each one.
Of the techniques available for replacing images, the most common is to assign the relevant piece of text
(usually a heading) a class value in HTML and also add a dummy span element before its content:
<h1 class="aFancyHeading"><span></span>A fancy heading</h1>
In an image editor, an image-based version of the heading is created and saved, and its dimensions are
measured. Example files for this are a-fancy-heading.gif, image-replacement.css, and image-
replacement.html, located in the chapter 3 folder. In the CSS file, you’ll see rules created to define the
dimensions of the heading (.aFancyHeading) and span (.aFancyHeading span). The heading’s position
value is set to relative, and the span element is then positioned in an absolute fashion, which ensures that
it sits over the text-based heading’s content. The width and height values ensure that the span (and
therefore its background image) expands to fill its container. (Note that when used in conjunction with
links, it’s useful to also set display: block within the CSS rule so that the entire area becomes clickable and
the cursor becomes a pointer—this is because some versions of Internet Explorer use the arrow pointer
instead of the usual finger pointer. Alternatively, set cursor to pointer in CSS.) The overflow: hidden
property/value pair ensures text doesn’t peek out from behind the image—an issue that sometimes occurs
in Internet Explorer or when text is resized. To deal with zoomed text in IE 7, it may also be necessary to
set a pixel font-size value for the heading that’s smaller than the height of the image.
Note: Setting overflow to hidden can be an issue when this technique is used in
conjunction with linked replaced elements, such as linked mastheads and logos. When
tabbing through links, replaced elements that have an overflow setting of hidden will
become displaced on receiving the focus, revealing the underlying text as well as the
image overlaying it. Caution needs to be used here.
The following image shows a page using this technique with and without CSS.
www.freepdf-books.com
Chapter 3
82
Some methods focus on hiding the text by setting display to none in CSS, but that can cause problems for
screen readers, so avoid doing this. Others use text-indent to shift the text off of the page, although using
absolute positioning with negative top and left coordinates is better—this prevents vertical space being
taken up by the offset text, which is quite often noticeable, especially if margins haven’t been controlled.
Note: Scalable Inman Flash Replacement (sIFR) is an alternative to replacing text with
GIF images. Instead, it uses a combination of CSS, Flash, and JavaScript to switch out
a block of text. Note that although this provides a great deal of typographic flexibility, it
should still be used sparingly—pages where too much text is switched out using sIFR
tend to be extremely sluggish. See sIFR Beauty (www.alvit.de/sifrbeauty/sifr-resources.php)
for resources and Mike Davidson’s site (www.mikeindustries.com/sifr/) for further
information.
Defining font size and line height
In theory, defining font sizes should be easy enough. You use the font-size property, and then you can set
the value to an absolute size, a relative size, a length, or a percentage. For instance, you might set the
following:
www.freepdf-books.com
Working With Type
83
h1 {
font-size: 20px;
}
p {
font-size: 12px;
}
Alternatively, you might go for something like this:
h1 {
font-size: 150%;
}
p {
font-size: 90%;
}
Each method of sizing fonts has its advantages and disadvantages, which we’ll briefly explore in this
section of the book.
Setting text in pixels
Many designers specify font sizes in pixels, largely because pixels are the only measurement that allows
you to be relatively certain that your text will look pretty much identical across various browsers and
platforms (in the same way that sizing page sections in pixels enables you to keep output consistent).
Unfortunately, unlike every other major browser on the market, Internet Explorer for Windows cannot
resize pixel-based text, which creates an accessibility problem (although a user can choose to ignore font
sizes via the little-known accessibility controls). Internet Explorer’s Text Size menu only allows resizing
of text sized using legacy methods, keywords, or relative units other than pixels. (Note that Internet
Explorer 7 can zoom the entire page, but not the text alone.)
Therefore, if you decide to size text in pixels, ensure that your text is very readable. Test it on various
people and listen to feedback. If complaints come your way regarding the fact that someone “had trouble
reading the words” or rooted around for a microscope before giving up and playing solitaire, you need to
increase your pixel size settings. The resulting page might not look quite as “designery,” but at least
people will be able to read it.
Setting text using keywords and percentages
A combination of keywords and percentages became fairly popular for a while on the Web. Available
keyword values are xx-small, x-small, small, medium, large, x-large, and xx-large. A keyword is used to set
the base value, using a body selector in CSS, and percentages are then used to set sizes for specific
elements, such as headings, paragraphs, and lists. Here’s an example:
www.freepdf-books.com
Chapter 3
84
body {
font-size: small;
}
p {
font-size: 93%;
(})
Keyword values don’t compound, and most modern browsers set a lower limit, even on xx-small, so text
tends never to enter the realm of the illegible.
Although Internet Explorer for Windows can resize text set with keywords (as can all other browsers), this
method has several disadvantages. The most problematic from a design perspective is that percentage
values aren’t particularly consistent across browsers and platforms. Scaling tends to “jump” at fairly
arbitrary percentage sizes, so while 93% may look the same in all browsers (using default font-size
settings, at least), 94% may look like 100% in one and 93% in another. Also, it’s often tricky to equate
percentages with the pixel (or point) sizes typically used in mock-ups.
In Internet Explorer, fonts that are set to Small in the ViewText Size menu can make keyword-set
CSS text hard to read, but users can increase the text size by using a more sensible setting. Also, it’s
worth noting that this is up to user choice, and having a tiny minority of users screwing up their own
settings and potentially ending up with unreadable text is better than the vast majority not being able to
resize the text because its size is defined in pixels. Still, there’s a better method for achieving this, as you’ll
see.
Setting text using percentages and ems
As mentioned, the problem with sizing text in pixels is that the text is not resizable in Internet Explorer. The
main problem with using keywords and percentages is that the text size can be different across platforms
and difficult to define—at least in terms of hitting a specific target size. This third method—and the one I
typically use for websites I design—enables you to create font sizes that are targeted at a pixel size but
are also resizable in Internet Explorer, since the measurements are relative units.
The system works by first setting a base font size of 62.5% using a body selector:
body {
font-size: 62.5%;
}
Since most browsers have a default font size of 16 pixels, the previous rule then sets the default size to
62.5% of that value—in other words, 10 pixels. From here, ems can be used to define font sizes of specific
elements, using values that are one-tenth the target pixel size:
www.freepdf-books.com
Working With Type
85
h1 {
font-size: 2.0em; /* will be the equivalent of 20px */
}
p {
font-size: 1.2em; /* will be the equivalent of 12px */
}
The system isn’t perfect—relative values defined in ems can be inherited, so if a list item is within another
list item, the size of the nested item(s) may increase or decrease, depending on the value assigned to the
parent. However, override rules can easily get around this problem (see “Dealing with font-size
inheritance” later in the chapter), and the method generally leads to more satisfactory results from a
design, control, and user point of view than either of the other two methods mentioned. It is worth noting,
however, that this method is somewhat reliant on the user—if someone has changed the default font size
in their browser, your design may not look as intended on their browser, since the value defined for body
may be 62.5% of something other than 16 pixels. Still, few people muck around with their browser settings,
and the general consensus in the industry is that the 62.5% method is the one to go for.
Note: If using this method, ensure that the font-size setting of all text-oriented elements
you use on the site is adjusted; otherwise, you’ll end up with some illegible text set at
62.5% of the default font size. Also ensure you test your work at a range of text sizes in
various browsers to ensure things still look OK if the text is zoomed in or out.
There is one other thing to bear in mind, though: Internet Explorer (again). Although the majority of
browser-specific issues are left until Chapter 9 of this book, we’ll make an exception now. Internet Explorer
has problems with text zooming when the font size is set below 100%, so an additional rule is required:
html {
font-size: 100%;
}
This doesn’t adversely affect other browsers, so you’ll find this rule in the boilerplate documents from the
download files, even though it should technically be in the conditional comments documents.
Setting text using rems
CSS3 has introduced a new sizing unit called the root em unit. The rem unit solves the problem of
inherited ems in nested items by being relative to the root element or the html element of your document.
In the case of rem units, you define a base font size using the html selector:
html {
font-size: 62.5%;
}
All remaining font sizes can be defined as follows:
h1 { font-size: 1.4rem; }
p { font-size: 1.2rem; }
www.freepdf-books.com
Chapter 3
86
It is important to consider older browsers that do not support rem units. This can be done by defining a font
size in pixel units as well as rem units.
h1 { font-size: 14px; font-size: 1.4rem; }
p { font-size: 12px; font-size: 1.2rem; }
Setting line height
Graphic designers will be familiar with leading, and the CSS line-height property enables you to set this.
Generally speaking, it’s a good idea to be fairly generous with leading for web pages, because text is
harder to read on-screen than in print; by placing larger gaps between each line, the eye can more easily
scan through large blocks of text.
When setting line-height, you have various options and can use a number, length, or percentage:
h1 {
font-size: 14px;
line-height: 20px;
}
h2 {
font-size: 1.3em;
line-height: 1.6em;
}
p {
font-size: 1.1em;
line-height: 1.5;
}
The difference between the font-size and line-height measurements is the leading value. Half the value is
applied above the text and half below. Should you use a number alone, rather than a length or percentage,
that value is multiplied by the font-size setting to define the line height. For example, if font-size is set to
10px and line-height is set to 1.5, the line-height value becomes 15px.
Many self-proclaimed web designers who have no graphic design experience ignore the line-height
property, but, as mentioned earlier, it’s essential for improving the legibility of a web page. In the following
screenshots, the left images shows the default spacing, and the right one shows increased line height,
resulting in increased legibility.
www.freepdf-books.com
Working With Type
87
Defining font-style, font-weight, and font-variant
These three properties are straightforward. The first, font-style, enables you to set italic or oblique text.
The former is often a defined face within the font, whereas the latter is usually computed. Typically, web
browsers treat both the same, and only the italic value is in general use (except for the occasional use of
normal—the default value—in order to override something set elsewhere).
An element’s font-style is set like this:
h2 {
font-style: italic;
}
The font-weight property is intended to make a font heavier or lighter, and despite the various available
values, only bold and normal are in general use. This is detailed in full in the font-weight entry of
Appendix D.
.introParagraph {
font-weight: bold;
}
The font-variant property has three available values: normal (the default), small-caps, and inherit. The
inherit value causes this element to use the font-variant settings of its parent element. Small caps are often
used to deemphasize uppercase letters in abbreviations and acronyms and are similar in size to a
typeface’s lowercase characters. This property affects only lowercase letters, and the display of small caps
varies across browsers and platforms—for example, older versions of Internet Explorer simply render such
text entirely in normal caps (in other words, in standard uppercase letters).
When defining a font-face rule, it is important to set font-style and font-weight to normal to ensure that all
browsers default to the same values. Webkit browsers need this definition, or else the font-face rule will
ignore any weight or style commands applied to it.
www.freepdf-books.com
Chapter 3
88
CSS shorthand for font properties
The CSS properties discussed so far can be written in shorthand, enabling you to cut down on space and
manage your CSS font settings with greater ease. Like other shorthand properties, some rules apply:
Some browsers are more forgiving than others regarding required and optional values, but you
should always specify the font-size and font-family values, in that order.
Omitted values revert to default settings.
The font-style, font-weight, and font-variant values, if included, should be placed at the start of the
rule (in any order), prior to the font-size value.
The font-size and line-height values can be combined using the syntax
font-size/line-height (for example, 12px/16px for 12px font-size and 16px
line-height).
A complete font declaration in shorthand could therefore look like this:
p {
font: italic small-caps bold 100%/1.3em Arial, Helvetica,
sans-serif;
}
The equivalent in longhand is the following:
p {
font-style: italic;
font-variant: small-caps;
font-weight: bold;
font-size: 100%;
line-height: 1.3em;
font-family: Arial, Helvetica, sans-serif;
}
As you can see, this is rather weightier!
An invalid font declaration is shown in the following code block. Here, the font-weight value (bold) is
incorrectly placed after the font-family value, and the font-size value is missing.
p.invalid {
font: Arial, Helvetica, sans-serif bold;
}
Controlling text element margins
By default, browsers place margins around block-level text-based elements (such as headings and
paragraphs), which can be overridden by CSS. However, many designers get confused when dealing with
margins, so a good rule of thumb is to first remove all element margins via the universal selector (see the
“Zeroing margins and padding on all elements” section in Chapter 2 for more information).
www.freepdf-books.com
Working With Type
89
* {
margin: 0;
padding: 0;
}
Once you’ve done this, you should primarily control spacing between text elements via the bottom
margins:
h1, h2 {
margin-bottom: 10px;
}
p {
margin-bottom: 1em;
}
In the previous example, the margins below headings are small, enabling the eye to rapidly travel from the
heading to the related body copy. The margin at the bottom of each paragraph is one character high.
Should you decide, after applying styles, that more room is required between paragraphs and subsequent
headings, apply a top margin to the relevant level (or levels) of heading, but be aware that vertical margins
collapse.
Later in the chapter, a few exercises will show how margins (along with various other settings) can affect
the way a page looks and feels. Certainly, margin definitions shouldn’t be throwaway—like in music, where
the gaps are almost as important as the notes, the whitespace in typography is almost as important as the
content.
Using text-indent for print-like paragraphs
Because of people’s familiarity with nonindented paragraphs on the Web, the W3C recommends staying
away from indented ones. However, there are times when designers yearn for a more print-based design,
as in the following image.
www.freepdf-books.com
Chapter 3
90
For this effect, two things not previously discussed in this book are required: the text-indent CSS property
and an adjacent sibling selector. This type of selector uses the syntax A+B, where B is the subject of the
selector. For paragraph indentation, the CSS rule would look something like the following code block:
p+p {
text-indent: 1.5em;
}
In plain English, this is saying, “If a paragraph follows another paragraph, indent the text by 1.5 ems.”
Therefore, paragraphs preceded by a different element, such as a heading, won’t be indented, as is
traditional in print.
Note that prior to version 7, Internet Explorer didn’t support adjacent sibling selectors,
and so this effect won’t work in version 6 or older of Microsoft’s browser. A workaround
would be to use a style sheet linked via a conditional comment to indent all paragraphs
for Internet Explorer 6 and older. See the “Dealing with Internet Explorer bugs” section in
Chapter 9 for more on conditional comments.
Setting letter-spacing and word-spacing
The letter-spacing and word-spacing properties work in the same way, taking length values or a default of
normal. For letter-spacing, the value increases whitespace between characters, and for word-spacing, the
defined value increases whitespace between words. Negative values are permitted, which cause
characters or words to bunch together (or kern, if you’re a graphic designer). A certain amount of
experimentation is recommended if you decide to use these properties. Because the Web’s resolution is
low, subtle kerning changes are hard to achieve online, and the results often end up looking clunky. Also,
spacing varies from platform to platform. One occasion when letter-spacing is worth experimenting with,
however, is when styling headings for web pages: a small increase in the letter-spacing value can help
further distinguish headings from body copy.
Examples of these properties in use are shown in the following code block:
www.freepdf-books.com
Working With Type
91
h1 {
letter-spacing: 3px;
}
h2 {
word-spacing: 2px;
}
Controlling case with text-transform
The text-transform property enables you to change the case of letters within an element. Available values
are capitalize, uppercase, lowercase, and none (the default). The uppercase and lowercase values force
the text of the applied element into the relevant case regardless of the original content (for example,
enabling you to override the case of the original content for ensuring that headings are consistent
sitewide), whereas capitalize sets the first letter of each word in uppercase.
In the following example, the first heading is styled as uppercase, the second as lowercase, and the third
as capitalize. Note that I wouldn’t recommend such a mix of styles in a website—these rules are just
examples of the properties in use.
Here’s the HTML:
<h1>A heading</h1>
<h2>Another heading</h2>
<h3>A third heading</h3>
Here’s the CSS:
h1 {
text-transform: uppercase;
}
h2 {
text-transform: lowercase;
}
h3 {
text-transform: capitalize;
}
Creating alternatives with classes and spans
It’s common in web design to define alternatives to the rules set for tag selectors (h1, h2, p, and so on).
This tends to happen most often in one of two situations. The first is when creating alternate styles for a
portion of a web page. (As in print, it’s often beneficial to use different text for sidebars and boxouts—
stand-alone boxes on a magazine page, either housing supplementary information to the main article or
entirely independent pieces that need to be visually distinct from other content on the page—and sidebars
to ensure that each area of content is easy to distinguish from another.) In this situation, it’s sensible to
define a default rule for each element using an element selector and then create an override for the portion
of the page that requires different text by using a contextual selector.
For example, imagine a typical web page that has a sidebar that’s marked up as an aside with an id value
of sidebar. You might use a different paragraph font in the sidebar to differentiate the text, like so:
www.freepdf-books.com
Chapter 3
92
p {
font: 1.2em/1.5 Verdana, Arial, sans-serif;
margin-bottom: 1em;
}
#sidebar p {
font: 1.2em/1.5 Arial, sans-serif;
}
The other occasion where alternatives are required is when creating one-off styles to override an existing
style. In such cases, you can define a class in the CSS and then use a class attribute to apply it to an
element. Should you want only a portion of some text to take on the style, you can surround the selection
with a span element and apply the class to that instead.
For example, if you wanted to create some “warning” text, you could use the following CSS:
.warning {
color: #ff0000;
font-size: 120%;
}
This can then be applied as follows:
<p class="warning">This paragraph takes on the styles defined in
the warning class</p>
<p>Only <em class="warning">this portion</em> of this
paragraph takes on the warningText class styles.</p>
Avoid overusing span elements, though. Text works best when it’s consistent across the page.
Note that the preceding CSS style has a capital letter halfway through it—this case is
known as lowerCamelCase and is a method of writing multiple-word style names,
because spaces must be avoided in CSS. Take care if you do this, because styles are
case sensitive. If you set a class attribute value to warningtext instead of warningText,
many browsers fail to display the style, reverting to the default style for the relevant
element. It is also important to remember that CSS styles can’t begin with a number.
1Style will not work.
Styling semantic markup
The exercises in this section will combine the elements discussed so far in this chapter, showing how to
use the knowledge gained to style some semantic markup. Three different examples are on offer, showing
how rapidly you can create great-looking text when working with CSS and also how you can easily restyle
a page of text without touching the markup. The markup that you’ll use is per that in the next code block,
and the default web page, without any CSS applied, is shown to its right.
<article class="wrapper">
www.freepdf-books.com
Working With Type
93
<h1>Article heading</h1>
<p>Lorem ipsum dolor sit amet,
consectetuer adipiscing elit. Sed
aliquet elementum erat. Integer
diam mi, venenatis non, cursus
a, hendrerit at, mi. Morbi risus
mi, tincidunt ornare, tempus
ut, eleifend nec, risus.</p>
<p>Quisque faucibus lorem eget sapien.
In urna sem, vehicula ut,
mattis et, venenatis at, velit.
Ut sodales lacus sed eros.
Pellentesque tristique senectus et
netus et malesuada fames
ac turpis egestas.</p>
<h2>Curabitur sit amet risus</h2>
<p>Lorem ipsum dolor sit amet,
consectetuer adipiscing elit. Sed
aliquet elementum erat. Integer
diam mi, venenatis non, cursus
a, hendrerit at, mi. Morbi risus mi,
tincidunt ornare, tempus
ut, eleifend nec, risus.</p>
<p>Quisque faucibus lorem eget sapien. In urna sem, vehicula ut,
mattis et, venenatis at, velit. Ut sodales lacus sed eros.
Pellentesque tristique senectus et netus et malesuada fames
ac turpis egestas.</p>
<h3>Praesent rutrum</h3>
<p>Nam scelerisque dignissim quam. Ut bibendum enim in orci. Vivamus
ligula nunc, dictum a, tincidunt in, dignissim ac, odio.</p>
<h3>Habitant morbid</h3>
<p>Nam scelerisque dignissim quam. Ut bibendum enim in orci. Vivamus
ligula nunc, dictum a, tincidunt in, dignissim ac, odio.</p>
</article>
The code block is simple. The text has three levels of headings, with paragraphs between them.
Everything is enclosed in an article element, which will be styled to restrict the width of its content. This
makes it simpler to see how the leading—defined via line-height—is working out. If you were surfing at full-
screen on a large monitor, the paragraphs might be shown on only a single line.
The default CSS document for these exercises has some rules common to all three examples. These are
shown in the following code block:
* {
margin: 0;
padding: 0;
}
html {
www.freepdf-books.com
Chapter 3
94
font-size: 100%;
}
body {
padding: 20px;
font-size: 62.5%;
}
.wrapper {
margin: 0 auto;
width: 400px;
}
The first rule, *, removes margins and padding from all elements, as discussed previously. The html and
body rules set the default size of the text on the web page to 62.5%, as explained in the “Setting text using
percentages and ems” section earlier in this chapter. Finally, the .wrapper rule defines a width for the
wrapper article and therefore for its content.
Styling semantic markup: A basic example with proportional line heights
Required files styling-semantic-text-starting-point.html and styling-semantic-text-starting-point.css
from the chapter 3 folder
What you’ll learn How to style headings and paragraphs using sans-serif fonts (Verdana for body copy
and Arial for headings) and proportional, unitless line-height settings
Completed files styling-semantic-text-1.html and styling-semantic-text-1.css from the chapter 3 folder
1. Define the font defaults. Using a body selector, define a default font for the web page, along with
a default line-height value. Because this is a basic example, Verdana is used as the primary font,
falling back to Arial and Helvetica. The unitless line-height value means that elements will have
proportional line heights based on their font-size values, unless otherwise stated.
body {
font-family: Verdana, Arial, Helvetica, sans-serif;
line-height: 1.5;
}
Note: In the CSS, you’ll end up with two body selectors if you follow this to the letter—
one for dealing with padding and setting the default font size to 62.5% and the other for
defining the default font-family value for the page, along with the line-height. This enables
these exercises to remain modular; in a real site, although it’s acceptable to use
selectors more than once, you should ensure property values and rules are correctly
housed in the relevant section of your boilerplates—see Chapter 10 and Appendix D for
more information on CSS management.
www.freepdf-books.com
Working With Type
95
2. Define common settings for headings. In this example, the top two levels of headings will have
the same font-family value. Therefore, it makes sense to use a grouped selector to define this
property:
h1, h2 {
font-family: Arial, Helvetica, sans-serif;
}
3. Define specific values for headings. How you style headings will depend on their purpose. For
these exercises, h1 is the page heading, h2 is a subheading, and h3 is a crosshead to introduce
a section of copy. With that in mind, the crosshead needs to be of similar size to the paragraphs,
the main heading needs to be most prominent, and the subheading needs to be somewhere in
between. Therefore, in the CSS, the h1 element has a font-size value of 2.5em, the h3 has a
much smaller 1.2em, and the h2 has an in-between 2em.
h1 {
font-size: 2.5em;
}
h2 {
font-size: 2em;
}
h3 {
font-size: 1.2em;
}
4. Style the paragraphs using the following rule. Whereas the space around headings is taken care
of with the line-height setting defined in the body selector, that doesn’t work for paragraphs, which
must have distinct space between them. Therefore, along with a font-size property/value pair, a
margin-bottom value sets the space between each paragraph to slightly more than the height of
one character.
p {
font-size: 1.1em;
margin-bottom: 1.1em;
}
5. Refine the element spacing. At this point, the spacing is still a little suspect—the crossheads don’t
stand out enough. Therefore, add a margin-top value to the h3 rule; this provides a little extra
space between paragraphs and level-three headings. (As mentioned earlier, vertical margins
collapse, so the space between a paragraph with a bottom margin of 1.1em and a level-three
heading with a top margin of 1.65em is 1.65em, not the sum of the two margins, which would be
2.75em.)
h3 {
font-size: 1.2em;
margin-top: 1.65em;
}
h3, p {
margin-left: 1em;
}
www.freepdf-books.com
Chapter 3
96
The following image shows what your completed page should look like.
Required files styling-semantic-text-starting-point.html and styling-semantic-text-starting-point.css
from the chapter 3 folder
What you’ll learn How to create a contemporary-looking page of text using Lucida fonts, as per the text
on Apple’s website
Completed files styling-semantic-text-2.html and styling-semantic-text-2.css from the chapter 3 folder
1. Set the font defaults. As in the previous exercise, use a body rule to define the default font for the
page, the first couple of choices of which are Lucida variants that are installed on Mac OS and
Windows. Other fonts are provided for legacy or alternate systems.
body {
font-family: "Lucida Grande", "Lucida Sans Unicode", Lucida, Arial,
Helvetica, sans-serif;
line-height: 1.5;
}
www.freepdf-books.com
Working With Type
97
2. Style the main heading. An h1 rule is used to style the main heading. The restrictive value for
line-height makes the leading value the height of one character of the heading, meaning there’s
no space underneath it. This means you can define an explicit padding-bottom value, followed by
a border-bottom (here, 1 pixel, solid, and very light gray), followed by a margin-bottom value. The
padding-bottom and margin-bottom values are the same, creating a very tight, clean feel for the
heading. Elsewhere, the color setting knocks it back slightly so that it doesn’t overpower the other
content, and the font-weight value removes the default bold setting that browsers apply to
headings. This helps the block of text appear light and clean.
h1 {
font-size: 1.8em;
line-height: 1em;
padding-bottom: 7px;
border-bottom: 1px solid #cccccc;
margin-bottom: 7px;
color: #666666;
font-weight: normal;
}
Tip: When removing the default bold style from headings, check them across
platforms—on some Windows systems, nonbold headings can look a bit spindly,
depending on the settings.
3. Style the other headings. For the next two heading levels, font-size values are assigned. In
keeping with the modern style, the crossheads are the same size as the paragraph text (styled in
the next step)—just displayed in bold; the subheading (h2) is slightly larger, making it a little more
prominent. Again, the headings are colored to make them blend in a little more and not distract
from the paragraph text.
h2, h3 {
color: #333333;
}
h2 {
font-size: 1.3em;
}
h3 {
font-size: 1.2em;
margin-top: 1.65em;
}
4. Style the paragraphs. The font-size setting is larger than that used on many websites (which
typically tend toward 11 pixels, which would require a 1.1em value in this example), but this
ensures clarity and, again, enhances the clean nature of the design.
p {
font-size: 1.2em;
margin-bottom: 1.2em;
}
www.freepdf-books.com
Chapter 3
98
5. The final rule—an adjacent sibling selector—styles the paragraph following the main heading,
making the intro paragraph bold. It’s colored a dark gray, rather than black, which would be
overpowering and wreck the balance of the page.
h1+p {
font-weight: bold;
color: #222222;
}
The following image shows what your completed page should look like.
Required filesstyling-semantic-text-starting-point.html and styling-semantic-text-starting-point.css and
styling-semantic-text baseline.gif from the chapter 3 folder
What you’ll learn How to create a page of traditional-looking text as per a printed book. The text
adheres strictly to a baseline grid, maintaining the page’s vertical rhythm. This requires
some extra calculations when it comes to defining line-height values.
Completed files styling-semantic-text-3.html and styling-semantic-text-3.css from the chapter 3 folder
www.freepdf-books.com
Working With Type
99
1. Define a default font for the page. Using a body rule, a default font is chosen for the web page.
This design primarily uses the Georgia font—a serif—to enhance the traditional feel.
body {
font-family: Georgia, "Times New Roman", Times, serif;
}
2. At this point, it’s also important to decide on a target line-height value for the page. For this
example, it’s going to be 18px.
3. Style the main heading. Here’s where things get a little tricky. For these examples, we’re working
with relative units. As mentioned earlier in the chapter, the 62.5% method means that you can
define font sizes by setting the font-size value to a setting in ems that’s one-tenth of the target
size in pixels. So, in the following code block, the h1 rule’s font-size value of 1.8em means it’s
effectively displayed at 18 pixels (assuming the user hasn’t messed around with their browser’s
default settings, again as mentioned earlier).
4. For the line-height value to hit the target of 18 pixels, it must therefore be 18 pixels or a multiple
of it. However, when using ems, this value is relative to the font-size value. One em is equal to
the height of one character, and since the font-size has been set to 1.8em (which is equivalent to
18 pixels), we set line-height to 1em. This makes the line-height of the h1 element the equivalent
of 18 pixels.
5. Similar thinking is used to define the value for margin-bottom—this needs to be 18 pixels to keep
the vertical rhythm going, so the value is set to 1em.
h1 {
font-size: 1.8em;
line-height: 1em;
margin-bottom: 1em;
}
6. Style the subheading. For the subheading, the font-size value is set to 1.4em. To keep the line-
height vertical rhythm going, you need to find the value that will multiply with the font-size setting
to create 1.8 (since 1.8em is the equivalent of 18 pixels). You can get this by dividing 1.8 by the
font-size value, which results in a line-height value of 1.2857142em. To keep the rhythm going,
this setting can then be used for both the margin-top and margin-bottom values.
h2 {
font-size: 1.4em;
line-height: 1.2857142em;
margin-top: 1.2857142em;
margin-bottom: 1.2857142em;
}
7. However, what this serves to do is isolate the heading on its own line, rather than making it
obviously lead to the subsequent paragraph. Two solutions exist for dealing with this. The first is
simply to remove the bottom margin; the second is to create asymmetrical margins, making the
top margin larger than the bottom one. To keep the entire space the element takes up strictly
within the grid and not interrupt the vertical rhythm too much, it’s sensible to take half the margin-
bottom value and add it to the margin-top value.
www.freepdf-books.com
Chapter 3
100
h2 {
font-size: 1.4em;
line-height: 1.2857142em;
margin-top: 1.9285713em;
margin-bottom: 0.6428571em;
}
8. Style the crossheads and paragraphs. For this example, the crossheads and paragraphs are
identical, save for the default styling on the headings that renders them in bold. The font-size
value is 1.2em. Again, 1.8 is divided by the font-size figure to arrive at the line-height and margin
values, both of which are set to 1.5em. Note that the h3 rule has no margin-bottom value,
meaning that each level-three heading hugs the subsequent paragraph.
h3 {
font-size: 1.2em;
line-height: 1.5em;
margin-top: 1.5em;
}
p {
font-size: 1.2em;
line-height: 1.5em;
margin-bottom: 1.5em;
}
At this point, your page should look like the following image.
www.freepdf-books.com
Working With Type
101
9. Add a (temporary) grid. When working on text that adheres to a baseline grid, it can help to create
a tiled background image that you can use to check whether your measurements are accurate.
The 18-pixel-high image file, styling-semantic-text-baseline.gif, has a single-pixel line at the
bottom of the image. When applied to the wrapper article’s background via the .wrapper rule (see
the following code), a ruled background is shown. Although intended as a temporary design aid,
you could retain the grid permanently, because it can help readers to rapidly skim text. However,
the aid works only when a browser is using default settings—when the text is enlarged, the
background image stays as it is, resulting in the grid of the image and the grid of the text being
out of sync.
.wrapper {
margin: 0 auto;
width: 400px;
background: url(styling-semantic-text-baseline.gif);
}
www.freepdf-books.com
Chapter 3
102
The following image shows how this image works behind the text styled in this exercise—as you can see,
the vertical rhythm is maintained right down the page.
Creating drop caps and pull quotes using CSS
The previous exercise showed how something aimed primarily at the world of print design—a baseline
grid—can actually work well online, and this section will continue that theme, showing how to use CSS to
create drop caps and pull quotes. Drop caps—large letters typically used at the start of a printed article—
are rare online, although they can be a useful way of drawing the eye to the beginning of the body copy.
Pull quotes are more common, and while part of their use in print—taking a choice quote and making it
stand out on the page to draw in the reader—is less effective online, pull quotes are still handy for
highlighting a piece of text (such as a quote or idea) or for providing client quotes on a company website.
Creating a drop cap using a CSS pseudo-element
Required files styling-semantic-text-2.html and styling-semantic-text-2.css from the chapter 3
folder.
www.freepdf-books.com
Working With Type
103
What you’ll learn How to create a drop cap for a website and how to use the CSS float property. Any
element can be floated left or right in CSS, and this causes subsequent content to
wrap around it.
Completed files drop-cap.html and drop-cap.css from the chapter 3 folder.
1. Create a new rule that targets the relevant character. For this, you can use a pseudo-element,
first-letter, and the adjacent sibling selector created earlier in the “Styling semantic markup”
section. See Appendix D for more on pseudo-elements.
h1+p:first-letter {
}
2. In plain English, this rule is saying, “Apply this rule to the first letter of the paragraph that follows
the level-one heading.”
3. Float the character and increase its size. Add a float: left property/value pair to float the first
character in the paragraph to the left, which makes subsequent content wrap around it. Then set
a large font-size value to increase the size of the character compared to the surrounding text.
h1+p:first-letter {
float: left;
font-size: 3em;
}
4. Finally, tweak the positioning. Define a line-height value and margin-top value to vertically
position the character; you may need to experiment some when working on your own designs
outside of this exercise, since the values required are somewhat dependent on the font-size
setting. The margin-right setting provides some spacing between the drop cap and the
subsequent text.
h1+p:first-letter {
float: left;
font-size: 3em;
line-height: 1.0em;
margin-top: -3px;
margin-right: 0.15em;
}
Note that you can use the first-line pseudo-element to target the first line of some text—
for example, to make it bold, which is a commonly used design element in magazines.
Although this technique is the most straightforward one for working with drop caps, the results aren’t
entirely satisfactory. Because of the way different browsers deal with the first-letter pseudo-element, the
display isn’t particularly consistent across browsers and platforms—see the following two images, which
show the results in Firefox and Safari. Therefore, if you want to use drop caps with more precision, it’s best
to fall back on a more old-fashioned but tried-and-tested method: the span element.
www.freepdf-books.com
Chapter 3
104
Required files styling-semantic-text-2.html, styling-semantic-text-2.css, quote-open.gif, and quote-
close.gif from the chapter 3 folder
What you’ll learn How to create a magazine-style pull quote, which can draw the user’s attention to a
quote or highlight a portion of an article
Completed files pull-quote.html and pull-quote.css from the chapter 3 folde
1. Add the HTML. The required markup for a basic pull quote is simple, centering around the
blockquote element and nesting a paragraph within. Add the following to the web page, above the
code <h2>Curabitur sit amet risus</h2>:
<blockquote>
<p>This is the pull quote. It's really very exciting, so read it now!
Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</p>
</blockquote>
2. Style the blockquote element. Create a blockquote rule and use the background property to add
the open quote image as its background. Set vertical margins that are larger than the margins
between the paragraphs (to ensure that the pull quote stands out from the surrounding text) and
the horizontal margins (to ensure that the pull quote doesn’t span the entire column width, which
also helps it visually stand out).
blockquote {
background: url(quote-open.gif) 0 0 no-repeat;
margin: 2.4em 2em;
}
3. Style the pull quote paragraph text. Using the contextual selector blockquote p, style the
paragraph text within the blockquote element. Making the text bold and larger than the
surrounding copy helps it stand out—but to ensure it doesn’t become too distracting, knock back
its color a little.
blockquote p {
color: #555555;
font-size: 1.3em;
font-weight: bold;
text-align: justify;
}
4. Use the background property to add the closing quote mark, which is added to the paragraph,
since you can add only one background image to an element in CSS. The background’s position
is set to 100% 90%—far right and almost at the bottom. Setting it at the absolute bottom would
www.freepdf-books.com
Working With Type
105
align the closing quote with the bottom of the leading under the last line of the paragraph text;
setting the vertical position value to 90%, however, lines up the closing quote with the bottom of
the text itself.
blockquote p {
color: #555555;
font-size: 1.3em;
font-weight: bold;
text-align: justify;
background: url(quote-close.gif) 100% 90% no-repeat;
}
5. Tweak the positioning. If you test the page now, you’ll see the paragraph content appearing over
the top of the background images. To avoid this, padding needs to be applied to the quote mark
to force its content inward but still leave the background images in place. Since the quote images
are both 23 pixels wide, a horizontal padding value of 33px provides room for the images and
adds an additional 10 pixels so that the content of the paragraph doesn’t abut the quote marks.
Finally, the default margin-bottom value for paragraphs is overridden (via a 0 value), since it’s
redundant here.
blockquote p {
color: #555555;
font-size: 1.3em;
font-weight: bold;
text-align: justify;
background: url(quote-close.gif) 100% 90% no-repeat;
padding: 0 33px;
margin-bottom: 0;
}
The following image shows your pull quote page so far.
6. Next, credit the quotation. To add a credit to the quote, add another paragraph, with a nested cite
element, inside which is the relevant content.
<blockquote>
<p>This is the pull quote. It's really very exciting, so read it now!
Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</p>
<p><cite>fredbloggs.com</cite></p>
</blockquote>
www.freepdf-books.com
Chapter 3
106
7. In CSS, add the following rule:
cite {
background: none;
display: block;
text-align: right;
font-size: 1.1em;
font-weight: normal;
font-style: italic;
}
8. Some of the property values in cite are there to override the settings from blockquote p and to
ensure that the second paragraph’s text is clearly distinguishable from the quote. However, at this
point, both paragraphs within the blockquote element have the closing-quote background, so a
final rule is required.
blockquote>p+p {
background: none;
}
9. This fairly complex rule uses both a child selector (>) and an adjacent selector (+) and styles the
paragraph that comes immediately after the paragraph that’s a child element of the blockquote
(which is the paragraph with the cite element). The rule overrides the background value defined in
step 5 for paragraphs within the block quote. Note that this assumes the quote itself will be only a
single paragraph. If you have multiparagraph quotes, you’ll need to apply a class to the final
paragraph and set the quote-close.gif image as a background on that, rather than on
blockquote p.
Using classes and CSS overrides to create an alternate pull quote
Required files pull-quote.html and pull-quote.css from the chapter 3 folder.
What you’ll learn How to use CSS classes to create alternatives to the default pull quote. In this
example, you’ll create a narrow pull quote that floats to the right of the body copy.
Completed files pull-quote-2.html and pull-quote-2.css from the chapter 3 folder.
1. Amend the HTML. First, add a class to the blockquote element so that it can be targeted in CSS:
www.freepdf-books.com
Working With Type
107
<blockquote id="fredBloggs">
2. Position the blockquote. Create a new CSS rule that targets the blockquote from the previous
step by using the selector #fredBloggs. Set float and width values to float the pull quote and
define its width.
#fredBloggs {
float: right;
width: 150px;
}
3. Remove the quote mark background image by setting background to none. Add the two border
property/value pairs shown to visually separate the pull quote from its surroundings, drawing the
eye to its content.
#fredBloggs {
float: right;
width: 150px;
background: none;
border-top: 5px solid #dddddd;
border-bottom: 5px solid #dddddd;
}
4. Add padding and margins. First, add vertical padding to ensure that the pull quote’s contents
don’t hug the borders added in the previous step. Next, define margin values, overriding those set
for the default blockquote from the previous exercise. Because this alternate pull quote is floated
right, there’s no need for top and right margins, which is why they’re set to 0; the bottom and left
margin values are left intact.
#fredBloggs {
float: right;
width: 150px;
background: none;
border-top: 5px solid #dddddd;
border-bottom: 5px solid #dddddd;
padding: 10px 0;
margin: 0 0 2em 2.4em;
}
5. Override the paragraph styles. The background and padding settings for the default blockquote
style are no longer needed, so they’re set to none and 0, respectively. Finally, text-align is set to
center, which is appropriate for a narrow pull quote such as this.
#fredBloggs p {
text-align: center;
background: none;
padding: 0;
}
6. Use pseudo-elements to add quotation marks before and after the blockquote contents.
www.freepdf-books.com
Chapter 3
108
#fredBloggs:before {
content: open-quote;
}
#fredBloggs:after {
content: close-quote;
}
Adding reference citations
The blockquote element can have a cite attribute, and the content from this attribute can be displayed by
using the following CSS rule:
blockquote[cite]:after {
display : block;
margin : 0 0 5px;
padding : 0 0 2px 0;
font-weight : bold;
font-size : 90%;
content : "[source: "" " attr(cite)"]";
}
Working with lists
This chapter concludes with the last of the major type elements: the list. We’ll first look at the different
types of lists—unordered, ordered, and definition—and also see how to nest them. Then we’ll move on to
cover how to style lists in CSS, list margins and padding, and inline lists.
Unordered lists
The unordered list, commonly referred to as a bullet point list, is the most frequently seen type of list
online. The list is composed of an unordered list element (<ul></ul>) and any number of list items within,
each of which looks like this (prior to content being added): <li></li>. An example of an unordered list
www.freepdf-books.com
Working With Type
109
follows, and the resulting browser display is shown to the right. As you can see, browsers typically render
a single-level unordered list with solid black bullet points.
<ul>
<li>List item one</li>
<li>List item two</li>
<li>List item 'n'</li>
</ul>
Ordered lists
On occasion, list items must be stated in order, whereupon an ordered list is used. It works in the same
way as an unordered list, the only difference being the containing element, which is <ol></ol>.
<ol>
<li>List item one</li>
<li>List item two</li>
<li>List item 'n'</li>
</ol>
Note: Web browsers automatically insert the item numbers when you use ordered lists.
The only way of controlling numbering directly is via the start attribute, whose value
dictates the first number of the ordered list.
Definition lists
A definition list isn’t a straightforward list of items. Instead, it’s a list of terms and explanations. This type of
list isn’t common online, but it has its uses. The list is enclosed in the definition list element (<dl></dl>),
and within the element are terms and definitions, marked up with <dt></dt> and <dd></dd>, respectively.
Generally speaking, browsers display the definition with an indented left margin, as in the following
example:
<dl>
<dt>Cat</dt>
<dd>Four-legged, hairy animal, with an
inflated sense of self-importance</dd>
<dt>Dog</dt>
<dd>Four-legged, hairy animal, often with
an inferiority complex</dd>
</dl>
Nesting lists
Lists can be nested, but designers often do so incorrectly, screwing up their layouts and rendering web
pages invalid. The most common mistake is placing the nested list outside any list items, as shown in the
following incorrect example:
www.freepdf-books.com
Chapter 3
110
<ul>
<li>List item one</li>
<ul>
<li>Nested list item one</li>
<li>Nested list item two</li>
</ul>
<li>List item two</li>
<li>List item 'n'</li>
</ul>
Nested lists must be placed inside a list item, after the relevant item that leads into the nested list. Here’s
an example:
<ul>
<li>List item one
<ul>
<li>Nested list item one</li>
<li>Nested list item two</li>
</ul>
</li>
<li>List item two</li>
<li>List item 'n'</li>
</ul>
Always ensure that the list element that contains the nested list is closed with an end tag. Not doing so is
another common mistake, and although it’s not likely to cause as many problems as the incorrect
positioning of the list, it can still affect your layout.
Styling lists with CSS
Lists can be styled with CSS, making it easy to amend item spacing or create custom bullet points. I tend
to think bullet points work well for lists. They’re simple and—pardon the pun—to the point. However, I
know plenty of people would rather have something more visually interesting, which is where the list-style-
image property comes in.
list-style-image property
The list-style-image property replaces the standard bullet or number from an unordered or ordered list with
whatever image you choose. If you set the following in your CSS, the resulting list will look like that shown
to the right. (Note that this is the nested list created earlier in this chapter.)
www.freepdf-books.com
Working With Type
111
ul {
list-style-image: url(bullet.gif);
}
Contextual selectors were first mentioned in Chapter 1 (see the section
“Types of CSS selectors”). These enable you to style things in context,
and this is appropriate when working with lists. You can style list items with one type of bullet and nested
list items with another. The original rule stays in place but is joined by a second rule:
ul {
list-style-image: url(bullet.gif);
}
ul ul {
list-style-image: url(bullet-level-two.gif);
}
This second rule’s selector is ul ul, which means that the declaration is
applied only to unordered lists within an unordered list (that is, nested lists). The upshot is that the top-
level list items remain with the original custom bullet, but the nested list items now have a different bullet
graphic.
With this CSS, each subsequent level would have the nested list bullet point, but it’s feasible to change the
bullet graphic for each successive level by using increasingly complex contextual selectors.
Note: When using custom bullet images, be wary of making them too large. Some
browsers clip the bullet image, and some place the list contents at the foot of the image.
In all cases, the results look terrible.
Dealing with font-size inheritance
Most of the font-size definitions in this chapter (and indeed, in this book) use relative units. The problem
with using ems, however, is that they compound. For example, if you have a typical nested list like the one
just shown and you define the following CSS, the first level of the list will have text sized at 1.5em; but the
second-level list is a list within a list, so its font-size value will be compounded (1.5 1.5 = 2.25em).
html {
font-size: 100%;
}
body {
font-size: 62.5%;
font-family: Verdana, Arial,
Helvetica, sans-serif;
}
li {
font-size: 1.5em;
}
www.freepdf-books.com
Chapter 3
112
The simple workaround for this is to use a contextual selector—li li—to set an explicit font-size value for list
items within list items, as shown in the following rule:
li li {
font-size: 1em;
}
With this, all nested lists take on the same font-size value as the parent list, which in this case is 1.5em.
list-style-position property
This property has two values: inside and outside. The latter is how list items are usually displayed: the
bullet is placed in the list margin, and the left margin of the text is always indented. However, if you use
inside, bullets are placed where the first text character would usually go, meaning that the text will wrap
underneath the bullet.
list-style-type property
The list-style-type property is used to amend the bullets in an unordered or ordered list, enabling you to
change the default bullets to something else (other than a custom image). In an unordered list, this
defaults to disc (a black bullet), but other values are available, such as circle (a hollow disc bullet), square
(a square bullet), and none, which results in no bullet points. For ordered lists, this defaults to decimal
(resulting in a numbered list), but a number of other values are available, including lower-roman (i, ii, iii,
and so on) and upper-alpha (A, B, C, and so on). A full list of supported values is in Appendix D.
Generally speaking, the values noted are the best supported, along with the upper and lower versions of
roman and alpha for ordered lists. If a browser doesn’t understand the numbering system used for an
ordered list, it usually defaults to decimal. The W3C recommends using decimal whenever possible,
because it makes web pages easier to navigate. I agree—things like alpha and roman are too esoteric for
general use, plus there’s nothing in the CSS specifications to tell a browser what to do in an alphabetic
system after z is reached (although most browsers are consistent in going on to aa, ab, ac, and so on).
List-style shorthand
As elsewhere in CSS, there is a shorthand property for list styles, and this is the aptly named list-style
property. An example of its use is shown in the following piece of CSS:
ul {
list-style-type: square;
list-style-position: inside;
list-style-image: url(bullet.gif);
}
which can be rewritten as follows:
ul {
list-style: square inside url(bullet.gif);
}
www.freepdf-books.com
Working With Type
113
List margins and padding
Browsers don’t seem to be able to agree on how much padding and margin to place around lists by
default, and also how margin and padding settings affect lists in general. This can be frustrating when
developing websites that rely on lists and pixel-perfect element placement. By creating a list and using
CSS to apply a background color to the list and a different color to list items and then removing the page’s
padding and margins, you can observe how each browser creates lists and indents the bullet points and
content.
In Gecko and Webkit browsers (for example, Mozilla Firefox), Chrome, Opera, and Safari, the list
background color is displayed behind the bullet points, which suggests that those browsers place bullet
points within the list’s left padding (because backgrounds extend into an element’s padding). Internet
Explorer shows no background color there, suggesting it places bullet points within the list’s left margin.
This is confirmed if you set the margin property to 0 for a ul selector in CSS. The list is unaffected in all
browsers but Internet Explorer, in which the bullets abut the left edge of the web browser window.
Conversely, setting padding to 0 makes the same thing happen in Gecko browsers, Safari, and Opera.
To get all browsers on a level playing field, you must remove margins and padding, which, as mentioned
previously in this book, is done in CSS by way of the universal selector:
* {
margin: 0;
padding: 0;
}
With this in place, all browsers render lists in the same way, and you can set specific values as
appropriate. For example, bring back the bullet points (which may be at least partially hidden if margins
and padding are both zeroed) by setting either the margin-left or padding-left value to 1.5em (that is, set
margin: 0 0 0 1.5em or padding: 0 0 0 1.5em). The difference is that if you set padding-left, any
background applied to the list will appear behind the bullet points, but if you set margin-left, it won’t. Note
that 1.5em is a big enough value to enable the bullet points to display (in fact, lower values are usually
sufficient, too—although take care not to set values too low, or the bullets will be clipped); setting a higher
value places more space to the left of the bullet points.
Inline lists for navigation
Although most people think of lists as being vertically aligned, you can also display list items inline. This is
particularly useful when creating navigation bars, as you’ll see in Chapter 5. To set a list to display inline,
you simply add display: inline; to the li selector. Adding list-style-type: none; to the ul selector ensures that
the list sits snug to the left of its container (omitting this tends to indent the list items). Adding a margin-
right value to li also ensures that the list items don’t sit right next to each other. Here’s an example:
ul {
list-style-type: none;
}
li {
display: inline;
margin-right: 10px;
www.freepdf-books.com
Chapter 3
114
}
Thinking creatively with lists
The final part of this chapter looks at creating lists with a little panache. Although most lists are perfectly
suited to straightforward bullet points, sometimes some added CSS and imagery can go a long way.
Creating better-looking lists
Required files The HTML and CSS documents from the basic-boilerplates folder as a starting
point, along with the images better-list-hollow-square.gif, better-list-shadow.gif, better-
list-square.gif, and better-list-star.gif from the chapter 3 folder
What you’ll learn How to style a three-level list to look great, using background images and overrides
Completed files better-looking-lists.html and better-looking-lists.css from the chapter 3 folder
1. Create the list. Within the HTML document’s wrapper div, add the following code:
<ul>
<li>List - 1.1
<ul>
<li>List - 2.1</li>
<li>List - 2.2
<ul>
<li>List - 3.1</li>
<li>List - 3.2</li>
<li>List - 3.3</li>
</ul>
</li>
<li>List - 2.3</li>
</ul>
</li>
</ul>
2. Amend the body rule. Add some padding to the body element so that page content doesn’t hug
the browser window edges during testing:
body {
font: 62.5%/1.5 Verdana, Arial, Helvetica, sans-serif;
padding: 20px;
}
3. Style the list elements. This kind of heavily styled list typically requires you to define specific
property values at one level and then override them if they’re not required for subsequent levels.
This is done by adding the three rules in the following code block. For this example, the top level
of the list (styled via ul) has a star background image that doesn’t repeat (the 1px vertical value is
used to nudge the image into place so it looks better positioned), and the list-style-type value of
none removes the default bullet points of all lists on the page.
www.freepdf-books.com
Working With Type
115
For the second level of lists (the first level of nesting), styled via ul ul, a horizontally tiling background
image is added, giving the impression that the top-level list is casting a soft shadow. The border-left setting
creates a soft boundary to the nested list’s left, thereby enclosing the content. The padding value ensures
that there’s space around nested lists.
For the third level of lists (the second level of nesting—that is, a nested list within a nested list), styled via
ul ul ul, no specific styles are required, but to deal with inherited styles from ul ul, background is set to
none and border-left is set to 0. If this weren’t done, third-level lists would also have the shadow
background and dotted left-hand border.
ul {
list-style-type: none;
background: url(better-list-star.gif) 0 1px no-repeat;
}
ul ul {
background: url(better-list-shadow.gif) repeat-x;
border-left: 1px dotted #aaaaaa;
padding: 10px;
}
ul ul ul {
background: none;
border-left: 0;
}
4. Style the list item elements. For the top-level list items, the li rule styles them in uppercase, adds
some padding (to ensure the items don’t sit over the background image applied in ul), and makes
the text bold and gray. For the nested list items, the li li rule overrides the text-transform property,
returning the text to sentence case, and adds a square gray bullet as a background image. The
font-weight value is an override, and the color setting is darker than for the parent list’s list items
so that the nonbold text of the nested list items stand out. Finally, for the third-level list items,
styled using the selector li li li, a background override provides a unique bullet point image (a
hollow square).
li {
text-transform: uppercase;
padding-left: 20px;
font-weight: bold;
color: #666666;
}
li li {
text-transform: none;
background: url(better-list-square.gif) 0 2px no-repeat;
font-weight: normal;
color: #333333;
}
li li li {
background: url(better-list-hollow-square.gif) 0 2px no-repeat;
}
www.freepdf-books.com
Chapter 3
116
Note: When creating lists such as this, don’t overcomplicate things, and try to avoid
going to many levels of nesting or combining ordered and unordered lists; otherwise, the
selectors required for overrides become extremely complicated.
Required files The HTML and CSS documents from the basic-boilerplates folder as a starting point
What you’ll learn How to style a list for displaying code online (complete with exercise headings and line
numbers)
Completed files display-code-online.html and display-code-online.css from the chapter 3 folder
1. Create the list. Code blocks require terminology and descriptions, meaning that a definition list
can be used to mark them up. For this example, the code block from the preceding “List style
shorthand” section will be used. Within the wrapper div, create a definition list and give it a class
value of codeList. For the term, add a description of the code, and for the definition, add an
ordered list, with each line of code within its own list item. Each line of code should also be
nested within a code element.
<dl class="codeList">
<dt>Writing out list styles in full</dt>
<dd>
<ol>
<li><code>ul {</code></li>
<li><code>list-style-type: square;</code></li>
<li><code>list-style-position: inside;</code></li>
<li><code>list-style-image: url(bullet.gif);</code></li>
<li><code>}</code></li>
</ol>
</dd>
</dl>
2. Amend the body and #wrapper CSS rules, adding some padding to the former (so the content
doesn’t hug the browser window edges during testing) and a shorthand font definition to the latter
(in place of existing content).
www.freepdf-books.com
Working With Type
117
body {
font: 62.5%/1.5 Verdana, Arial, Helvetica, sans-serif;
padding: 20px;
}
#wrapper {
font: 1.2em/1.5em 'Lucida Grande', 'Lucida Sans Unicode', Lucida,
Arial, Helvetica, sans-serif;
}
3. Style the list. Add the following rule, which adds a solid border around the definition list that has a
codeList class value:
.codeList {
border: 1px solid #aaaaaa;
}
4. Style the definition term element. Add the following rule, which styles the dt element. The rule
colors the background of dt elements within any element with a class value of codeList and also
adds some padding so the content of the dt elements doesn’t hug their borders. The font-weight
value of bold ensures the content stands out, while the border-bottom value will be used as a
device throughout the other rules, separating components of the design with a fairly thin white
line.
.codeList dt {
background: #dddddd;
padding: 7px;
font-weight: bold;
border-bottom: 2px solid #ffffff;
}
5. Style the list items within the ordered list by adding the following rule. The
margin-left value places the bullets within the definition list, rather than outside of it.
.codeList li {
background: #ffffff;
margin-left: 2.5em;
}
Note that in Internet Explorer, the bullets typically display further to the left than in other
browsers. This behavior can be dealt with by overriding the margin-left value of .codeList
li in an IE-specific style sheet attached using a conditional comment—see Chapter 9 for
more on this technique.
6. Finally, style the code elements. The background value is slightly lighter than that used for the dt
element, ensuring that each element is distinct. By setting display to block, the code elements
stretch to fill their container (meaning that the background color also does this). The borders
ensure that each line of code is visibly distinct, and the border-right setting essentially provides a
border all the way around the code lines, seeing as the border-bottom setting in .codeList dt
defines one at the top of the first line of code. The font is set to a monospace font, and the
padding values place some space around the code, making it easier to read.
www.freepdf-books.com
Chapter 3
118
.codeList code {
background: #eaeaea;
display: block;
border-bottom: 2px solid #ffffff;
border-right: 2px solid #ffffff;
font : 1.2em "Courier New", Courier, monospace;
padding: 2px 10px;
}
That just about wraps things up for online type. After all that text, it’s time to change track. In Chapter 4,
you’ll look at working with images on the Web, and in Chapter 5, you’ll combine what you’ve learned so far
and add anchors into the mix to create web navigation.
4
www.freepdf-books.com
119
Chapter 4
Working With Images
In this chapter:
Understanding color theory
Choosing the best image format
Avoiding common mistakes
Working with images in HTML5
www.freepdf-books.com
Chapter 4
120
Using alt text to improve accessibility
Using CSS when working with images
Displaying a random image from a selection
Introduction
Although text makes up the bulk of the Web’s content, it’s inevitable that you’ll end up working with images
at some point—that is, unless you favor terribly basic websites akin to those last seen in 1995. Images are
rife online, comprising the bulk of interfaces, the navigation of millions of sites, and a considerable amount
of actual content, too. As the Web continues to barge its way into every facet of life, this trend can only
continue; visitors to sites now expect a certain amount of visual interest, just as readers of a magazine
expect illustrations or photographs.
Like anything else, use and misuse of images can make or break a website—so, like elsewhere in this
book, this chapter covers more than the essentials of working with HTML and CSS. Along with providing
an overview of color theory, we’ve compiled a brief list of common mistakes that people make when
working with images for the Web—after all, even the most dedicated web designers pick up bad habits
without realizing it. Finally, at the end of the chapter, we’ll introduce your first piece of JavaScript, providing
you with a handy cut-out-and-keep script to randomize images on a web page.
Color theory
Color plays a massively important role in any field of design, and web design is no exception. Therefore, it
seems appropriate to include in this chapter a brief primer on color theory and working with colors on the
Web.
Color wheels
Circular color diagrams—commonly referred to as color wheelswere invented by Newton and remain a
common starting point for creative types wanting to understand the relationship between colors and also
for creating color schemes. On any standard color wheel, the three primary colors are each placed one-
third of the way around the wheel, with secondary colors equally spaced between them—secondary colors
being a mix of two primary colors. Between secondary and primary colors are tertiary colors, the result of
mixing primary and secondary colors. Some color wheels blend the colors together, creating a continuous
shift from one color to another, while others have rather more defined blocks of color; however, in all
cases, the positioning is the same.
Additive and subtractive color systems
On-screen colors use what’s referred to as an additive system, which is the color system used by light—
where black is the absence of color and colored light is added together to create color mixes. The additive
primaries are red, green, and blue (which is why you commonly hear RGB referring to the definition of
www.freepdf-books.com
Working With Images
121
screen colors). Mix equal amounts of red, green, and blue light, and you end up with white; mix
secondaries from the primaries, and you end up with magenta, yellow, and cyan.
In print, a subtractive system is used, similar to that used in the natural world. This works by absorbing
colors before they reach the eye—if an object reflects all light, it appears white, and if it absorbs all light, it
appears black. Inks for print are transparent, acting as filters to enable light to pass through, reflect off the
print base (such as paper), and produce unabsorbed light. Typically, the print process uses cyan,
magenta, and yellow as primaries, along with a key color—black—since equal combination of three print
inks tends to produce a muddy color rather than the black that it should produce in theory.
Although the technology within computers works via an additive system to display colors, digital-based
designers still tend to work with subtractive palettes when working on designs (using red, yellow, and blue
primaries), because that results in natural color combinations and palettes.
Creating a color scheme using a color wheel
Even if you have a great eye for color and can instinctively create great schemes for websites, it pays to
have a color wheel handy. These days, you don’t have to rely on reproductions in books or hastily created
painted paper wheels. There are now digital color wheels that enable you to experiment with schemes,
including Color Consultant Pro for the Mac (www.code-line.com/software/colorconsultantpro.html),
shown in the following screenshot, and Color Wheel Pro (www.color-wheel-pro.com) and ColorImpact
(www.tigercolor.com/Default.htm), both for Windows.
www.freepdf-books.com
Chapter 4
122
When working on color schemes and creating a palette for a website, various schemes are available for
you. The simplest is a monochromatic scheme, which involves variations in the saturation (effectively the
intensity or strength) of a single hue. Such schemes can be soothing—notably when based on green or
blue—but also have a tendency to be bland, unless used with striking design and black and white. A
slightly richer scheme can be created by using colors adjacent on the color wheel—this is referred to as an
analogous scheme and is also typically considered harmonious and pleasing to the eye.
For more impact, a complementary scheme can be used, which uses colors on opposite sides of the color
wheel (such as red/green, orange/blue, and yellow/purple); this scheme is often seen in art, such as a
pointillist using orange dots in areas of blue to add depth. Complementary schemes work well because of
a subconscious desire for visual harmony—an equal mix of complementary colors results in a neutral gray.
Such effects are apparent in human color vision: if you look at a solid plane of color, you’ll see its
complementary color when you close your eyes.
A problem with a straight complementary scheme is that overuse of its colors can result in garish, tense
design. A subtler but still attention-grabbing scheme can be created by using a color and the hues
adjacent to the complementary color. This kind of scheme (which happens to be the one shown in the
previous screenshot) is referred to as split-complementary.
www.freepdf-books.com
Working With Images
123
Another scheme that offers impact—and one often favored by artists—is the triadic scheme, which
essentially works with primary colors or shifted primaries (that is, colors equally spaced around the color
wheel). The scheme provides plenty of visual contrast and, when used with care, can result in a balanced,
harmonious result.
How colors “feel” also plays a part in how someone reacts to them—for example, people often talk of
“warm” and “cool” colors. Traditionally, cooler colors are said to be passive, blending into backgrounds,
while warmer colors are cheerier and welcoming. However, complexity is added by color intensity—a
strong blue will appear more prominent than a pale orange. A color’s temperature is also relative, largely
defined by what is placed around it. On its own, green is cool, yet it becomes warm when surrounded by
blues and purples.
Against black and white, a color’s appearance can also vary. Against white, yellow appears warm, but
against black, yellow has an aggressive brilliance. However, blue appears dark on white but appears
luminescent on black.
The human condition also adds a further wrench in the works. Many colors have cultural significance,
whether from language (cowardly yellow) or advertising and branding. One person may consider a color
one thing (green equals fresh), and another may have different ideas entirely (green equals moldy).
There’s also the problem of color blindness, which affects a significant (although primarily male) portion of
the population, meaning you should never rely entirely on color to get a message across. Ultimately, stick
to the following rules, and you’ll likely have some luck when working on color schemes:
Work with a color wheel, and be mindful of how different schemes work.
Use tints and shades of a hue, but generally avoid entirely monochromatic schemes—inject an
adjacent color for added interest.
Create contrast by adding a complementary color.
Keep saturation levels and value levels the same throughout the scheme (a color’s value
increases the closer it is to white).
Keep things simple—using too many colors results in garish schemes.
Don’t rely on color to get a message across—if in doubt about the effects of color blindness,
test your design with a color blindness simulator application such as Color Oracle
(http://colororacle.cartography.ch/).
Go with your gut reaction—feelings play an important part when creating color schemes. What
feels right is often a good starting point.
Working with hex
The CSS specifications support just 16 color names: aqua, black, blue, fuchsia, gray, green, lime, maroon,
navy, olive, purple, red, silver, teal, white, and yellow. All other colors must be written in another format,
such as RGB numbers or percentages—rgb(255,0,0) or rgb(100%,0%,0%)—or hexadecimal format, which
tends to be most popular in online design. Note that to keep things consistent, it actually makes sense to
write all colors—even the 17 with supported names—in hex. Colors written in hex comprise a hash sign
www.freepdf-books.com
Chapter 4
124
followed by six digits. The six digits are comprised of pairs, representing the red, green, and blue color
values, respectively:
#XXxxxx: Red color value
#xxXXxx: Green color value
#xxxxXX: Blue color value
Because the hexadecimal system is used, the digits can range in value from 0 to f, with 0 being the lowest
value (nothing) and f being the highest. Therefore, if we set the first two digits to full (ff) and the others to
0, we get #ff0000, which is the hex color value for red. Likewise, #00ff00 is green, and #0000ff is blue.
Of course, there are plenty of potential combinations—16.7 million of them, in fact. Luckily, any half-decent
graphics application will do the calculations for you, so you won’t have to work out for yourself that black is
#000000 and white is #ffffff—just use an application’s color picker/eyedropper tool, and it should provide
you with the relevant hex value.
0to255.com offers a nice service to help web designers find variations of any color and quickly copy the
hex code.
Note: When a hex value consists of three pairs, the values can be abbreviated. For
example, the value #ffaa77 can be written #fa7. Some designers swear by this
abbreviated form. I tend to use the full six-figure hex value because it keeps things
consistent.
www.freepdf-books.com
Working With Images
125
Web-safe colors
Modern PCs and Macs come with some reasonable graphics clout, but this wasn’t always the case. In fact,
many computers still in common use cannot display millions of colors. Back in the 1990s, palette
restrictions were even more ferocious, with many computers limited to a paltry 256 colors (8-bit). Microsoft
and Apple couldn’t agree on which colors to use, so the web-safe palette was created, which comprises
just 216 colors that are supposed to work accurately on both platforms without dithering. (For more
information about dithering, see the “GIF” section later in this chapter.) Applications such as Photoshop
have built-in web-safe palettes, and variations on the palette can be seen at www.visibone.com.
Colors in the web-safe palette are made up of combinations of RGB in 20% increments, and as you might
expect, the palette is limited. Also discouraging, in the article “Death of the Websafe Color Palette?” on
Webmonkey (www.webmonkey.com/00/37/index2a.html; posted September 6, 2000), David Lehn and
Hadley Stern reported that all but 22 of these colors were incorrectly shifted in some way when tested on a
variety of platforms and color displays—in other words, only 22 of the web-safe colors are actually totally
web-safe.
The majority of people using the Web have displays capable of millions of colors, and almost everyone
else can view at least thousands of colors. Unless you’re designing for a very specific audience
with known restricted hardware, stick with sRGB (the default color space of the Web—see
www.w3.org/Graphics/Color/sRGB) and design in millions of colors. And consider yourself lucky that it’s not
1995.
Choosing formats for images
To present images online in the best possible way, it’s essential to choose the best file format when
exporting and saving them. Although the save dialogs in most graphics editors present a bewildering list of
possible formats, the Web typically uses just two: JPEG and GIF (along with the GIF89, or transparent
GIF, variant), although a third, PNG, is finally gaining popularity, largely because of Internet Explorer 7
finally having offered full support for it.
JPEG
The Joint Photographic Experts Group (JPEG) format is used primarily for images that require smooth
color transitions and continuous tones, such as photographs. JPEG supports millions of colors, and
relatively little image detail is lost—at least when compression settings aren’t too high. This is because the
format uses lossy compression, which removes information that the eye doesn’t need. As the compression
level increases, this information loss becomes increasingly obvious, as shown in the following images. As
you can see from the image on the right, which is much more compressed than the one on the left, nasty
artifacts become increasingly dominant as the compression level increases. At extreme levels of
compression, an image will appear to be composed of linked blocks (see the following two images, the
originals of which are in the chapter 4 folder as tree.jpg and tree-compressed.jpg).
www.freepdf-books.com
Chapter 4
126
Although it’s tricky to define a cutoff point, it’s safe to say that for photographic work where it’s important to
retain quality and detail, 50 to 60% compression (40 to 50% quality) is the highest you should go for.
Higher compression is sometimes OK in specific circumstances, such as for very small image thumbnails,
but even then, it’s best not to exceed 70% compression.
If the download time for an image is unacceptably high, you could always try reducing the dimensions
rather than the quality; a small, detailed image usually looks better than a large, heavily compressed
image. Also, bear in mind that common elements—that is, images that appear on every page of a website,
perhaps as part of the interface—will be cached and therefore need to be downloaded only once. Because
of this, you can get away with less compression and higher file sizes.
Note: Be aware that applications have different means of referring to compression
levels. Some, such as Adobe applications, use a quality scale, in which 100 is
uncompressed and 0 is completely compressed. Others, such as Paint Shop Pro, use
compression values, in which higher numbers indicate increased compression. Always
be sure you know which scale you’re using.
Some applications have the option to save progressive JPEGs. Typically, this format results in larger file
sizes, but it’s useful because it enables your image to download in multiple passes. This means that a low-
resolution version will display rapidly and gradually progress to the quality you saved it at, allowing viewers
to get a look at a simplified version of the image without having to wait for it to load completely.
GIF
Graphics Interchange Format (GIF) is in many ways the polar opposite of JPEG—it’s lossless, meaning
that there’s no color degradation when images are compressed. However, the format is restricted to a
maximum of 256 colors, thereby rendering it ineffective for color photographic images. Using GIF for such
images tends to produce banding, in which colors are reduced to the nearest equivalent. A fairly extreme
example of this is shown in the following illustration.
www.freepdf-books.com
Working With Images
127
GIF is useful for displaying images with large areas of flat color, such as logos, line art, and type. As we
mentioned in the previous chapter, you should generally avoid using graphics for text on your web pages,
but if you do, PNG is the best choice of format, depending on the stylization of the text and whether it
needs to be transparent.
Although GIF is restricted to 256 colors, it’s worth noting that you don’t have to use the same 256 colors
every time. Most graphics applications provide a number of palette options, such as perceptual, selective,
and web. The first of those, perceptual, tends to prioritize colors that the human eye is most sensitive to,
thereby providing the best color integrity. Selective works in a similar fashion but balances its color choices
with web-safe colors, thereby creating results more likely to be safe across platforms. Web refers to the
216-color web-safe palette discussed earlier. Additionally, you often have the option to lock colors, which
forces your graphics application to use only the colors within the palette you choose.
Images can also be dithered, which prevents continuous tones from becoming bands of color. Dithering
simulates continuous tones, using the available (restricted) palette. Most graphics editors allow for three
different types of dithering: diffusion, pattern, and noise—all of which have markedly different effects on an
image. Diffusion applies a random pattern across adjacent pixels, whereas pattern applies a half-tone
pattern rather like that seen in low-quality print publications. Noise works rather like diffusion, but without
diffusing the pattern across adjacent pixels. The following are four examples of the effects of dithering on
an image that began life as a smooth gradient. The first image (1) has no dither, and the gradient has been
turned into a series of solid, vertical stripes. The second image (2) shows the effects of diffusion dithering;
the third (3), pattern; and the fourth (4), noise.
www.freepdf-books.com
Chapter 4
128
GIF89: The transparent GIF
The GIF89 file format is identical to GIF, with one important exception: you can remove colors, which
provides a very basic means of transparency and enables the background to show through. Because this
is not alpha transparency (a type of transparency that enables a smooth transition from solid to
transparent, allowing for many levels of opacity), it doesn’t work in the way many graphic designers
expect. You cannot, for instance, fade an image’s background from color to transparent and expect the
web page’s background to show through—instead, GIF89’s transparency is akin to cutting a hole with a
pair of scissors: the background shows through the removed colors only. This is fine when the “hole” has
flat horizontal or vertical edges. But if you try this with irregular shapes—such as in the following image of
the cloud with a drop shadow—you’ll end up with ragged edges. In the example, the idea was to have the
cloud casting a shadow onto the gray background. However, because GIFs can’t deal with alpha
transparency, we instead end up with an unwanted white outline. (One way around this is to export the
image with the same background color as that of the web page, but this is possible only if the web page’s
background is a plain, flat color.)
Because of these restrictions, GIF89s are not used all that much these days. They do cling on in one area
of web design, though: as spacers for stretching table cells in order to lay out a page. However, in these
enlightened times, that type of technique must be avoided, since you can lay out precisely spaced pages
much more easily using CSS.
www.freepdf-books.com
Working With Images
129
PNG
For years, PNG (pronounced “ping,” and short for Portable Network Graphics) lurked in the wilderness as a
capable yet unloved and unused format for web design. Designed primarily as a replacement for GIF, the
format has plenty to offer, including a far more flexible palette than GIF and true alpha transparency. Some
have touted PNG as a JPEG replacement, too, but this isn’t recommended—PNGs tend to be much larger
than JPEGs for photographic images. For imagery with sharp lines, areas of flat color, or where alpha
transparency is required, it is, however, a good choice.
The reason PNG was less common than GIF or JPEG primarily had to do with Internet Explorer. Prior to
version 7, Microsoft’s browser didn’t offer support for PNG alpha transparency, instead replacing
transparent areas with white or gray. Although a proprietary workaround exists (see Chapter 9’s “Dealing
with Internet Explorer bugs” section), it isn’t intuitive, and it requires extra code. With post–version 6
releases of Internet Explorer finally supporting alpha transparency, PNG is a popular choice.
The three adjacent images highlight the benefit of PNG over GIF,
as shown in a web browser. The first illustration shows two PNGs
on a white background. The second illustration shows this
background replaced by a grid. Note how the button’s drop
shadow is partially see-through, while the circle’s center is
revealed as being partially transparent, increasing in opacity
toward its edge. The third illustration shows the closest equivalent
when using GIFs—the drop shadow is surrounded by an ugly
cutout, and the circle’s central area loses its transparency. Upon
closer inspection, the circle is also surrounded by a jagged edge,
and the colors are far less smooth than those of the PNG.
For more information about this format, checkout the
PNG website at www.libpng.org/pub/png.
Other image formats
You may have worked on pages in the past and added the odd BMP or TIFF file or seen another site do
the same. These are not standard formats for the Web, though, and while they may work fine in some
cases, they require additional software in order to render in some browsers (in many cases, they won’t
render at all, or they’ll render inconsistently across browsers). Furthermore, JPEG, GIF, and PNG are well-
suited to web design because they enable you to present a lot of visual information in a fairly small file.
Presenting the same in a TIFF or BMP won’t massively increase the image’s quality (when taking into
www.freepdf-books.com
Chapter 4
130
account the low resolution of the Web), but it will almost certainly increase download times. Therefore,
quite simply, don’t use any formats other than JPEG, GIF, or PNG for your web images (and if you decide
to use PNG transparency, be sure that your target audience will be able to see the images).
Common web image gaffes
The same mistakes tend to crop up again and again when designers start working with images. To avoid
making them, read on to find out about some common ones (and how to avoid them).
Using graphics for body copy
Some sites use graphics for body copy on web pages in order to get more typographical control than CSS
allows. However, using graphics for body copy causes text to print poorly—much worse than HTML-based
text. Additionally, it means the text can’t be read by search engines, can’t be copied and pasted, and can’t
be enlarged, unless you’re using a browser (or operating system) that can zoom—and even then it will be
pixelated. If graphical text needs to be updated, it means reworking the original image (which could include
messing with line wraps, if words need to be added or removed), reexporting it, and reuploading it.
As mentioned in the “Image-replacement techniques” section of Chapter 3, the argument is a little less
clear-cut for headings (although I recommend using styled HTML-based text for those, too), but for body
copy, you should always avoid using images.
Not working from original images
If it turns out an image on a website is too large or needs editing in some way, the original should be
sourced to make any changes if the online version has been in any way compressed. This is because
continually saving a compressed image reduces its quality each time. Also, under no circumstances
should you increase the dimensions of a compressed JPEG. Doing so leads to abysmal results every time.
Overwriting original documents
The previous problem gets worse if you’ve deleted your originals. Therefore, be sure that you never
overwrite the original files you’re using. If resampling JPEGs from a digital camera for the Web, work with
copies so you don’t accidentally overwrite your only copy of that great photo you’ve taken with a much
smaller, heavily compressed version. More important, if you’re using an application that enables layers,
save copies of the layered documents prior to flattening them for export—otherwise you’ll regret it when
having to make that all-important change and having to start from scratch.
Busy backgrounds
When used well, backgrounds can improve a website, adding visual interest and atmosphere—see the
following image, showing the top of a version of the Snub Communications homepage. However, if
backgrounds are too busy, in terms of complicated artwork and color, they’ll distract from the page’s
content. If placed under text, they may even make your site’s text-based content impossible to read. With
www.freepdf-books.com
Working With Images
131
that in mind, keep any backgrounds behind content subtle—near-transparent single-color watermarks tend
to work best.
For backgrounds outside of the content area (as per the “Watermarks” section in Chapter 2), you must
take care, too. Find a balance in your design and ensure that the background doesn’t distract from the
content, which is the most important aspect of the site.
Lack of contrast
It’s common to see websites that don’t provide enough contrast between text content and the
background—for example, (very) light gray text on a white background, or pale text on an only slightly
darker background. Sometimes this lack of contrast finds its way into other elements of the site, such as
imagery comprising interface elements. This isn’t always a major problem; in some cases, designs look
stylish if a subtle scheme is used with care. You should, however, ensure that usability isn’t affected—it’s
all very well to have a subtle color scheme, but not if it stops visitors from being able to easily find things
like navigation elements or from being able to read the text.
Using the wrong image format
Exporting photographs as GIFs, using BMPs or TIFFs online, rendering soft and blotchy line art and text
as a result of using the JPEG format—these are all things to avoid in the world of creating images for
websites. See the section “Choosing formats for images” earlier in this chapter for an in-depth discussion
of formats.
Resizing in HTML
When designers work in WYSIWYG editing tools, relying on a drag-and-drop interface, it’s sometimes
tempting to resize all elements in this manner (and this can sometimes also be done by accident), thereby
compromising the underlying code of a web page. Where images are concerned, this has a detrimental
effect, because the pixel dimensions of the image no longer tally with its width and height values. In some
cases, this may lead to distorted imagery (as shown in the rather extreme example that follows); it may
also lead to visually small images that have ridiculously large files sizes by comparison. In most cases,
distortion of detail will still occur, even when proportion is maintained.
www.freepdf-books.com
Chapter 4
132
Note: There are exceptions to this rule, however, although they are rare. For instance, if
you work with pixel art saved as a GIF, you can proportionately enlarge an image,
making it large on the screen. Despite the image being large, the file size will be tiny.
Not balancing quality and file size
Bandwidth can be a problem in image-heavy sites—both in terms of the host getting hammered when
visitor numbers increase and in terms of the visitors, many of whom may be stuck with slower connections
than you having to download the images. Therefore, you should always be sure that your images are
highly optimized in order to save on hosting costs and ensure that your website’s visitors don’t have to
suffer massive downloads. (In fact, they probably won’t—they’ll more than likely go elsewhere.)
But this doesn’t mean you should compress every image on your website into a slushy mess (and we’ve
seen plenty of sites where the creator has exported JPEGs at what looks like 90% compression—“just in
case”).
Err on the side of caution, but remember: common interface elements are cached, so you can afford to
save them at a slightly higher quality. Any image that someone requests (such as via a thumbnail on a
portfolio site) is something they want to see, so these too can be saved at a higher quality because the
person is likely to wait. Also, there is no such thing as an optimum size for web images. If you’ve read in
the past that no web image should ever be larger than 50 KB, it’s hogwash. The size of your images
depends entirely on context, the type of site you’re creating, and the audience you’re creating it for.
Text overlays and splitting images
Some designers use various means to stop people from stealing images from their site and reusing them.
The most common are including a copyright statement on the image itself, splitting the image into a
number of separate images to make it harder to download, and adding an invisible transparent GIF
overlay.
The main problem with copyright statements is that they are often poorly realized (see the following
example), ruining the image with a garish text overlay. Ultimately, while anyone can download images from
your website to their hard drive, you need to remember that if someone uses your images, they’re
infringing your copyright, and you can deal with them accordingly (and, if they link directly to images on
your server, try changing the affected images to something text-based, like “The scumbag whose site
you’re visiting stole images from me”).
www.freepdf-books.com
Working With Images
133
As for splitting images into several separate files or placing invisible GIFs over images to try to stop people
from downloading them, don’t do this—there are simple workarounds in either case, and you just end up
making things harder for yourself when updating your site. Sometimes you even risk compromising the
structural integrity of your site when using such methods.
Stealing images and designs
Too many people appear to think that the Internet is a free-for-all, outside of the usual copyright
restrictions, but this isn’t the case: copyright exists on the Web just like everywhere else. Unless you have
permission to reuse an image you’ve found online, you shouldn’t do so. If discovered, you may get the
digital equivalent of a slap on the wrist, but you could also be sued for copyright infringement.
Although it’s all right to be influenced by someone else’s design, you should also ensure you don’t simply
rip off a creation found on the Web—otherwise, you could end up in legal trouble or the subject of ridicule.
Working with images in HTML
The img element is used to add images to a web page. It’s an empty tag, so it takes the combined start
and end tag form with a trailing slash, as outlined in Chapter 1. The following code block shows an
example of an image element, complete with relevant attributes:
<img src="sunset.jpg" height="200" width="400" alt="Sunset in
ÍReykjavík" />
Perhaps surprisingly, the height and width attributes are actually optional, although I recommend
including them because they assist the browser in determining the size of the image before it downloads
(thereby speeding up the process of laying out the page). The only two image element attributes required
www.freepdf-books.com
Chapter 4
134
in HTML are src and alt. The first, src, is the path to the image file to be displayed; and the second, alt,
provides some alternative text for when the image is not displayed.
Note that this chapter’s section on images largely concerns itself with inline images—the
addition of images to the content of a web page. For an overview of using images as
backgrounds, see the “Web page backgrounds” section of Chapter 2; for an overview of
working with images within web navigation and with links in general, see Chapter 5.
Using alt text for accessibility benefits
Alternate text—usually referred to as alt text, after its attribute—is often ignored or used poorly by
designers, but it’s essential for improving the accessibility of web pages. Visitors using screen readers rely
on the alt attribute’s value to determine what an image shows. Therefore, always include a succinct
description of the image’s content and avoid using the image’s file name, because that’s often of little help.
Ignoring the alt attribute not only renders your page invalid according to the W3C recommendations but
also means that screen readers (and browsers that cannot display images) end up with something like this
for output: [IMAGE][IMAGE][IMAGE]—not very helpful, to say the least.
Descriptive alt text for link-based images
Images often take on dual roles, being used for navigation purposes as well as additional visual impact. In
such cases, the fact that the image is a navigation aid is likely to be of more significance than its visual
appearance. For instance, many companies use logos as links to a homepage—in such cases, some
designers would suggest using “Company X homepage” for the alt text, because it’s more useful than
“Company X.”
Alternatively, stick with using the alt attribute for describing the image, and add a title attribute to the
link, using that to describe the target. Depending on user settings, the link’s title attribute will be read in
the absence of any link text.
Tip: If you don’t have access to screen-reading software for testing alt text and various
other accessibility aspects of a website, either install the text-based browser Lynx; run
Opera in User mode, which can emulate a text browser; or try the Universal Access
options on your computer such as Mac OS X with Voice Over options in Safari.
Null alt attributes for interface images
In some cases, images have no meaning at all (such as if they’re a part of an interface), and there is some
debate regarding the best course of action with regard to such images’ alt values. Definitely never type
something like spacer or interface element; otherwise, screen readers and text browsers will drive their
users crazy relaying these values back to them. Instead, it’s recommended that you use a null alt
attribute, which takes the form alt="".
www.freepdf-books.com
Working With Images
135
Null alt attributes are unfortunately not interpreted correctly by all screen readers; some, upon discovering
a null alt attribute, go on to read the image’s src value. A common workaround is to use empty alt
attributes, which just have blank space for the value (alt=" "). However, the null alt attribute has valid
semantics, so it should be used despite some screen readers not being able to deal with it correctly.
Alternatively, try reworking your design so that images without meaning are applied as background images
to div elements, rather than placed inline.
Using alt and title text for tooltips
Although the W3C specifically states that alt text
shouldn’t be visible if the image can be seen, Internet
Explorer ignores this, displaying alt text as a tooltip
when the mouse cursor hovers over an image, as
shown in the adjacent example.
Internet Explorer users are most likely accustomed to
this by now, and, indeed, you may have used alt text to
create tooltips in your own work. If so, it’s time to stop.
This behavior is not recommended by the W3C, and it’s
also not common across all browsers and platforms.
If an image requires a tooltip, most browsers display the value of a title attribute as one. In spite of this, if
the text you’re intending for a pop-up is important, you should instead place it within the standard text of
your web page, rather than hiding it where most users won’t see it. This is especially important when you
consider that Firefox crops the values after around 80 characters, unlike some browsers, which happily
show multiline tooltips.
Using CSS when working with images
In the following section, we’re going to look at relevant CSS for web page images. You’ll see how best to
apply borders to images and wrap text around them, as well as define spacing between images and other
page elements.
Applying CSS borders to images
You may have noticed earlier that we didn’t mention the border attribute when working through the img
element. This is because the border attribute is deprecated; adding borders to images is best achieved
and controlled by using CSS. (Also, because of the flexibility of CSS, this means that if you want only a
simple surrounding border composed of flat color, you no longer have to add borders directly to your
image files.) Should you want to add a border to every image on your website, you could do so with the
following CSS:
img {
border: 1px solid #000000;
}
www.freepdf-books.com
Chapter 4
136
In this case, a 1-pixel solid border, colored black (#000000 in hex), would surround every image on the site.
Using contextual selectors, this can be further refined. For instance, should you only want the images
within a content area (marked up as a div with an id value of content) to be displayed with a border, you
could write the following CSS:
div#content img {
border: 1px solid #000000;
}
Alternatively, you could set borders to be on by default and override them in specific areas of the website
via a rule using grouped contextual selectors:
img {
border: 1px solid #000000;
}
#masthead img, #footer img, #sidebar img {
border: 0;
}
Finally, you could override a global border setting by creating, for example, a portfolio class and then
assigning it to relevant images. In CSS, you’d write the following:
.portfolio {
border: 0;
}
And in HTML, you’d add the portfolio class to any image that you didn’t want to have a border:
<img class="portfolio" src="sunset.jpg" height="200" width="400"
alt="A photo of a sunset" />
Clearly, this could be reversed (turning off borders by default and overriding this with, say, an addBorder
style that could be used to add borders to specific images). Obviously, you should go for whichever system
provides you with the greatest flexibility when it comes to rapidly updating styles across the site and
keeping things consistent when any changes occur. Generally, the contextual method is superior for
achieving this.
Although it’s most common to apply borders using the shorthand shown earlier, it’s possible to define
borders on a per-side basis, as demonstrated in the “Using classes and CSS overrides to create an
alternate pull quote” exercise in Chapter 3. If you wanted to style a specific image to resemble a Polaroid
photograph, you could set equal borders on the top, left, and right, and a larger one on the bottom. In
HTML, you would add a class attribute to the relevant image:
<img class="photo" src="sunset.jpg" height="300" width="300"
alt="Sunset photo" />
In CSS, you would write the following:
.photo {
border-width: 8px 8px 20px;
border-style: solid;
www.freepdf-books.com
Working With Images
137
border-color: #ffffff;
}
The results of this are shown in the image to the right.
(Obviously, the white border shows only if you have a
contrasting background—you wouldn’t see a white border on
a white background!)
Should you want to, you can also reduce the declaration’s size
by amalgamating the border-style and border-color
definitions:
.photo {
border: solid #ffffff;
border-width : 8px 8px 20px;
}
Note that when you’ve used a contextual selector with an id value to style a bunch of
elements in context, overriding this often requires the con