Head First HTML with CSS XHTML
Author: Desconocido
Date: 2009-01-27 15:06:19+00:00

Upload by mohaa99 ™ (show some respect to the original uploader)

Praise for Head First HTML with CSS & XHTML

“Head First HTML with CSS & XHTML is a thoroughly modern introduction to forward-looking practices in Web page markup and presentation. It correctly anticipates readers’ puzzlements and handles them just in time. The highly graphic and incremental approach precisely mimics the best way to learn this stuff: make a small change and see it in the browser to understand what each new item means.”

— Danny Goodman, author of Dynamic HTML: The Definitive Guide

“Eric and Elisabeth Freeman clearly know their stuff. As the Internet becomes more complex, inspired construction of web pages becomes increasingly critical. Elegant design is at the core of every chapter here, each concept conveyed with equal doses of pragmatism and wit.”

— Ken Goldstein, Executive Vice President &

Managing Director, Disney Online

“The Web would be a much better place if every HTML author started off by reading this book.”

— L. David Baron, Technical Lead, Layout & CSS, Mozilla Corporation http://dbaron.org/

“I’ve been writing HTML and CSS for ten years now, and what used to be a long trial and error learning process has now been reduced neatly into an engaging paperback. HTML used to be something you could just hack away at until things looked okay on screen, but with the advent of web standards and the movement towards accessibility, sloppy coding practice is not acceptable anymore... from a business standpoint or a social responsibility standpoint. Head First HTML with CSS & XHTML teaches you how to do things right from the beginning without making the whole process seem overwhelming. HTML, when properly explained, is no more complicated than plain English, and the Freemans do an excellent job of keeping every concept at eye-level.”

— Mike Davidson, President & CEO, Newsvine, Inc.

“The information covered in this book is the same material the pros know, but taught in an educational and humorous manner that doesn’t ever make you think the material is impossible to learn or you are out of your element.”

— Christopher Schmitt, Author of The CSS Cookbook
and Professional CSS, schmitt@christopher.org Oh, great. You made an XHTML book simple enough a CEO can understand it. What will you do next? Accounting simple enough my developer can understand it? Next thing you know we’ll be collaborating as a team or something.

— Janice Fraser, CEO, Adaptive Path

More Praise for Head First HTML with CSS & XHTML

“I *heart* Head First HTML with CSS & XHTML – it teaches you everything you need to learn in a ‘fun coated’ format!”

— Sally Applin, UI Designer and Fine Artist, http://sally.com.

“This book has humor, and charm, but most importantly, it has heart. I know that sounds ridiculous to say about a technical book, but I really sense that at its core, this book (or at least its authors) really care that the reader learn the material. This comes across in the style, the language, and the techniques. Learning – real understanding and comprehension – on the part of the reader is clearly top most in the minds of the Freemans. And thank you, thank you, thank you, for the book’s strong, and sensible advocacy of standards compliance. It’s great to see an entry level book, that I think will be widely read and studied, campaign so eloquently and persuasively on behalf of the value of standards compliance in web page code.

I even found in here a few great arguments I had not thought of – ones I can remember and use when I am asked – as I still am – ‘what’s the deal with compliance and why should we care?’ I’ll have more ammo now! I also liked that the book sprinkles in some basics about the mechanics of actually getting a web page live - FTP, web server basics, file structures, etc.”

— Robert Neer, Director of Product Development, Movies.com

“Freeman’s Head First HTML with CSS & XHTML is a most entertaining book for learning how to build a great web page. It not only covers everything you need to know about HTML, CSS, and XHTML, it also excels in explaining everything in layman’s terms with a lot of great examples. I found the book truly enjoyable to read, and I learned something new!”

— Newton Lee, Editor-in-Chief, ACM Computers in Entertainment http://www.acmcie.org

“My wife stole the book. She’s never done any web design, so she needed a book like Head First HTML with CSS & XHTML to take her from beginning to end. She now has a list of web sites she wants to build – for our son’s class, our family, ... If I’m lucky, I’ll get the book back when she’s done.”

— David Kaminsky, Master Inventor, IBM

“Beware. If you’re someone who reads at night before falling asleep, you’ll have to restrict Head First HTML with CSS & XHTML to daytime reading. This book wakes up your brain.”

— Pauline McNamara, Center for New Technologies and Education, Fribourg University, Switzerland

Previous Praise for books by the authors

From the awesome Head First Java folks, this book uses every conceivable trick to help you understand and remember. Not just loads of pictures: pictures of humans, which tend to interest other humans. Surprises everywhere. Stories, because humans love narrative. (Stories about things like pizza and chocolate. Need we say more?) Plus, it’s darned funny.

— Bill Camarda, READ ONLY

“This book’s admirable clarity, humor and substantial doses of clever make it the sort of book that helps even non-programmers think well about problem-solving.”

— Cory Doctorow, co-editor of Boing Boing

and author of “Down and Out in the Magic Kingdom”

and “Someone Comes to Town, Someone Leaves Town”

“I feel like a thousand pounds of books have just been lifted off of my head.”

— Ward Cunningham, inventor of the Wiki

and founder of the Hillside Group

“This book is close to perfect, because of the way it combines expertise and readability. It speaks with authority and it reads beautifully. It’s one of the very few software books I’ve ever read that strikes me as indispensable. (I’d put maybe 10 books in this category, at the outside.)”

— David Gelernter, Professor of Computer Science,

Yale University and author of “Mirror Worlds” and “Machine Beauty”

“A Nose Dive into the realm of patterns, a land where complex things become simple, but where simple things can also become complex. I can think of no better tour guides than the Freemans.”

— Miko Matsumura, Industry Analyst, The Middleware Company Former Chief Java Evangelist, Sun Microsystems

“I laughed, I cried, it moved me.”

— Daniel Steinberg, Editor-in-Chief, java.net

“Just the right tone for the geeked-out, casual-cool guru coder in all of us. The right reference for practical development strategies—gets my brain going without having to slog through a bunch of tired, stale professor-speak.”

— Travis Kalanick, Founder of Scour and Red Swoosh

Member of the MIT TR100

“I literally love this book. In fact, I kissed this book in front of my wife.”

— Satish Kumar

Other related books from O’Reilly

HTML Pocket Reference

CSS Pocket Reference

CSS Cookbook

Cascading Style Sheets: The Definitive Guide

HTML & XHTML: The Definitive Guide

Dynamic HTML: The Definitive Reference

Learning Web Design: A Beginner’s Guide to HTML, Graphics, and Beyond Other books in O’Reilly’s Head First series Head First JavaTM

Head First Object-Oriented Analysis and Design (OOA&D)

Head First Design Patterns

Head First Servlets and JSP

Head First EJB

Head First PMP

Head First SQL

Head First Software Development

Head First JavaScript

Head First Ajax

Head First Physics

Head First Statistics

Head First Rails

Head First PHP & MySQL

Head First Algebra

Make it Stick

Head First HTML
with CSS & XHTML

Wouldn’t it be dreamy
if there was an HTML book
that didn’t assume you knew what
elements, attributes, validation,
selectors, and pseudo-classes were,
al by page three? It’s probably just
a fantasy...

Elisabeth Freeman

Eric Freeman

Beijing • Cambridge • Köln • Sebastopol • Taipei • Tokyo

Head First HTML with CSS and XHTML
by Elisabeth Freeman and Eric Freeman

Copyright © 2006 O’Reilly Media, Inc. All rights reserved.

Printed in the United States of America.

Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.

O’Reilly Media books may be purchased for educational, business, or sales promotional use. Online editions are also available for most titles (safari.oreilly.com). For more information, contact our corporate/institutional sales department: (800) 998-9938 or corporate@oreilly.com.

Associate Publisher: Mike Hendrickson

Series Creators:

Kathy Sierra, Bert Bates

Series Advisors:

Elisabeth Freeman, Eric Freeman

Editor:

Brett McLaughlin

Cover Designers:

Ellie Volckhausen, Karen Montgomery

HTML Wranglers:

Elisabeth Freeman, Eric Freeman

Structure:

Elisabeth Freeman

Style:

Eric Freeman

Page Viewer:

Oliver

Printing History:

December 2005: First Edition.

Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc. The Head First series designations, Head First HTML with CSS and XHTML, and related trade dress are trademarks of O’Reilly Media, Inc.

Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc., was aware of a trademark claim, the designations have been printed in caps or initial caps.

While every precaution has been taken in the preparation of this book, the publisher and the authors assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein.

In other words, if you use anything in Head First HTML with CSS & XHTML to, say, run a nuclear power plant, you’re on your own. We do, however, encourage you to visit the Head First Lounge.

No elements or properties were harmed in the making of this book.

Thanks to Clemens Orth for the use of his photo, “applestore.jpg”, which appears in Chapter 5.

ISBN: 978-0-596-10197-8

[C]

[1/09]

Browser wars? You’ll
find out in Chapter 6.

To the W3C, for saving us from the browser wars and
for their brilliance in separating structure (HTML) from
presentation (CSS)...

And for making HTML, CSS, and XHTML complex enough
that people need a book to learn it.

the authors

Authors of Head First HTML with CSS & XHTML
eeman

Elisabeth Fr

Eric Freeman

Elisabeth is an author and software developer.

She’s been involved with the Internet since the early

Eric is a computer scientist with a passion for media and days, having co-founded The Ada Project (TAP), an
software architectures. He just wrapped up four years at
award winning web site for women in computing
a dream job – directing Internet broadband and wireless
now adopted by the ACM. More recently Elisabeth
efforts at Disney – and is now back to writing, creating cool led research and development efforts in digital media
software, and hacking Java and Macs.

at the Walt Disney Company where she co-invented

Eric spent a lot of the ‘90s working on alternatives to the Motion, a content system that delivers terabytes of
desktop metaphor with David Gelernter (and they’re
video every day to Disney, ESPN, and Movies.com
both still asking the question “why do I have to give a file users.

a name?” ). Based on this work, Eric landed a Ph.D. at

Elisabeth is a computer scientist at heart and holds

Yale University in ’97. He also co-founded Mirror Worlds
graduate degrees in Computer Science from Yale

Technologies (now acquired) to create a commercial

University and Indiana University. She’s worked in
version of his thesis work, Lifestreams.

a variety of areas including visual languages, RSS

In a previous life, Eric built software for networks and
syndication, and Internet systems. She’s also been an
supercomputers. You might know him from such books as
active advocate for women in computing, developing

JavaSpaces Principles Patterns and Practice. Eric has fond programs that encourage woman to enter the field.

memories of implementing tuple-space systems on

These days you’ll find her sipping some Java or Cocoa

Thinking Machine CM-5s and creating some of the first
on her Mac, although she dreams of a day when the

Internet information systems for NASA in the late 80s.

whole world is using Scheme.

Eric is currently living on Bainbridge Island. When he’s

Elisabeth has loved hiking and the outdoors since her
not writing text or code you’ll find him spending more
days growing up in Scotland. When she’s outdoors her
time tweaking than watching his home theater and trying
camera is never far away. She’s also an avid cyclist,
to restoring a circa 1980s Dragon’s Lair video game. He
vegetarian, and animal lover.

also wouldn’t mind moonlighting as an electronica DJ.

You can send her email at beth@oreilly.com

Write to him at eric@oreilly.com or visit his blog at
http://www.ericfreeman.com
viii

Table of Contents (summary)

Intro
xxv

1

The Language of the Web: getting to know HTML

1

2

Meet the ‘HT’ in HTML: going further, with hypertext

43

3

Web Page Construction: building blocks

77

4

A Trip to Webville: getting connected

125

5

Meeting the Media: adding images to your pages

165

6

Serious HTML: standards, compliance, and all that jazz 223

7

Putting ‘X’ into HTML: moving to XHTML

265

8

Adding a Little Style: getting started with CSS

285

9

Expanding your Vocabulary: styling with fonts and colors 341

10 Getting Intimate with Elements: the box model

385

11 Advanced Web Construction: divs and spans

429

12 Arranging Elements: layout and positioning

487

13 Getting Tabular: tables and lists

549

14 Getting Interactive: X HTML forms

591

Appendix: The Top Ten Topics (we didn’t cover): leftovers 639

Table of Contents (the real thing)

Intro

Your brain on HTML & CSS. Here you are trying to learn something, while here your brain is doing you a favor by making sure the learning doesn’t stick. Your brain’s thinking, “Better leave room for more important things, like which wild animals to avoid and whether naked snowboarding is a bad idea.” So how do you trick your brain into thinking that your life depends on knowing HTML & CSS?

Who is this book for?

xxvi

We know what your brain is thinking
xxvii

Metacognition
xxix

Bend your brain into submission
xxxi

Technical reviewers
xxxiv

Acknowledgments
xxxv
ix

table of contents
getting to know html

1 The Language of the Web

The only thing that is standing between you and getting
yourself on the Web is learning to speak the lingo:

HyperText Markup Language, or HTML for short. So, get ready for some language lessons. After this chapter, not only are you going to understand some basic elements of HTML, but you’ll also be able to speak HTML with a little style. Heck, by the end of this book you’ll be talking HTML like you grew up in Webville.

The Web killed the video star

2

What does the Web server do?

3

What you write (the HTML)...

4

No pressure, but

What the browser creates...

5
thousands of people are going
to visit this Web page when you’re

Your big break at Starbuzz Coffee

9
finished. It not only needs to
be correct, it’s gotta look

Creating the Starbuzz Web page

11
great, too!

Creating an HTML file (Mac)

12

Creating an HTML file (Windows)

14

Meanwhile, back at Starbuzz Coffee...

17

Opening your Web page in a browser

19

Taking your page for a test drive...

20

Tags dissected...

25

Meet the style element

29

Giving Starbuzz some style...

30

Who does what?

32

Fireside Chat

34

Bullet Points

36

Exercise Solutions

38

“I need the HTML f le ‘lounge.html’”

“Found it, here ya go”

Web Server
x

going further, with hypertext

2Meeting the ‘HT’ in HTML

Did someone say “hypertext?” What’s that? Oh, only the entire basis of the Web. In Chapter 1 we kicked the tires of HTML and found it to be a nice markup language (the ‘ML’ in HTML) for describing the structure of Web pages. Now we’re going to check out the ‘HT’ in HTML, hypertext, which will let us break free of a single page and link to other pages. Along the way we’re going to meet a powerful new element, the <a> element, and learn how being “relative” is a groovy thing. So, fasten your seat belts – you’re about to learn some hypertext.

Head First Lounge, New and Improved

44

Creating the new lounge

46

What did we do?

48

What does the browser do?

49

Understanding attributes

51

Technical difficulties

58

Planning your paths...

60

Fixing those broken images...

66

Exercise Solutions

73
xi
table of contents
building blocks

3Web Page Construction

I was told I’d actually be creating Web pages in this book?

You’ve certainly learned a lot already: tags, elements, links, paths... but it’s all for nothing if you don’t create some killer Web pages with that knowledge. In this chapter we’re going to ramp up construction: you’re going to take a Web page from conception to blueprint, pour the foundation, build it, and even put on some finishing touches. All you need is your hard hat and your tool belt, as we’ll be adding some new tools and giving you some insider knowledge that would make Tim “The Toolman” Taylor proud.

From Journal to Web site, at 12mph

79

The rough design sketch

80

From a sketch to an outline

81
h1

From the outline to a Web page

82
p

Test driving Tony’s Web page

84
h2

Meet the <q> element

86

Looooong Quotes

90
img

Adding a <blockquote>

91

The real truth behind the <q> and <blockquote> mystery 94
p

Use the <p> element to make a list...

103

Constructing HTML lists in two easy steps

104
h2

Putting one element inside another is called “nesting”

109
p

To understand the nesting relationships, draw a picture

110

Using nesting to make sure your tags match

111
h2

Inline or block?

113
img

Exercise Solutions

119
p
xii

getting connected

4A Trip to Webville

Web pages are a dish best served on the Internet. So far you’ve only created HTML pages that live on your own computer. You’ve also only linked to pages that are on your own computer. We’re about to change all that. In this chapter we’ll encourage you to get those Web pages on the Internet where all your friends, fans, and customers can actually see them. We’ll also reveal the mysteries of linking to other pages by cracking the code of the h, t, t, p,

:, /, /, w, w, w. So, gather your belongings; our next stop is Webville.

Getting Starbuzz (or yourself) onto the Web

126

Finding a hosting company

127

How can you get a domain name?

128

Moving in

130

Getting your files to the root folder

131

As much FTP as you can possibly fit in two pages

132

Back to business...

135

Mainstreet, URL

136

What is the HTTP Protocol?

137

What’s an absolute path?

138

How default pages work

141

How do we link to other Web sites?

144

Linking to Caffeine Buzz

145

Web page fit and finish

149

Linking into a page

151

Using the <a> element to create a destination

152

How to link to destination anchors

153

Linking to a new window

157

Opening a new window using target

158

Exercise Solutions

162
xiii

table of contents
adding images to your pages

5Meeting the Media

Smile and say “cheese.” Actually, smile and say “gif”, “jpg”, or “png” – these are going to be your choices when “developing pictures” for the Web. In this chapter you’re going to learn all about adding your first media type to your pages: images. Got some digital photos you need to get online? No problem.

Got a logo you need to get on your page? Got it covered. But before we get into all that, don’t you still need to be formally introduced to the <img> element? So sorry, we weren’t being rude, we just never saw the right opening. To make up for it, here’s an entire chapter devoted to <img>. By the end of the chapter you’re going to know all the ins and outs of how to use the <img> element and its attributes. You’re also going to see exactly how this little element causes the browser to do a lot extra work to retrieve and display your images.

How the browser works, with images

166

How images work

169

Here’s a lot

Here’s one pixel.

And now for the formal introduction: meet the <img> element 173
of pixels that
together make up
the upper part of

Always provide an alternative

176
the right wing of
the butterfly.

Creating the ultimate fan site: myPod

178

Whoa! The image is way too large

181

Fixing up the myPod HTML

191

Reworking the site to use thumbnails

195

Turning the thumbnails into links

199

So, how do I make links out of images?

201

What format should we use?

206

This image is made up

To be transparent, or not to be transparent? That is the question...

207
of thousands of pixels
when it’s displayed on
a computer screen.

Wait, what is the color of the Web page background?

209

Check out the logo with a matte

210

Add the logo to the myPod Web page

211

Exercise Solutions

216
xiv

standards, compliance, and all that jazz

6 Serious HTML

What else is there to know about HTML? You’re well on your way to mastering HTML. In fact, isn’t it about time we move on to CSS and learn how to make all this bland markup look fabulous? Before we do, we need to make sure your HTML is really tight (you know... buttoned up, ship shape, nailed down) and we’re going to do that by getting serious about the way we write our HTML. Don’t get us wrong, you’ve been writing first-class HTML all along, but there’s a few things you can do to help the browser faithfully display your pages and to make sure that little mistakes don’t creep into your markup. What’s in it for you? Pages that display more uniformly across browsers (and are readable on mobile devices and screen readers for the visually impaired), pages that load faster, and pages that are guaranteed to play well with CSS. Get ready, this is the chapter where you move from Web tinkerer to Web professional.

Cubicle Conversation

224

A brief history of HTML

226

We can’t have your pages putting the browser into quirks mode 229

Adding the document type definition

231

Meet the W3C validator

234

Validating the Head First Lounge

235

Houston, we have a problem...

236

Adding a <meta> tag to specify the content type

240

Making the validator happy with a <meta> content tag...

241

Third time’s the charm?

242

Changing the doctype to strict

246

Do we have validation?

247

Fixing the nesting problem

249

One more chance to be strict...

250

Strict HTML 4.01, grab the handbook

252

Fireside Chat

256

HTML Archeology

259

Exercise Solutions

263
xv

table of contents
moving to xhtml

7 Putting the ‘X’ into HTML

We’ve been keeping a dirty secret from you. We know you thought you bought an HTML book, but this is really an XHTML book in disguise. In fact, we’ve been teaching you mostly XHTML all along. You’re probably wondering, just what the heck is XHTML? Well, meet eXtensible HTML – otherwise known as XHTML – the next evolution of HTML. It’s leaner, meaner, and even more tuned for compatibility with a wide range of devices beyond browsers. In this short little chapter we’re going to get you from HTML to XHTML in three simple steps. So, turn the page, you’re almost there... (and then we’re on to CSS).

What is XML?

267

What does this have to do with HTML?

268

So why would you want to use XHTML?

270

The XHTML 1.0 checklist

272

Going from strict HTML to XHTML 1.0

274

Old school HTML 4.01 Strict

275

New and improved XHTML 1.0

275

Validation: it’s not just for HTML

277

Fireside Chat

280

HTML or XHTML? The choice is yours...

282

Exercise Solutions

284

I like keeping up with
trends and technologies.

XHTML is the future, and since
it’s almost exactly like HTML,
why not go with the better
technology?

Maintains her
own blog.

xvi

getting started with CSS

8Adding a Little Style

I was told there’d be CSS in this book. So far you’ve been concentrating on learning XHTML to create the structure of your Web pages. But as you can see, the browser’s idea of style leaves a lot to be desired. Sure, we could call the fashion police, but we don’t need to. With CSS, you’re going to completely control the presentation of your pages, often without even changing your XHTML.

Could it really be so easy? Well, you are going to have to learn a new language; after all, Webville is a bilingual town. After reading this chapter’s guide to learning the language of CSS, you’re going to be able to stand on either side of Main Street and hold a conversation.

You’re not in Kansas anymore...

286

Overheard on Webville’s “Trading Spaces”

288

Using CSS with XHTML

289

Let’s put a line under the welcome message, too

295

Specifying a second rule, just for the <h1>

296

Getting the Lounge style into the elixirs and directions pages 303

Linking to the external style sheet

305

Five-Minute

It’s time to talk about your inheritance...

311

Mystery

What if we move the font up the family tree?

312

Overriding inheritance

314

Creating a selector for the class

318

Taking classes further...

320

The world’s smallest and fastest guide to how styles are applied 322

Who gets the inheritance?

326

Making sure the Lounge CSS validates

329

Exercise Solutions

333
html
head
body
meta
title
style
h1
p
p
h2
p
img
a
em
a
xvii

table of contents
styling with fonts and colors

9 Expanding your Vocabulary

Your CSS language lessons are coming along nicely.

You already have the basics of CSS down and you know how to create CSS
rules to select and determine the style of the elements. Now what you need is to increase your vocabulary, and that means picking up some new properties and learning about what they can do for you. In this chapter we’re going to work through some of the most common properties that affect the display of text. To do that, you’ll need to learn a few things about fonts and color. You’re going to see you don’t have to be stuck with the fonts everyone else uses, or the clunky sizes and styles the browser uses as the defaults for paragraphs and headings.

You’re also going to see there is a lot more to color than meets the eye.

Text and fonts from 30,000 feet

342

What is a font family anyway?

344

Specifying font families using CSS

347

Dusting off Tony’s Journal

348

How do I deal with everyone having different fonts?

351

So, how should I specify my font sizes?

354

Let’s make these changes to the font sizes in Tony’s Web page 356

Changing a font’s weight

359

Adding style to your fonts

361

Styling Tony’s quotes with a little italic

362

How do Web colors work?

364

How do I specify Web colors? Let me count the ways...

367

The two minute guide to hex codes

370

How to find Web colors

372

A

Back to Tony’s page...

375

B

5

10

4

6

9

11 C

Everything you ever wanted to know about text-decorations

377

3

12 D

Removing the underline...

378

2

13

7 8

E

1

14

Exercise Solutions

381

F

15

0
xviii

the box model

10Getting Intimate with Elements

To do advanced Web construction you really need to know
your building materials. In this chapter we’re going to take a close look at our building materials: the XHTML elements. We’re going to put block and inline elements right under the microscope and see what they’re made of. You’re going to see how you can control just about every aspect of how an element is constructed with CSS. But we’re not going to stop there; you’re also going to see how you can give elements unique identities. And, if that weren’t enough, you’re going to discover why you might want to use multiple style sheets.

The lounge gets an upgrade

386

Starting with a few simple upgrades

388

Checking out the new line height

390

Getting ready for some major renovations

391

A closer look at the box model...

392

What you can do to boxes...

394

Creating the guarantee style

399

Padding, border, and margins for the guarantee

401

Adding some padding

401

Now let’s add some margin

402

Adding a background image

404

Fixing the background image

407

How do you add padding only on the left?

408

How do you increase the margin just on the right?

409

A two-minute guide to borders

410

Border fit and finish

412

Interview with an HTML class

414

The id attribute

416

Using an id in the lounge

418

Remixing style sheets

420

Using multiple style sheets

421

Exercise Solutions

426
xix

table of contents
divs and spans

11 Advanced Web Construction

It’s time to get ready for heavy construction. In this chapter we’re going to roll out two new XHTML elements, called <div> and <span>. These are no simple “two by fours;” these are full blown steel beams. With <div> and

<span>, you’re going to build some serious supporting structures, and once you’ve got those structures in place, you’re going to be able to style them all in new and powerful ways. Now, we couldn’t help but notice that your CSS toolbelt is really starting to fill up, so it’s time to show you a few shortcuts that will make specifying all these properties a lot easier. And, we’ve also got some special guests in this chapter, the pseudo-classes, which are going to allow you to create some very interesting selectors. (But, if you’re thinking that “pseudo-classes” would make a great name for Weekly Elixir
your next band; too late, we beat you to it.)

Specials

A close look at the elixirs HTML

431

Let’s explore how we can divide a page into logical sections 433

Lemon Breeze

Adding a border

440

The ultimate healthy drink,

An over-the-border test drive

440
this elixir combines herbal
botanicals, minerals, and
vitamins with a twist of

Adding some real style to the elixirs section

441
lemon into a smooth citrus
wonder that will keep your
immune system going all

The game plan

442
day and all night.

Working on the elixir width

442

Adding the basic styles to the elixirs

447

What we need is a way to select descendants

453

Chai Chiller

Changing the color of the elixir headings

455

Not your traditional chai,
é with
this elixir mixes mat

chai spices and adds

Fixing the line height

456
an extra chocolate kick
for a caffeinated taste

It’s time to take a little shortcut...

458
sensation on ice.

Adding <span>s in three easy steps

464

The <a> element and its multiple personalities

468

How can you style elements based on their state?

469

Black Brain Brew

Putting those pseudo-classes to work

471

Want to boost your
memory? Try our Black

, made

Isn’t it about time we talk about the “cascade”?

473

Brain Brew elixir
with black oolong tea and
just a touch of espresso.

The cascade

475

Your brain will thank you
for the boost.

Welcome to the “What’s my specificity game”

476

Join us any evening for these and all
our wonderful elixirs.

Putting it all together

477

Exercise Solutions

483
xx

layout and positioning

12Arranging Elements

It’s time to teach your XHTML elements new tricks. We’re not going to let those XHTML elements just sit there anymore; it’s about time they get up and help us create some pages with real layouts. How? Well, you’ve got a good feel for the <div> and <span> structural elements and you know all about how the box model works, right? So, now it’s time to use all that knowledge to craft some real designs. No, we’re not just talking about more background and font colors, we’re talking about full blown professional designs using multi-column layouts. This is the chapter where everything you’ve learned comes together.

Did you do the Super Brain Power?

488

Use the flow, Luke

489

What about inline elements?

491

How it all works together

492

How to float an element

495

Behind the scenes at the lounge

497
h1
text

The new Starbuzz

499
h2
text
h2

Move the sidebar just below the header

504
text
p id=”amazing”

text
text

Set the width of the sidebar and float it

504
p
span
em
text

Fixing the two-column problem

507
em
span
text

Setting the margin on the main section

508
p
text

Back to clearing up the overlap problem

511
text
text

Righty tighty, lefty loosey

514
text

Liquid and frozen designs

517
p

How absolute positioning works

520
img
img
img
img

Changing the Starbuzz CSS

523

One tradeoff you can make to fix the footer

527

Positioning the award

529

How does fixed positioning work?

535

Using a negative left property value

537

Getting relative

539

To three-columns and beyond...

541

Exercise Solutions

544
xxi

table of contents
tables and more lists

13 Getting Tabular

If it walks like a table and talks like a table... There comes a time in life when we have to deal with the dreaded tabular data. Whether you need to create a page representing your company’s inventory over the last year, or a catalog of your Beanie Babies collection (don’t worry, we won’t tell), you know you need to do it in HTML; but how? Well, have we got a deal for you: order now and in a single chapter we’ll reveal the secrets of tables that will allow you to put your very own data right inside HTML tables. But there’s more: with every order we’ll throw in our exclusive guide to styling HTML tables. And, if you act now, as a special bonus, we’ll throw in our guide to styling HTML lists. Don’t hesitate, call now!

How do we make tables with HTML?

551

How to create a table using HTML

552

What the browser creates

553

Tables dissected...

554

Adding a caption and a summary

557

Before we start styling, let’s get the table back into Tony’s page...

559

Getting those borders to collapse

564

How about some color?

566

Tony made an interesting discovery...

567

Another look at Tony’s table

568

How to tell cells to span more than one row

569

The new and improved table

571

Trouble in paradise?

572

Overriding the CSS for the nested table headings

576

Giving Tony’s site the final polish

577

Exercise Solutions

588
xxii

14 xhtml forms

Getting Interactive

So far all your Web communication has been one way:

from your page to your visitors. Golly, wouldn’t it be nice if your visitors could talk back? That’s where HTML forms come in: once you enable your pages with forms (along with a little help from a Web server), your pages are going to be able to gather customer feedback, take an online order, get the next move in an online game, or collect the votes in a “hot or not” contest. In this chapter you’re going to meet a whole team of XHTML elements that work together to create Web forms.

You’ll also learn a bit about what goes on behind the scenes in the server to support forms, and we’ll even talk about keeping those forms stylish (a controversial topic –
read on and see why).

How forms work

592

How forms work in the browser

593

What you write in XHTML

594

What the browser creates

595

How the <form> element works

596

Getting ready to build the Bean Machine form

604

Adding the <form> element

605

How <form> element names work

606

Back to getting those <input> elements in your XHTML...

608

Adding some more input elements to your form

609

Adding the <select> element

610

Give the customer a choice of whole or ground beans

612

Punching the radio buttons

613

Completing the form

614

Adding the checkboxes and textarea

615

Watching GET in action

621

To Table or Not to Table? That’s the question...

626

Getting the form elements into a table

627

Styling the form and the table with CSS

630

Exercise Solutions

635
xxiii

table of contents

15 appendix: leftovers

The Top Ten Topics (we didn’t cover)

We covered a lot of ground, and
you’re almost finished with this
book. We’ll miss you, but before we let you go,
we wouldn’t feel right about sending you out into
the world without a little more preparation. We
can’t possibly fit everything you’ll need to know
into this relatively small chapter. Actually, we did
originally include everything you need to know
about XHTML and CSS (not already covered by
the other chapters), by reducing the type point
size to .00004. It all fit, but nobody could read it.

So, we threw most of it away, and kept the best
bits for this Top Ten chapter.

More Selectors

640

Frames

642

Multimedia & Flash

643

Tools for Creating Web Pages

644

Client-side Scripting

645

Server-side Scripting

646

Tuning for Search Engines

647

More about Style Sheets for Printing

648

Pages for Mobile Devices

649

Blogs

650
iIndex

651
xxiv

how to use this book

Intro

I can’t believe
they put that in an

HTML book!

In this section, we answer the burning question:

“So, why DID they put that in an HTML book?”

xxv

Make it Stick

how to use this book

Who is this book for ?

If you can answer “yes” to all of these:

If you have access to any

1 Do you have access to a computer with a Web browser computer manufactured
and a text editor?

in the last decade, the
answer is yes.

2 Do you want to learn, understand, and remember how to create Web pages using the best techniques and the most recent standards?

3 Do you prefer stimulating dinner party conversation to dry, dull, academic lectures?

this book is for you.

Who should probably back away from this book?

If you can answer “yes” to any one of these:

1 Are you completely new to computers?

(You don’t need to be advanced, but you should
understand folders and files, simple text editing
applications, and how to use a Web browser.)

2 Are you a kick-butt Web developer looking for a
reference book?

3 Are you afraid to try something different? Would you rather have a root canal than mix stripes with
plaid? Do you believe that a technical book can’t be
serious if HTML tags are anthropomorphized?

this book is not for you.

[Note from marketing: this book is
for anyone with a credit card.]

xxvi
intro

the intro

We know what you’re thinking.

“How can this be a serious book?”

“What’s with all the graphics?”

“Can I actually learn it this way?”

Your brain think

THIS is imp
s
ortant.

And we know what your brain is thinking.

Your brain craves novelty. It’s always searching, scanning, waiting for something unusual. It was built that way, and it helps you stay alive.

Today, you’re less likely to be a tiger snack. But your brain’s still looking.

You just never know.

So what does your brain do with all the routine, ordinary, normal things you encounter? Everything it can to stop them from interfering with the brain’s real job—recording things that matter. It doesn’t bother saving the boring things; they never make it past the “this is obviously not important”

filter.

How does your brain know what’s important? Suppose you’re out for a day hike and a tiger jumps in front of you, what happens inside your head and body?

Great. Only

Neurons fire. Emotions crank up. Chemicals surge.

637 more dul ,

And that’s how your brain knows...

dry, boring pages.

s

This must be important! Don’t forget it!

Your brain think
orth

But imagine you’re at home, or in a library. It’s a safe, warm, tiger-THIS isn’t w
saving.

free zone. You’re studying. Getting ready for an exam. Or trying to learn some tough technical topic your boss thinks will take a week, ten days at the most.

Just one problem. Your brain’s trying to do you a big favor. It’s trying to make sure that this obviously non-important content doesn’t clutter up scarce resources. Resources that are better spent storing the really big things. Like tigers. Like the danger of fire. Like how you should never again snowboard in shorts.

And there’s no simple way to tell your brain, “Hey brain, thank you very much, but no matter how dull this book is, and how little I’m registering on the emotional Richter scale right now, I really do want you to keep this stuff around.”

you are here� xxvii

how to use this book

We think of a “Head First” reader as a learner.

So what does it take to learn something? First, you have to get it, then make sure you don’t forget it. It’s not about pushing facts into your head. Based on the latest research in cognitive science, neurobiology, and educational psychology, learning takes a lot more than text on a page. We know what turns your brain on.

Browsers make requests for HTML
pages or other r

Some of the Head First learning principles:

esources, like images.

Make it visual. Images are far more memorable than words alone, and make learning much more effective (up to 89% improvement in recall and transfer studies). It also makes things more understandable.

Put the words within or near the graphics they relate to, Web Server

“Found it, here ya go”

rather than on the bottom or on another page, and learners will be up to twice as likely to solve problems related to the content.

Use a conversational and personalized style. In recent studies, students performed up to 40% better on post-learning tests if the content spoke directly to the reader, using a first-person, conversational style rather than taking a formal tone. Tell stories instead of lecturing. Use casual language. Don’t It really sucks to forget
your <body> element.

take yourself too seriously. Which would you pay more attention to: a stimulating dinner party companion, or a lecture?

Does it make sense to

Get the learner to think more deeply. In other words, unless create a bathtub class for
you actively flex your neurons, nothing much happens in your head.

my style, or just to style
the whole bathroom?

A reader has to be motivated, engaged, curious, and inspired to solve problems, draw conclusions, and generate new knowledge.

And for that, you need challenges, exercises, and thought-provoking questions, and activities that involve both sides of the brain, and multiple senses.

The head element is
where you put things

Get—and keep—the reader’s attention. We’ve
about your page.

all had the “I really want to learn this but I can’t stay awake past page one” experience. Your brain pays attention to things that are out of the ordinary, interesting, strange, eye-catching, unexpected.

Learning a new, tough, technical topic doesn’t have to be boring. Your brain will learn much more quickly if it’s not.

Touch their emotions. We now know that your ability to remember something is largely dependent on its emotional content. You remember what you care about. You remember when you feel something. No, we’re not talking heart-wrenching stories about a boy and his dog. We’re talking emotions like surprise, curiosity, fun, “what the...?” , and the feeling of “I Rule!” that comes when you solve a puzzle, learn something everybody else thinks is hard, or realize you know something that “I’m more technical than thou” Bob from engineering doesn’t.

xxviii intro

the intro

Metacognition: thinking about thinking

If you really want to learn, and you want to learn more quickly and more deeply, pay attention to how you pay attention. Think about how you think. Learn how you I wonder how I
can trick my brain
learn.

into remembering

Most of us did not take courses on metacognition or learning theory when we were this stuff...

growing up. We were expected to learn, but rarely taught how to learn.

But we assume that if you’re holding this book, you really want to learn how to create Web pages. And you probably don’t want to spend a lot of time. And you want to remember what you read, and be able to apply it.

And for that, you’ve got to understand it. To get the most from this book, or any book or learning experience, take responsibility for your brain.

Your brain on this content.

The trick is to get your brain to see the new material you’re learning as Really Important. Crucial to your well-being. As important as a tiger.

Otherwise, you’re in for a constant battle, with your brain doing its best to keep the new content from sticking.

So how DO you get your brain to think HTML & CSS
are as important as a tiger?

There’s the slow, tedious way, or the faster, more effective way. The slow way is about sheer repetition. You obviously know that you are able to learn and remember even the dullest of topics, if you keep pounding on the same thing. With enough repetition, your brain says, “This doesn’t feel important to him, but he keeps looking at the same thing over and over and over, so I suppose it must be.”

The faster way is to do anything that increases brain activity, especially different types of brain activity. The things on the previous page are a big part of the solution, and they’re all things that have been proven to help your brain work in your favor. For example, studies show that putting words within the pictures they describe (as opposed to somewhere else in the page, like a caption or in the body text) causes your brain to try to make sense of how the words and picture relate, and this causes more neurons to fire.

More neurons firing = more chances for your brain to get that this is something worth paying attention to, and possibly recording.

A conversational style helps because people tend to pay more attention when they perceive that they’re in a conversation, since they’re expected to follow along and hold up their end. The amazing thing is, your brain doesn’t necessarily care that the “conversation”

is between you and a book! On the other hand, if the writing style is formal and dry, your brain perceives it the same way you experience being lectured to while sitting in a roomful of passive attendees. No need to stay awake.

But pictures and conversational style are just the beginning.

you are here� xxix

how to use this book

Here’s what WE did:

We used pictures, because your brain is tuned for visuals, not text. As far as your brain’s concerned, a picture really is worth 1024 words. And when text and pictures work together, we html
embedded the text in the pictures because your brain works more effectively when the text is body
within the thing the text refers to, as opposed to in a caption or buried in the text somewhere.

h1
p
p
h2
p

We used redundancy, saying the same thing in different ways and with different media types, img
a
em
a
and multiple senses, to increase the chance that the content gets coded into more than one area of your brain.

We used concepts and pictures in unexpected ways because your brain is tuned for novelty, and we used pictures and ideas with at least some emotional content, because your brain is tuned to pay attention to the biochemistry of emotions. That which causes you to feel something is more likely to be remembered, even if that feeling is nothing more than a little humor,
surprise, or interest.

We used a personalized, conversational style, because your brain is tuned to pay more attention when it believes you’re in a conversation than if it thinks you’re passively listening to a presentation. Your brain does this even when you’re reading.

Be the Browser

We included more than 100 activities, because your brain is tuned to learn and remember more when you do things than when you read about things. And we made the exercises challenging-yet-do-able, because that’s what most people prefer.

We used multiple learning styles, because you might prefer step-by-step procedures, while someone else wants to understand the big picture first, while someone else just wants to see a code example. But regardless of your own learning preference, everyone benefits from seeing the BULLET POINTS
same content represented in multiple ways.

We include content for both sides of your brain, because the more of your brain you engage, the more likely you are to learn and remember, and the longer you can stay focused.

Puzzles

Since working one side of the brain often means giving the other side a chance to rest, you can be more productive at learning for a longer period of time.

And we included stories and exercises that present more than one point of view, because your brain is tuned to learn more deeply when it’s forced to make evaluations and judgements.

We included challenges, with exercises, and by asking questions that don’t always have a straight answer, because your brain is tuned to learn and remember when it has to work at something. Think about it—you can’t get your body in shape just by watching people at the gym.

But we did our best to make sure that when you’re working hard, it’s on the right things. That
you’re not spending one extra dendrite processing a hard-to-understand example, or parsing difficult, jargon-laden, or overly terse text.

We used people. In stories, examples, pictures, etc., because, well, because you’re a person. And your brain pays more attention to people than it does to things.

We used an 80/20 approach. We assume that if you’re going to be a kick-butt Web developer, this won’t be your only book. So we don’t talk about everything. Just the stuff you’ll actually need.

xxx
intro

the intro

Here’s what YOU can do to bend
your brain into submission

So, we did our part. The rest is up to you. These tips are a starting point; listen to your brain and figure out what works for you and what doesn’t. Try new things.

cut this out and stick i
on y
t
our refrigerator.

1 Slow down. The more you understand,

6 Talk about it. Out loud.

the less you have to memorize.

Speaking activates a different part of the brain.

Don’t just read. Stop and think. When the

If you’re trying to understand something, or
book asks you a question, don’t just skip to the
increase your chance of remembering it later, say
answer. Imagine that someone really is asking
it out loud. Better still, try to explain it out loud
the question. The more deeply you force your
to someone else. You’ll learn more quickly, and
brain to think, the better chance you have of
you might uncover ideas you hadn’t known were
learning and remembering.

there when you were reading about it.

2 Do the exercises. Write your own notes.

We put them in, but if we did them for you,

7 Listen to your brain.

that would be like having someone else do

Pay attention to whether your brain is getting
your workouts for you. And don’t just look at
overloaded. If you find yourself starting to skim the
the exercises. Use a pencil. There’s plenty of
surface or forget what you just read, it’s time for a
evidence that physical activity while learning
break. Once you go past a certain point, you won’t
can increase the learning.

learn faster by trying to shove more in, and you
might even hurt the process.

3 Read the “There are No Dumb Questions”

That means all of them. They’re not optional

8 Feel something!

sidebars— they’re part of the core content!

Your brain needs to know that this matters. Get

Don’t skip them.

involved with the stories. Make up your own
captions for the photos. Groaning over a bad joke is
still better than feeling nothing at all.

4 Make this the last thing you read before
bed. Or at least the last challenging thing.

Part of the learning (especially the transfer to

9 Create something!

long-term memory) happens after you put the

Apply this to something new you’re designing, or
book down. Your brain needs time on its own, to
rework an older project. Just do something to get some do more processing. If you put in something new
experience beyond the exercises and activities in
during that processing-time, some of what you
this book. All you need is a pencil and a problem
just learned will be lost.

to solve... a problem that might benefit from using

HTML and CSS.

5 Drink water. Lots of it.

Your brain works best in a nice bath of fluid.

Dehydration (which can happen before you ever
feel thirsty) decreases cognitive function.

you are here� xxxi
how to use this book

Read Me

This is a learning experience, not a reference book. We deliberately stripped out everything that might get in the way of learning whatever it is we’re working on at that point in the book. And the first time through, you need to begin at the beginning, because the book makes assumptions about what you’ve already seen and learned.

We begin by teaching basic HTML, then standards-based HTML

4.01, and then on to XHTML.

To write standards-based HTML or XHTML, there are a lot of technical details you need to understand that aren’t helpful when you’re trying to learn the basics of HTML.

Our approach is to have you learn the basic concepts of HTML first (without worrying about these details), and then, when you have a solid understanding of HTML, teach you to write standards compliant HTML and XHTML. This has the added benefit that the technical details are more meaningful after you’ve already learned the basics.

It’s also important that you be writing compliant HTML or XHTML when you start using CSS, so, we make a point of getting you to standards-based HTML and XHTML
before you begin any serious work with CSS.

We don’t cover every single HTML element or attribute or CSS
property ever created.

There are a lot of HTML elements, a lot of attributes, and a lot of CSS properties. Sure, they’re all interesting, but our goal was to write a book that weighs less than the person reading it, so we don’t cover them all here. Our focus is on the core HTML elements and CSS properties that matter to you, the beginner, and making sure that you really, truly, deeply understand how and when to use them. In any case, once you’re done with Head First HTML & CSS, you’ll be able to pick up any reference book and get up to speed quickly on all the elements and properties we left out.

This book advocates a clean separation between the structure of your pages and the presentation of your pages.

Today, serious Web pages use HTML and XHTML to structure their content, and CSS for style and presentation. 1990s-era pages often used a different model, one where HTML was used for both structure and style. This book teaches you to use HTML for structure and CSS for style; we see no reason to teach you out-dated bad habits.

We encourage you to use more than one browser with this book.

While we teach you to write HTML, CSS, and XHTML that is based on standards, you’ll still (and probably always) encounter minor differences in the way Web browsers display xxxii intro
the intro
pages. So, we encourage you to pick at least two up-to-date browsers and test your pages using them. This will give you experience in seeing the differences among browsers and in creating pages that work well in a variety of browsers.

We often use tag names for element names.

Rather than saying “the a element”, or “the ‘a’ element”, we use a tag name, like “the <a> element”. While this may not be technically correct (because <a> is an opening tag, not a full blown element), it does make the text more readable, and we always follow the name with the word “element” to avoid confusion.

The activities are NOT optional.

The exercises and activities are not add-ons; they’re part of the core content of the book.

Some of them are to help with memory, some are for understanding, and some will help you apply what you’ve learned. Don’t skip the exercises. The crossword puzzles are the only things you don’t have to do, but they’re good for giving your brain a chance to think about the words in a different context.

The redundancy is intentional and important.

One distinct difference in a Head First book is that we want you to really get it. And we want you to finish the book remembering what you’ve learned. Most reference books don’t have retention and recall as a goal, but this book is about learning, so you’ll see some of the same concepts come up more than once.

The examples are as lean as possible.

Our readers tell us that it’s frustrating to wade through 200 lines of an example looking for the two lines they need to understand. Most examples in this book are shown within the smallest possible context, so that the part you’re trying to learn is clear and simple. Don’t expect all of the examples to be robust, or even complete—they are written specifically for learning, and aren’t always fully-functional.

We’ve placed all the example files on the Web so you can download them. You’ll find them at http://www.headfirstlabs.com/books/hfhtml/

The ‘Brain Power’ exercises don’t have answers.

For some of them, there is no right answer, and for others, part of the learning experience of the Brain Power activities is for you to decide if and when your answers are right. In some of the Brain Power exercises you will find hints to point you in the right direction.

you are here� xxxiii

the review team

Valentin Crettaz

Corey McGlone

Tech Reviewers

Joe Konior

Barney Marispini

Lousie Barr

Fearless leader
of the Extreme

Eiffel Tower

Review Team.

Marcus Green

Ike Van Atta

Johannes de Jong

Pauline McNamara Pauline gets the “kick
ass reviewer” award.

Our reviewers:

We’re extremely grateful for our technical review team. Johannes de Jong organized and led the whole effort, acted as “series dad,” and made it all work smoothly. Pauline McNamara, “co-manager” of the effort, held things together and was the first to point out when our examples were a little David O’Meara
more “baby boomer” than hip. The whole team proved how much we needed their technical expertise and attention to detail. Valentin Crettaz, Barney Marispini, Marcus Green, Ike Van Atta, David O’Meara, Joe Konior, and Corey McGlone left no stone unturned in their review and the book is a much better book for it. You guys rock! And further thanks to Corey and Pauline for never letting us slide on our often too formal (or we should just say it, incorrect) punctuation. A shout out to JavaRanch as well for hosting the whole thing.

A big thanks to Louise Barr, our token Web designer, who kept us honest on our designs and on our use of XHTML & CSS (although you’ll have to blame us for the actual designs).

xxxiv intro

the intro

Acknowledgments*

Esteemed Reviewer,

David Powers

Even more technical review:

We’re also extremely grateful to our esteemed technical reviewer David Powers.

We have a real love/hate relationship with David because he made us work so hard, but the result was oh so worth it. The truth be told, based on David’s comments, we made significant changes to this book and it is technically twice the book it was before. Thank you, David.

At O’Reilly:

Our biggest thanks to our editor, Brett McLaughlin, who cleared the path for this book, removed every obstacle to its completion, and sacrificed family time to get it done. Brett also did hard editing time on this book (not an easy task for a Head First title). Thanks Brett, this book wouldn’t have happened without you.

Our sincerest thanks to the whole O’Reilly team: Greg Corrin, Glenn Bisignani, Tony Artuso, and Kyle Hart all led Don’t let the sweater fool
the way on marketing and we appreciate their out-
you, this guy is hard core
of-the-box approach. Thanks to Ellie Volkhausen

(technically of course).

for her inspired cover design that continues to serve
us well, and to Karen Montgomery for stepping in and bringing life to this book’s cover. Thank you, as always, to Colleen Gorman for her hardcore copyedit (and for keeping it all fun). And, we couldn’t have pulled off a color book like this without Sue Willing and Claire Cloutier.

Brett McLaughlin

No Head First acknowledgment would be complete without thanking Mike Loukides for shaping the Head First concept into a series, and to Tim O’Reilly for always being there and his continued support. Finally, thanks to Mike Hendrickson for bringing us into the Head First family and having the faith to let us run with it.

Kathy Sierra

Kathy Sierra and Bert Bates:

Bert Bates

Last, and anything but least, to Kathy

Sierra and Bert Bates, our partners
in crime and the BRAINS who created the
series. Thanks guys for trusting us even more
with your baby. We hope once again we’ve
done it justice. The three-day jam session was
the highlight of writing the book, we hope to
repeat it soon. Oh, and next time around can
you give LTJ a call and tell him he’s just going
to have to make a trip back to Seattle?

Hard at work researching

Kara

Head First Parelli.

*The large number of acknowledgments is because we’re testing the theory that everyone mentioned in a book acknowledgment will buy at least one copy, probably more, what with relatives and everything. If you’d like to be in the acknowledgment of our next book, and you have a large family, write to us.

you are here� xxxv

1 getting to know HTML

The Language of the Web

Not so fast... to get to
know me you’ve got to speak the
universal language. You know,

HTML and CSS.

The only thing that is standing between you and getting
yourself on the Web is learning to speak the lingo:

HyperText Markup Language, or HTML for short. So, get ready for some language lessons. After this chapter, not only are you going to understand some basic elements of HTML, but you’ll also be able to speak HTML with a little style. Heck, by the end of this book you’ll be talking HTML like you grew up in Webville.

this is a new chapter

1

html powers the web

The Web

Video killed the radio star

Want to get an idea out there? Sell something? Just need a creative outlet? Turn to the Web – we don’t need to tell you it has become the universal form of communication. Even
better, it’s a form of communication YOU can participate in.

But, if you really want to use the Web effectively, you’ve got to know a few things about HTML, not to mention how the Web works. Let’s take a look from 30,000 feet:

Once you’ve put your files on
a Web server, any browser can

To make Web pages, you
retrieve your Web pages over
create files written in the
the Internet.

HyperText Markup Language

(HTML for short) and place
them on a Web server (we’ll
talk about how to get your
files on a server later in the
book).

The Internet

<html>

<head>

<title>

My Playlist

</title>

Web Server

<head>

<body>

<h1>Kick’n Tunes

</h1>

<p>BT - Satellite:

nice downbeat tune.

</p>

<p>

...

The HTML in your Web page tells the
browser everything it needs to know to

And there are a lot of PCs and devices
display your page. And, if you’ve done your
connected to the Internet all running Web
job well, your pages will even display well on
browsers. More importantly, there are

PDAs and mobile devices, and work with
friends, family, fans, and potential customers
speech browsers and screen magnifiers for
using those PCs!

the visually impaired.

2

Chapter 1

getting to know html

What does the Web server do?

Web servers have a full time job on the Internet, tirelessly waiting for requests from Web browsers. What kinds of requests? Requests for Web pages, images, sounds, or maybe even a movie. When a server gets a request for any of these resources, the server finds the resource, and then sends it back to the browser.

Browsers make

The server’s just a computer
requests for HTML
connected to the Internet waiting
pages or other
for requests from browsers.

resources, like images.

<html>

<head>

<title>

My Playlist

</title>

<head>

<body>

“I need the HTML f le ‘lounge.html’”

<h1>Kick’n Tunes

</h1>

<p>BT - Satellite:

nice downbeat tune.

</p>

<p>

...

<html>

<head>

<title>

My Playlist

</title>

<head>

<body>

<h1>Kick’n Tunes

</h1>

<p>BT - Satellite:

nice downbeat tune.

</p>

<p>

...

Each server

“Found it, here ya go”

stores HTML
files, pictures,
sounds and other

...and if the server can
file types.

Web Server
locate the resource, it
sends it to the browser.

What does the Web browser do?

You already know how a browser works: you’re surfing around the Web and you click on a link to visit a page. That click causes your browser to request an HTML page from a Web server, retrieve it, and display the page in your browser window.

...and the browser displays

The browser
the HTML page.

The server “serves up” <html> <head>
retr

<title>
ieves the page...

Web pages and sends

Head First Lounge

</title>
them to the browser. <head>

<body>

<h1>Welcome to Head

</h1>

<img src=”drinks.gi

<p>Join us any even

</p>

<p>

...

Web Server

But, how does the browser know how to display a page? That’s where HTML comes in. HTML tells the browser all about the content and structure of the page. Let’s see how that works...

you are here �

3

writing some html

What you write (the HTML)...

So, you know HTML is the key to getting a browser to display your pages, but, what exactly does HTML look like? And, what does it do?

Let’s have a look at a little HTML... imagine you’re going to create a Web page to advertise the Head First Lounge, a local hangout with some good tunes, refreshing elixirs, and wireless access. Here’s what you’d write in HTML:

<html>

<head>

A

<title> Head First Lounge</title>

</head>

<body>

B

<h1> Welcome to the Head First Lounge</h1>

<img src=”drinks.gif”>

C

<p>

D Join us any evening for refreshing elixirs,
conversation and maybe a game or

E
two of <em> Dance Dance Revolution</em> .

Wireless access is always provided;

BYOWS (Bring your own web server).

</p>

<h2> Directions</h2> F

<p>

You’ll find us right in the center of

G

downtown Webville. Come join us!

</p>

</body>

We don’t expect you to know

</html>

Relax HTML, yet.

At this point you should just be getting
a feel for what HTML looks like; we’re
going to cover everything in detail in a bit. For
now, study the HTML and see how it gets represented
in the browser on the next page. Be sure to pay careful
attention to each letter annotation and how and where
it is displayed in the browser.

4

Chapter 1

getting to know html

What the browser creates...

When the browser reads your HTML, it interprets all the tags that surround your text. Tags are just words or characters in angle brackets, like <head> , <p> , <h1> , and so on. The tags tell the browser about the structure and meaning of your text. So rather than just giving the browser a bunch of text, with HTML you can use tags to tell the browser what text is in a heading, what text is a paragraph, what text needs to be emphasized, or even where images need to be placed.

Let’s check out how the browser interprets the tags in the

Head First Lounge:

Notice how each tag in
the HTML maps to what
the browser displays.

A

B

C

E

D

F

G
you are here �

5
more about markup and tags
there are no

Dumb Questions

Q:

paragraph breaks occur.

extensions) to the end of the file name to

So HTML is just a bunch of tags

So why did we insert our own format ing if
give the operating system a bet er idea of
that I put around my text?

the browser is just going to ignore it? To
what the file is. But, as you’ve seen, what
help us more easily read the document when real y mat ers is what we put inside the file.

A:

we’re editing the HTML. As your HTML

For starters. Remember that HTML
documents become more complicated,

Q: Markup seems silly. What-you-
stands for HyperText Markup Language, so
you’l find a few spaces, returns, and tabs
see-is-what-you-get applications have

HTML gives you a way to “mark up” your
here and there real y help to improve the
been around since, what, the ‘70s? Why
text with tags that tel the browser how your
readability of the HTML.

isn’t the Web based on a format like
text is structured. But there is also the

Microsoft Word or a similar application?

HyperText aspect of HTML, which we’l talk

Q:

about a little later in the book.

So there are two levels of
headings, <h1> and a subheading <h2>?

Q:

A: The Web is created out of text files

How does the browser decide how
without any special format ing characters.

to display the HTML?

A: Actualy there are six, <h1>

This enables any browser in any part of
through <h6>, which the browser typical y
the world to retrieve a Web page and

A:

displays in successively smal er font sizes.

understand its contents. You’ll see that

HTML tells your browser about

Unless you are creating a complex and
on the Web, in many ways HTML is more
the structure of your document: where the
large document, you typically won’t use
powerful than using a proprietary document
headings are, where the paragraphs are,
headings beyond <h3>.

format.

what text needs emphasis, and so on.

Given this information, browsers have built-

Q:

Q: Is there any way to put comments
in default rules for how to display each of

Why do I need the <html> tag?

to myself in HTML?

these elements.

Isn’t it obvious this is a HTML document?

But, you don’t have to set le for the default
set ings. You can add your own style and

A:

A: Yes, if you place your comments
formatting rules with CSS that determine

The <html> tag tells the browser
in between <!-- and --> the browser will
font, colors, size, and a lot of other
your document is actual y HTML. While
some browsers wil forgive you if you omit
total y ignore them. Say you wanted to write
characteristics of your page. We’ll get back
it, some won’t, and as we move toward
a comment “Here’s the beginning of the
to CSS later in the chapter.

“industrial strength HTML” later in the book, lounge content”. You’d do that like this: Q:

you’ll see it is quite important to include

<!-- Here’s the beginning of

The HTML for the Head First
this tag.

the lounge content -->

Lounge has al kinds of indentation and
spacing, and yet I don’t see that when it

Q: What makes a file an HTML file?

is displayed in the browser. How come?

Notice that you can put comments on
multiple lines. Keep in mind anything you

A:

A:

put between the “<!--” and the “-->”, even

Basically an HTML file is a simple

Correct, and good catch. Browsers

HTML, will be ignored by the browser.

text file. Unlike a word processing file, there
ignore tabs, returns, and most spaces in
is no special format ing embedded in it. By

HTML documents. Instead, they rely on
convention we add a “.html” or “.htm” (on
your markup to determine where line and
systems that only support three let er file

6

Chapter 1

getting to know html

Sharpen your pencil

You’re closer to learning HTML than you think...

Here’s the HTML for the Head First Lounge again. Take a look at the tags and see if you can guess what they tell the browser about the content. Write your answers in the space on the right; we’ve already done the first couple for you.

Tells the browser this is the start of HTML..

<html>

Starts the page “head” (more about this later).

<head>

<title> Head First Lounge</title>

</head>

<body>

<h1> Welcome to the Head First Lounge</h1>

<img src=”drinks.gif”>

<p>

Join us any evening for refreshing elixirs,
conversation and maybe a game or
two of <em> Dance Dance Revolution</em> .

Wireless access is always provided;

BYOWS (Bring your own web server).

</p>

<h2> Directions</h2>

<p>

You’ll find us right in the center of
downtown Webville. Come join us!

</p>

</body>

</html>
you are here �

7

what the markup does

Sharpen your pencil
answers

Tells the browser this is the start of HTML.

<html>

Starts the page “head”.

<head>

Gives the page a title.

<title> Head First Lounge</title> End of the header.

</head>

Start of the body of page.

<body>

Tells browser that “Welcome to...” is a heading.

<h1> Welcome to the Head First Lounge</h1>

<img src=”drinks.gif”>

Places the image “drinks.gif” here.

<p>

Start of a paragraph.

Join us any evening for refreshing elixirs,
conversation and maybe a game or

Puts emphasis on Dance Dance Revolution.

two of <em> Dance Dance Revolution</em> .

Wireless access is always provided;

BYOWS (Bring your own web server).

</p>

End of paragraph.

<h2> Directions</h2>

Tells the browser that “Directions” is a subheading.

Start of another paragraph.

<p>

You’ll find us right in the center of
downtown Webville. Come join us!

</p>

End of paragraph.

</body>

End of the body.

</html>

Tells the browser this is the end of the HTML.

8

Chapter 1

getting to know html

Your big break at Starbuzz Coffee

Starbuzz Coffee has made a name for itself as the fastest
growing coffee shop around. If you’ve seen one on your local corner, look across the street – you’ll see another one.

In fact, they’ve grown so quickly, they haven’t even managed to put up a web page, yet... and therein lies your big break: By chance, while buying your Starbuzz Chai Tea, you run
into the Starbuzz CEO...

Word has it you
know a little about HTML.

We real y need a Web page
that features the Starbuzz
offerings. Can you help?

The Starbuzz CEO
brain
power

?

Decisions, decisions.

Check your first priority below (choose only one):

❏ A. Give dog a bath.

❏ C. Take the Starbuzz gig and launch

BIG-TIME Web career.

❏ B. Finally get my checking account

❏ D. Schedule dentist appointment.

balanced.

you are here �

9

what goes on the starbuzz page

Wonderful! We’re
so glad you’ll be helping us. *

Here’s what we need on our
first page...

Thanks for giving us a hand!

On the Web page we just need t
something simple (see below) tha

Starbuzz Cof eeS
e
t
includes the beverage names, prices,
a
e f
r
f
b
and descriptions.

o C z z u
ibbles

The CEO scr

House Blend, $1.49
something on a napkin
fees from Mexico, Bolivia
t to you...

A smooth, mild blend of cof
and hands i
and Guatemala.

Mocha Cafe Latte, $2.35

Espresso, steamed milk and chocolate syrup.

Cappuccino, $1.89

A mixture of espresso, steamed milk and foam.

Chai Tea, $1.85

A spicy drink made with black tea, spices, milk and honey.

Sharpen your pencil

Take a look at the napkin. Can you
determine the structure of it? In other
words, are there obvious headings?

Paragraphs? Is it missing anything like a
title?

Go ahead and mark up the napkin (using
your pencil) with any structure you see,
and add anything that is missing.

You’ll find our answers at the end of

* If by chance you chose options A, B, or D on the previous page, we Chapter 1.

recommend you donate this book to a good library, use it as kindling this winter, or what the hell, go ahead and sell it on Amazon and make some cash.

10

Chapter 1

getting to know html

Creating the Starbuzz Web page

Of course, the only problem with all this is that
you haven’t actually created any Web pages, yet.

But, that’s why you decided to dive head first
into HTML, right?

No worries, here’s what you’re going to do on
the next few pages:

1

Create an HTML file using your favorite
text editor.

2

Type in the menu the Starbuzz CEO wrote
on the napkin.

3

Save the file as “index.html”.

4

Open the file “index.html” in your favorite
browser, step back, and watch the magic
happen.

No pressure, but
thousands of people are
going to visit this Web page
when you’re finished. It not
only needs to be correct, it’s
gotta look great, too!

you are here �

11

writing html on a macintosh

Creating an HTML file (Mac)

All HTML files are text files. To create a text file you
need an application that allows you to create plain
text without throwing in a lot of fancy formatting and
special characters. You just need plain, pure text.

We’ll use TextEdit on the Mac in this book; however,
if you prefer another text editor, that should work
fine as well. And, if you’re running Windows, you’ll
want to skip ahead a couple of pages to the Windows
instructions.

Step one:

Navigate to your Applications folder

The TextEdit application is in the

Applications folder. The easiest way to get
there is to choose “New Finder Window”

from the Finder’s File menu and then look
for the Application directly in your shortcuts.

When you’ve found it, click on Applications.

Step two:

Locate and run TextEdit

You’ll probably have lots of applications listed

Here’s TextEdit.

in your applications folder, so scroll down
until you see TextEdit. To run the application,
double click on the TextEdit icon.

Your Finder
shortcuts.

Step three (optional):

Keep TextEdit in your Dock

If you want to make your life easier,
click and hold on the TextEdit icon in
the Dock (this icon appears once the
application is running). When it displays
a popup menu, choose “Keep in Dock.”

That way, the TextEdit icon will always
appear in your Dock and you won’t have
to hunt it down in the Applications folder
every time you need to use it.

12

Chapter 1

getting to know html

Step four:

Change your TextEdit Preferences

By default, TextEdit is in “rich text”

mode, which means it will add its own
formatting and special characters to
your file when you save it – not what
you want. So, you’ll need to change
your TextEdit Preferences so that

This text formatting menu

TextEdit saves your work as a pure
means you’re in “rich text”

text file. To do this, first choose the
mode. If you see these,

“Preferences” menu item from the
you need to change your

TextEdit menu.

preferences.

Step five:

Set Preferences for Plain text

Once you see the Preferences dialog
box, there are three things you need
to do.

First, choose “Plain text” as the
default editor mode in the New

Document tab.

Second, in the “Open and Save”

tab, make sure that the “Add .txt
extension to plain text files” is
unchecked.

Last, make sure “Ignore rich text
commands in HTML files” is
checked.

That’s it; to close the dialog box
click on the red button in the top
left corner.

Step six:

Quit and restart

Now quit out of TextEdit by choosing

Quit from the TextEdit menu, and then

See, the forma
restart the application. This time, you’ll
tting menu
is gone: that means w
see a window with no fancy text formatting
e’re
in text mode.

menus at the top of the window. You’re
now ready to create some HTML.

you are here �

13

writing html on windows

Creating an HTML file (Windows)

If you’re reading this page you must be a Windows XP user. If not, Or another version of Windows.

you might want to skip a couple of pages ahead. Or, if you just want to sit in the back and not ask questions, we’re okay with that too.

To create HTML files in XP we’re going to use Notepad – it ships with every copy of Windows, the price is right, and it’s easy to use. If If you’re using another
you’ve got your own favorite editor that runs on XP, that’s fine too; just version of Windows you’ll
make sure you can create a plain text file with an “.html” extension.

find Notepad there as well.

Assuming you’re using Notepad, here’s how you’re going to create your first HTML file.

Step one:

Open the Start menu and navigate to Notepad

You’ll find the Notepad application in Accessories. The
easiest way to get there is to click on the “Start” menu,
then on “All Programs”, then “Accessories”. You’ll see

Notepad listed there.

14

Chapter 1

getting to know html

Step two:

Open Notepad

Once you’ve located Notepad in the

Accessories folder, go ahead and click
on it. You’ll see a blank window ready
for you to start typing HTML.

But recommended.

Step three (optional):

Don’t hide extensions of well
known file types.

By default XP’s File Explorer hides the
file extensions of well known file types.

For example, a file named, “Irule.html”

will be shown in the Explorer as “Irule”

without its “.html” extension.

It’s much less confusing if XP shows
you these extensions, so let’s change
your folder options so you can see the
file extensions.

First, in any Explorer window select

“Folder Options...” from the Tools
menu.

Next, in the “View” tab, under

“Advanced settings”, scroll down until
you see “Hide extensions for known file
types” and uncheck this option.

That’s it. Click on the OK button to
save the preference and you’ll now see
the file extensions in the Explorer.

you are here �

15
editors and html
there are no

Dumb Questions

Q: Why am I using a simple text

A: The simple answer: use whatever
editor? Aren’t there powerful tools like
browser you like. HTML and CSS are

Dreamweaver, FrontPage and GoLive for
industry standards, which means that all
creating Web pages?

browsers try to support HTML and CSS in
the same way (just make sure you are using

A:

the newest version of the browser for the

You’re reading this book because
best support).

you want to understand the true technologies The complex answer: in reality there are used for Web pages, right? Now those are all slight dif erences in the way browsers great tools, but they do a lot of the work for
handle your pages. If you’ve got users who
you, and until you are a master of HTML and
wil be accessing your pages in a variety of

CSS you want to learn this stuf without a big
browsers, then always test your web page
tool get ing in your way.

in several dif erent browsers. Some pages

Once you’re a master, however, these tools
wil look exactly the same; some won’t. The
do provide some nice features like syntax
more advanced you become with HTML and
checking and previews. At that point,

CSS, the more these slight dif erences may
when you view the “code” window, you’ll
matter to you, and we’ll get into some of
understand everything in it, and you’l find
these subtleties throughout the book.

that changes to the raw HTML and CSS are

If you’re looking for a good browser, give
often a lot faster than going through a user

Mozilla’s Firefox a try; it has very good
interface. You’l also find that as standards

HTML and CSS support.

change, these tools aren’t always updated
right away and may not support the most

Q:

recent standards until their next release

I’m creating these files on my own
cycle. Since you’l know how to change the
computer – how am I going to view these

HTML and CSS without the tool, you’ll be
on the Web/Internet?

able to keep up with the latest and greatest
all the time.

A: That’s one great thing about HTML:

Q:

you can create files and test them on your

I get the editor, but what browser
own computer and then later publish them
am I supposed to be using? There are so
on the Web. Right now we’re going to worry
many – Internet Explorer, Firefox, Opera,
about how to create the files and what goes

Safari – what’s the deal?

in them. We’ll come back to getting them on
the Web a bit later.

16

Chapter 1

getting to know html

Meanwhile, back at Starbuzz Coffee...

Okay, now that you know the basics of creating a plain text file, you just need to get some content into your text editor, save it, and then load it into your browser.

Start by typing in the beverages straight from the CEO’s napkin; these beverages are the content for your page. You’ll be adding some HTML
markup to give the content some structure in a bit, but for now, just get the basic content typed in. While you’re at it, go ahead and add “Starbuzz Coffee Beverages” at the top of the file.

Type in the info from
the napkin like this.

Mac

Windows
you are here �

17

saving your html

Saving your work...

Once you’ve typed in the beverages from the CEO’s napkin,
you’re going to save your work in a file called “index.html”.

Before you do that, you’ll want to create a folder named

“starbuzz” to hold the site’s files.

To get this all started, choose “Save” from the File menu and you’ll see a “Save As” dialog box. Then, here’s what you need to do:

Windows

1 First, create a “starbuzz” folder
for all your Starbuzz related
files. You can do this with the

New Folder button.

Create a new
folder here.

Mac

Windows

Using Windows you need to also
choose “All Files” as your type,
otherwise Notepad will add a

“.txt” to your filename.

Create a new
folder here.

2 Next, click on the newly created

“starbuzz” folder and then enter

“index.html” as the file name and click
on the Save button.

18

Chapter 1

getting to know html

Opening your Web page
in a browser

Are you ready to open your first Web page? Using your
favorite browser, choose “Open File...” (or “Open...”

using Windows XP and Internet Explorer) from the

File menu and navigate to your “index.html” file. Select
it and click “Open”.

Mac

On the Mac, navigate to your
file, and select it by clicking
on the file icon and then on
the Open button.

In Windows Internet Explorer it’s
a two step process. First you’ll
get the open dialog box.

Windows

Then click “Browse” to get a
browse dialog and navigate to
where you saved your file.

you are here �

19

testing your html

Taking your page for a

Windows
test drive...

Success! You’ve got the page loaded in
the browser, although the results are
a little... uh... unsatisfying. But that’s
just because all you’ve done so far is go
through the mechanics of creating a page
and viewing it in the browser. And, so
far, you’ve only typed in the content of the

Web page. That’s where HTML comes
in. HTML gives you a way to tell the
browser about the structure of your page.

What’s structure? As you’ve already seen,
it is a way of marking up your text so
that the browser knows what’s a heading,
what text is in a paragraph, what text is a
subheading, and so on. Once the browser
knows a little about the structure, it can
display your page in a more meaningful
and readable manner.

Mac

Depending on your
operating system and browser,
often you can just double-click
the HTML file or drag it on top
of the browser icon to open it.

Much simpler.

20

Chapter 1

getting to know html

Markup Magnets

So, let’s add that structure. .

Your job is to add structure to the text from the Starbuzz napkin.

Use the fridge magnets at the bottom of the page to mark up the text so that you’ve indicated which parts are headings, subheadings and paragraph text. We’ve already done a few to get you started.

You won’t need all the magnets below to complete the job; some will be left over.

<h1> Starbuzz Coffee Beverages </h1>

House Blend, $1.49

A smooth, mild blend of coffees from Mexico, Bolivia
and Guatemala.

<h2>

Mocha Cafe Latte, $2.35 </h2>

Espresso, steamed milk and chocolate syrup.

<p>

</p>

Cappuccino, $1.89

A mixture of espresso, steamed milk and foam.

Chai Tea, $1.85

A spicy drink made with black tea, spices, milk and
honey.

<p>

</p>

</h2>

<p>

</p>

</h1>

<h2>

</h1>

</p>

<h1>

<p>

<h1>

</h1>

<h2>

</h2>

<h1>

</h1>

<h2>

Use this magnet

Use this magnet

Use this magnet

Use this
to end a
to start a
to end a
magnet to
paragraph.

heading.

Use this magnet

Use this magnet subheading.

start a
to end a heading.

to start a
subheading.

paragraph.

you are here �

21

your first html markup

Congratulations,
you’ve just written
your first HTML!

They might have looked like fridge
magnets, but you were really marking up
your text with HTML. Only, as you know,
we usually refer to the magnets as tags.

Check out the markup below and compare it to
your magnets on the previous page.

Use the <h1> and </h1> tags to mark
headings. All the text in between is
the actual content of the heading.

<h1> Starbuzz Coffee Beverages</h1>

<h2> House Blend, $1.49</h2>

The <h2> and </h2> tags

<p> A smooth, mild blend of coffees from Mexico, go around a subheading.

Think of an <h2> heading

Bolivia and Guatemala. </p>
as a subheading of an <h1>
heading.

<h2> Mocha Cafe Latte, $2.35</h2>

<p> Espresso, steamed milk and chocolate syrup. </p> The <p> and </p> tags

<h2> Cappuccino, $1.89</h2>
go around a block of
tex

<p> A mixture of espresso, steamed milk and foam. </p> t that is a paragraph.

That can be one or many
sentences.

<h2> Chai Tea, $1.85</h2>

<p> A spicy drink made with black tea, spices, milk and honey. </p>

Notice that you don’t have to put ma
tags on the same line. Y
tching
ou can put as much
content as you like between them.

22

Chapter 1

getting to know html

Are we there yet?

You have an HTML file with markup – does that make a Web page? Almost.

You’ve already seen the <html> , <head> , <title> , and <body> tags, and we just need to add those to make this a first class HTML page...

he

First, surround your

Next add <head> and </head> tags. T

HTML with <html> &
head contains information about your Web

Go ahead and put a title

</html> tags. This tells page, like its title. For now, think about it inside the head. The title
the browser the content this way: the head allows you to tell the eb page.

usually appears at the top
of the file is HTML.

browser things about the W
of the browser window.

<html>

<head>

The head consists of the <head>

<title> Starbuzz Coffee</title>

& </head> tags and everything

</head>
in between.

<body>

<h1> Starbuzz Coffee Beverages</h1>

<h2> House Blend, $1.49</h2>

<p> A smooth, mild blend of coffees from Mexico, Bolivia and Guatemala. </p>

The body consists
of the <body>

<h2> Mocha Cafe Latte, $2.35</h2>

& </body> tags

<p> Espresso, steamed milk and chocolate syrup. </p> and everything in
between.

<h2> Cappuccino, $1.89</h2>

<p> A mixture of espresso, steamed milk and foam. </p>

<h2> Chai Tea, $1.85</h2>

<p> A spicy drink made with black tea, spices, milk and honey. </p>

</body>

</html> The body contains a

Keep your
ll the content and
struc
head and body
ture of your Web page – the parts of
separate when
the Web page that you see in your browser.

writing HTML.

you are here �

23

another test with some markup

Another test drive...

Go ahead and change your “index.html” file by adding
in the <head>, </head>, <title>, </title>, <body> and

</body> tags. Once you’ve done that, save your changes and reload the file into your browser.

Notice that the title,
which you specified in
the <head> element,

You can reload the index.html file by
shows up here.

selecting the “Open File” menu item again,
or by using your browser’s reload button.

Now things look a bit better.

The browser has interpreted
your tags and created a
display for the page that is
not only more structured but
also more readable.

Sweet!

24

Chapter 1

getting to know html

Tags dissected...

Okay, you’ve seen a bit of markup, so let’s zoom in
and take a look at how tags really work...

You usually put tags around some piece of content.

Here we’re using tags to tell the browser that our
content, “Starbuzz Coffee Beverages”, is a top

This is the closing tag
level heading (that is, heading level one).

that ends the heading;
in this case the </h1>
tag is ending an <h1>

Here’s the opening tag
heading. You know it’s
that begins the heading.

a closing tag because
it comes after the
content, and it’s got
a “/” before the “h1”.

e a

All closing tags hav

<h1> Starbuzz Coffee Beverages </h1> “/” in them.

The whole shebang is called an element. In this case we
can call it the <h1> element. An element consists of the Tags consist of the tag name ters. enclosing tags and the content in between.

surrounded by angle brackets;

We call an opening tag
that is, the < and > charac
and its closing tag
matching tags.

To tell the browser about the structure of your
page, use pairs of tags around your content.

Remember,

Element = Opening Tag + Content + Closing Tag
you are here �

25
elements and matching tags
there are no

Dumb Questions

Q: So matching tags don’t have to be Q: I’ve noticed the HTML in some A: Wow, sharp eye. There are some on the same line?

pages doesn’t always match opening
elements that use a shorthand notation with
tags with closing tags.

only one tag. Keep that in the back of your

A:

mind for now and we’l come back to it in a

No; remember the browser doesn’t
later chapter.

real y care about tabs, returns, and most

A: Well, the tags are supposed to
spaces. So, your tags can start and end
match. In general, browsers do a pretty

Q:

anywhere on the same line or they can start
good job of figuring out what you mean if you

An element is an opening tag +
and end on dif erent lines. Just make sure
write incorrect HTML. But, as you’re going
content + closing tag, but can’t you have
you start with an opening tag, like <h2>, and to see, these days there are big benefits to tags inside other tags? Like the head and
end with a closing tag, like </h2>.

writing total y correct HTML. If you’re worried body are inside an <html> tag?

Q:

you’l never be able to write perfect HTML,
don’t be; there are plenty of tools to verify

Why do the closing tags have that your code before you put it on a Web server A: Yes, HTML tags are often “nested”

extra “/”?

so the whole world can see it. For now, just
like that. If you think about it, it’s natural
get in the habit of always matching your
for an HTML page to have a body, which

A:

opening tags with closing tags.

contains a paragraph, and so on. So many

That “/” in the closing tag is to help

HTML elements have other HTML elements
both you and the browser know where a

Q:

between their tags. We’l take a good look
particular piece of structured content ends.

Well, what about that <img
at this kind of thing in later chapters, but

Otherwise, the closing tags would look just
src=”drinks.gif”> tag in the lounge
for now just get your mind noticing how the
like the opening tags, right?

example? Did you forget the closing tag? elements relate to each other in a page.

brain
power

?

Tags can be a little more interesting than what you’ve seen so far. Here’s the paragraph tag with a little extra added to it. What do you think this does?

<p id=”houseblend”> A smooth, mild
blend of coffees from Mexico, Bolivia
and Guatemala. </p>

26

Chapter 1

getting to know html

Oh, I forgot to mention,
we need our company mission

Exercise
on a page, too. Grab the mission
statement off one of our coffee
cups and create another page
for it...

Starbuzz Cof ee’s

Mission

To provide al the
caf eine that you
need to power your
life.

Just drink it.

1 Write the HTML for the new

“mission.html” page here.

2 Type in your HTML using a
text editor, and save it as

“mission.html” in the same
folder as your “index.html”

file.

3 Once you’ve done that, open

“mission.html” in your browser.

4 Check your work at the end
of the chapter before moving
on...

you are here �

27

using css for style

Okay, it looks like you’re
getting somewhere. You’ve
got the main page and the mission
page all set. But, don’t forget the

CEO said the site needs to look
great too. Don’t you think it
needs a little style?

Right. We have the
structure down, so now
we’re going to concentrate
on its presentation.

You already know that HTML gives
you a way to describe the structure
of the content in your files. When the
browser displays your HTML, it uses
its own built-in default style to present
this structure. But, relying on the
browser for style obviously isn’t going
to win you any “designer of the month”

awards.

That’s where CSS comes in. CSS
gives you a way to describe how your
content should be presented. Let’s get

CSS is an abbreviation
our feet wet by creating some CSS that
for Cascading Style
makes the Starbuzz page look a little

Sheets. We’ll get into
more presentable (and launch your
what that all means

Web career in the process).

later, but for now
just know that CSS
gives you a way to
tell the browser how
elements in your page
should look.

28

Chapter 1
getting to know html

Meet the style element

To add style, you add a new (say it with us) E-L-E-M-E-N-T
to your page – the <style> element. Let’s go back to the main Starbuzz page and add some style. Check it out...

The <style> element is placed inside the
head of your HTML.

Just like other elements, the <style>

<html>
element has an opening tag, <style>,

<head>
and a closing tag, </style>...

<title> Starbuzz Coffee</title>

...but, the <style> tag a

<style type=”text/css”>
lso requires an
attribute, called type, which tells the
browser the kind of style you’re using.

Because you’re going t

</style>
o use CSS, you
need to specify the “tex

</head>
t/css” type.

And, here’s where you’re

<body>
going to define the styles

<h1> Starbuzz Coffee Beverages</h1>
for the page.

<h2> House Blend, $1.49</h2>

<p> A smooth, mild blend of coffees from Mexico, Bolivia and Guatemala. </p>

<h2> Mocha Caffe Latte, $2.35</h2>

<p> Espresso, steamed milk and chocolate syrup. </p>

<h2> Cappuccino, $1.89</h2>

<p> A mixture of espresso, steamed milk and milk foam. </p>

<h2> Chai Tea, $1.85</h2>

<p> A spicy drink made with black tea, spices, milk and honey. </p>

</body>

</html>
there are no

Dumb Questions

Q: An element can have an “attribute?” What does that Q: Why do I have to specify the type of the style, mean?

“text/css”, as an attribute of the style? Are there other kinds of style?

A: Atributes give you a way to provide additional information about an element. Like, if you have a style element, the at ribute A: There aren’t currently any other styles that work with
al ows you to say exactly what kind of style you’re talking about.

today’s browsers, but those designers of HTML are always

You’ll be seeing a lot more attributes for various elements; just planning ahead and anticipate that there may be other types of remember they give you some extra info about the element.

style in the future. Personally, we’re holding our breath for the

<style type=“50sKitsch”> style.

you are here �

29

adding a style element

Giving Starbuzz some style...

Now that you’ve got a <style> element in the HTML head, al you need to do is supply some CSS to give the page a little pizazz. Below you’ll find some CSS
already “baked” for you. Whenever you see the R e a d y logo, you’re seeing Bake

HTML and CSS that you should type in as-is. Trust us. You’ll learn how the markup works later, after you’ve seen what it can do.

So, take a look at the CSS and then add it to your “index.html” file. Once you’ve got it typed in, save your file.

Ready Bake

CSS

<html>

<head>

<title> Starbuzz Coffee</title>

<style type=”text/css”>

body {

background-color: #d2b48c;

margin-left: 20%;

margin-right: 20%;

border: 1px dotted gray;

CSS uses a syntax that

padding: 10px 10px 10px 10px;
is totally different from

font-family: sans-serif;

HTML.

}

</style>

</head>

<body>

<h1> Starbuzz Coffee Beverages</h1>

<h2> House Blend, $1.49</h2>

<p> A smooth, mild blend of coffees from Mexico, Bolivia and Guatemala. </p>

<h2> Mocha Caffe Latte, $2.35</h2>

<p> Espresso, steamed milk and chocolate syrup. </p>

<h2> Cappuccino, $1.89</h2>

<p> A mixture of espresso, steamed milk and milk foam. </p>

<h2> Chai Tea, $1.85</h2>

<p> A spicy drink made with black tea, spices, milk and honey. </p>

</body>

</html>

30

Chapter 1

getting to know html

Cruisin’ with style...

It’s time for another test drive, so reload your “index.html” file again.

This time you’ll see the Starbuzz Web page has a whole new look.

Background color is now tan.

Now we have margins
around the content.

Margin

We’ve got a gray border around
the content as well...

There’s now some
padding between the
content and the
border (on all sides).

We’re using a
different font for
a cleaner look.

Whoa! Very nice. We’re in
business now!

you are here �

31

looking more closely at css

Even though you’ve just glanced at CSS, you’ve already begun to see what it can do. Match each line in the style definition to what it does.

Defines the font to use for text.

background-color: #d2b48c;

Defines a border around the body that
margin-left: 20%;
margin-right: 20%;
is dotted and the color gray.

border: 1px dotted gray;

Sets the left and right margins to take
up 20% of the page each.

padding: 10px 10px 10px 10px;

Sets the background color to a tan
color.

font-family: sans-serif;

Creates some padding around the
body of the page.

there are no

Dumb Questions

Q: CSS looks like a totaly different is good at what it does, this is actually easier Q: Why is there a “body” in front of language than HTML. Why have two
than if you had to use one language to do
the CSS rules? What does that mean?

languages? That’s just more for me to
both jobs.

learn, right?

Q:

A: The “body” in the CSS means that

A:

#d2b48c doesn’t look like a color. all the CSS between the “{” and “}” applies to You are quite right that HTML and

How is #d2b48c the color “tan”?

content within the HTML <body> element.

CSS are completely dif erent languages,

So when you set the font to sans-serif,
but that is because they have very different

A:

you’re saying that the default font within the
jobs. Just like you wouldn’t use English to

There are a few dif erent ways to
body of your page should be sans-serif.

balance your checkbook, or Math to write a
specify colors with CSS. The most popular is We’l go into a lot more detail about how poem, you don’t use CSS to create structure called a “hex code”, which is what #d2b48c CSS works shortly, so keep reading. Soon,
or HTML to create style because that’s not
is. This real y is a tan color. For now, just go you’l see that you can be a lot more specific what they were designed for. While it does
with it, and we’l be showing you exactly how about how you apply these rules, and by mean you need to learn two languages,

#d2b48c is a color a little later.

doing so you can create some pretty cool
you’l discover that because each language
designs.

32

Chapter 1

getting to know html

Now that you’ve put a little style in the Starbuzz “index.html” page, go ahead and update your “mission.html” page to have the same style.

Exercise

1 Write the HTML for the “mission.html” page below, and then add the new CSS.

2 Update your “mission.html” file to include the new CSS.

3 Once you’ve done that, reload “mission.html” in your browser.

4 Make sure your mission page looks like ours, at the end of the chapter.

you are here �

33

content and style

Tonight’s talk: HTML and CSS on content and style.

HTML

CSS

Greetings CSS; I’m glad you’re here because

I’ve been wanting to clear up some confusion
about us.

Really? What kind of confusion?

Lots of people think that my tags tel the
browsers how to display the content. It’s just not true! I’m all about structure, not presentation.

Heck yeah - I don’t want people giving you
credit for my work!

Wel , you can see how some people might get
confused; after al , it’s possible to use HTML
without CSS and still get a decent-looking page.

“Decent” might be overstating it a bit, don’t you
think? I mean, the way most browsers display
straight HTML looks kinda crappy. People
need to learn how powerful CSS is and how
easily I can give their web pages great style.

Hey, I’m pretty powerful too. Having your
content structured is much more important
than having it look good. Style is so superficial;
it’s the structure of the content that matters.

Get real! Without me web pages would be
pretty damn boring. Not only that, take away
the ability to style pages and no one is going to
take your pages seriously. Everything is going
to look clumsy and unprofessional.

Whoa, what an ego! Wel I guess I shouldn’t
expect anything else from you – you’re just
trying to make a fashion statement with al that
style you keep talking about.

34

Chapter 1
getting to know html

HTML

CSS

Fashion statement? Good design and layout
can have a huge effect on how readable and
usable pages are. And you should be happy
that my flexible style rules allow designers to
do all kinds of interesting things with your
elements without messing up your structure.

Right. In fact we’re total y different languages,
which is good because I wouldn’t want any of
your style designers messing with my structure
elements.

Don’t worry, we’re living in separate universes.

Yea, that is obvious to me any time I look at

CSS – talk about an alien language.

Yeah, like HTML can be called a language?

Who has ever seen such a clunky thing with all
those tags?

Mil ions of web writers would disagree with you.

I’ve got a nice clean syntax that fits right in with
the content.

Just take a look at CSS; it’s so elegant and
simple, no goofy angle brackets <around>

<everything>. <See> <I> <can><talk>

<just><like><Mr.><HTML><,><look><at>

<me><!>

Hey stupid, ever heard of closing tags?

Just notice that no matter where you go, I’ve
got you surrounded by <style> tags. Good luck
escaping!

Ha! I’ll show you... because, guess what? I can
escape...

you are here �

35

review of basic html and css

Not only is this one fine cup of

House Blend, but now we’ve got a web
page to tell all our customers about our
coffees. Excellent work.

I’ve got some bigger ideas for the future;
in the meantime, can you start thinking
about how we are going to get these
pages on the Internet so other people
can see them?

BULLET POINTS

� HTML and CSS are the languages we use

� Closing tags have a “/” after the left
to create web pages.

angle bracket, in front of the tag name to

� Web servers store and serve Web pages,
distinguish them as closing tags.

which are created from HTML and CSS.

� Your pages should always have an <html>

Browsers retrieve pages and render their
element along with a <head> element and
content based on the HTML and CSS.

a <body> element.

� HTML is an abbreviation for HyperText

� Information about the Web page goes into

Markup Language and is used to structure
the <head> element.

your web page.

� What you put into the <body> element is

� CSS is an abbreviation for Cascading
what you see in the browser.

Style Sheets, and is used to control the

�
presentation of your HTML.

Most whitespace (tabs, returns, spaces)

are ignored by the browser, but you can

� Using HTML we mark up content with tags
use these to make your HTML more
to provide structure. We call matching
readable (to you).

tags, and their enclosed content, elements.

� CSS can be added to an HTML Web page

� An element is composed of three parts:

by putting the CSS rules inside the <style>
an opening tag, content and a closing tag.

element. The <style> element should

There are a few elements, like <img>, that
always be inside the <head> element.

are an exception to this rule.

� You specify the style characteristics of the

� Opening tags can have attributes. We’ve
elements in your HTML using CSS.

seen a couple: type and align.

36

Chapter 1

getting to know html

HTMLcross

It’s time to sit back and give your left brain something
to do. It’s your standard crossword; all of the solution
words are from this chapter.

1

2

1

2

3

3

4

5

4

5

6

6

6

6

7

8

9

7

8

9

10

11

12

10

11

12

13

13

14

14

15

15

16

16

17

17

18

18

Across

Down

Across

4. We emphasized this.

Down

1. What you see in your page.

4. We emphasized this.

5. Always separate these in HTML.

1. What you see in your page.

2. The "M" in HTML.

5. Always separate these in HTML.

7. CSS is used when you need to control this.

2. The "M" in HTML.

3. Browsers ignore this.

7. CSS is used when you need to control this.

11. You markup content to provide this.

3. Browsers ignore this.

6. Style we're all waiting on.

11. You markup content to provide this.

14. Only style available.

6. Style we're all waiting on.

8. Tags can have these to provide additional

14. Only style available.

15. About your web page.

8. Tags can have these to provide additional
information.

15. About your web page.

16. Two tags and content.

information.

9. Purpose of <p> element.

16. Two tags and content.

17. You define presentation through this tag.

9. Purpose of <p> element.

10. Appears at the top of the browser for each

17. You define presentation through this tag.

18. Company that launched your web career.

10. Appears at the top of the browser for each
page.

18. Company that launched your web career.

page.12. Opening and closing.

12. Opening and closing.

13. There are six of these.

13. There are six of these.

you are here �

37

exercise solutions

Sharpen your pencil

Go ahead and mark up the napkin (using your pencil) with any structure you see, and add anything that is missing.

Solution

Not going to be part
of the web page

Thanks for giving us a hand!

On the Web page we just need t
something simple (see below) tha

Starbuzz Cof eeS

Add a page heading.

e
t
includes the beverage names, prices
a
e f
r
f
b
zz Coffee and descriptions.

o C

Starbu z z u

Beverages

House Blend, $1.49
fees from Mexico, Bolivia

A sub-heading..

A smooth, mild blend of cof
and Guatemala.

Mocha Cafe Latte, $2.35

Paragraphs.

Espresso, steamed milk and chocolate syrup.

Another sub-heading.

Cappuccino, $1.89

A mixture of espresso, steamed milk and foam.

More sub-headings.

Chai Tea, $1.85

A spicy drink made with black tea, spices, milk and honey.

38

Chapter 1

getting to know html

Markup Magnets Solution

Your job is to add some structure to the text from the Starbuzz napkin. Use the fridge magnets at the bottom of the page to mark up the text so that you’ve indicated which parts are headings, subheadings and paragraph text. We’ve already done a few to get you started. You won’t need all the magnets below to complete the job; some will be left over.

<h1> Starbuzz Coffee Beverages </h1>

<h2> House Blend, $1.49 </h2>

A smooth, mild blend of coffees from Mexico, Bolivia

<p>
and Guatemala. </p>

<h2>

Mocha Cafe Latte, $2.35 </h2>

Espresso, steamed milk and chocolate syrup.

<p>

</p>

Cappuccino, $1.89 </h2>

<h2>

A mixture of espresso, steamed milk and foam. </p>

<p>

<h2> Chai Tea, $1.85 </h2>

<p>

A spicy drink made with black tea, spices, milk and
honey. </p>

</h1>

<h1>

<h1>

</h1>

<h1>

</h1>
you are here �

39

exercise solutions

<html>

<head>

Exercise

<title>Starbuzz Coffee’s Mission</title>

Solutions

</head>

<body>

<h1>Starbuzz Coffee’s Mission</h1>

<p>To provide all the caffeine that you need to
power your life.</p>

Starbuzz Cof ee’s

Mission

<p>Just drink it.</p>

To provide al the
caf eine that you
need to power your

</body>
life.

Just drink it.

</html>

Here’s the HTML.

Here’s the HTML
displayed in a browser.

40

Chapter 1

getting to know html

Exercise

<html>

Solutions

<head>

<title>Starbuzz Coffee’s Mission</title>

<style type=”text/css”>
body {
background-color: #d2b48c;
margin-left: 20%;
margin-right: 20%;
border: 1px dotted gray;
padding: 10px 10px 10px 10px;
font-family: sans-serif;

}

</style>

</head>

<body>

<h1>Starbuzz Coffee’s Mission</h1>

<p>To provide al the caffeine that you need to power your life.</p>

<p>Just drink it.</p>

</body>

</html>
you are here �

41

exercise solutions

Even though you’ve just glanced at CSS, you’ve already seen the beginnings Exercise
of what it can do. Match each line in the style definition to what it does.

Solutions

Defines the font to use for text.

background-color: #d2b48c;

Defines a border around the body that
margin-left: 20%;
is dotted and the color gray.

margin-right: 20%;

Sets the left and right margins to take
border: 1px dotted gray;
up 20% of the page each.

Sets the background color to a tan
padding: 10px 10px 10px 10px;
color.

font-family: sans-serif;

Creates some padding around the
body of the page.

42

Chapter 1

2 going further, with hypertext

Meeting the ‘HT’ in HTML

Right, that’s me, they

You’re not
call me Hyper Ted.

listening. I came here
to meet HyperTEXT!

Did someone say “hypertext?” What’s that? Oh, only the entire basis of the Web. In Chapter 1 we kicked the tires of HTML and found it to be a nice markup language (the ‘ML’ in HTML) for describing the structure of Web pages. Now we’re going to check out the ‘HT’ in HTML, hypertext, which will let us break free of a single page and link to other pages. Along the way we’re going to meet a powerful new element, the <a> element, and learn how being “relative” is a groovy thing. So, fasten your seat belts – you’re about to learn some hypertext.

this is a new chapter

43

improving the head first lounge

Head First Lounge, New and Improved

Remember the Head First Lounge? Great site, but wouldn’t it be nice if customers could view a list of the refreshing elixirs? Even better, we should give customers some real driving directions so they can find the place.

Here’s the new
and improved
page.

The “elixirs” link points to a page
tions.

with a full list of elixir selec

We’ve added
links to two
new pages, one
for elixirs and
one for driving
directions.

The “detailed directions”

link leads to an HTML page
with driving directions.

directions.html

44

Chapter 2

going further with hypertext

A page listing some
refreshing and healthy

drinks. Feel free to grab
one before going on.

Creating the new and improved
lounge in three steps...

Let’s rework the original Head First Lounge
page so it links to the two new pages.

1

The first step is easy because we’ve already
created the “directions.html” and

“elixir.html” files for you.

You’ll find them in the

Ready
source files for the book,

Bake
which are available at
http://www.headfirstlabs.com.

elixir.html

2

Next you’re going to edit the “lounge.html”

file and add in the HTML needed to link to

“directions.html” and “elixir.html”.

3

Last, you’ll give the pages a test drive and
try out your new links. When you get back
we’ll sit down and look at how it all works.

Flip the page and let’s get started...

you are here �

45

looking at the source files

Creating the new lounge

1

Grab the source files

Go ahead and grab the source files from http://www.headfirstlabs.com. Once you’ve downloaded them, look under the folder “chapter2/lounge” and you’ll find

“lounge.html”, “elixir.html”, and “directions.html” (and a bunch of image files).

Here’s the current lounge
file, without links.

<html>

.

.

.

</html>

You’ll find the lounge directory
here in your source files.

lounge.html
chapter2

Two new files, already

<html>

.

.

written for you. Go

.

</html>
ahead and take a
elixir.html

All the lounge files
peek - you already know
lounge
are in this folder.

everything you need to

<html>
understand them.

.

.

.

</html>
directions.html
green.jpg
blue.jpg

And here’s all the
drinks.gif
images needed
for our new and
lightblue.jpg
red.jpg
improved lounge.

brain
power

A

The Head First Lounge is already growing; do you think that keeping all the site’s files in a single directory is a good way to organize the site? What would you do differently?

46

Chapter 2
going further with hypertext

2

Edit lounge.html

Open “lounge.html” in your editor. Add the new text and HTML that is highlighted below.

Go ahead and type this in; we’ll come back and see how it all works on the next page.

<html>

<head>

Let’s add “New and Improved” to the heading.

<title> Head First Lounge</title>

</head>

<body>

<h1> Welcome to the New and Improved Head First Lounge</h1>

<img src=”drinks.gif”>

Here’s where we add the HTML for the link to the elixirs.

<p>

Join us any evening for

To create links we use the
refreshing <a href=”elixir.html”> elixirs</a> ,

<a> element; we’ll take a
conversation and maybe a game or two of
look at how this element
works in just a sec...

<em> Dance Dance Revolution</em> .

Wireless access is always provided;

BYOWS (Bring your own web server).

We need to add some text

</p>
here to point customers to

<h2> Directions</h2>
the new directions.

<p>

You’ll find us right in the center of downtown Webville.

If you need help finding us, check out
our <a href=”directions.html”> detailed directions</a> .

Come join us!

</p>

</body>

And here’s where we add the link to the directions, again using an <a> element.

</html>

3

Save lounge.html and give it a test drive.

When you’re finished with the changes, save the file “lounge.html” and open it in your browser. Here are a few things to try...

1

Click on the elixir link and the new elixir page will display.

2

Click on the browser’s back button and “lounge.html”

should be displayed again.

3

Click on the directions link and the new directions page will display.

you are here �

47

how to create links

Okay, I’ve loaded the

Behind
new lounge page, clicked
the links, and everything
the Scenes
worked. But, I want to
make sure I understand
how the HTML works.

What did we do?

Let’s step through creating the HTML links. First we need to put 1
the text we want for the link in an <a> element, like this:

<a>elixirs</a>

<a>driving directions</a>

The <a> element is used t
create a link t
o

The content of the <a> element acts as a label for the o another page.

link. In the browser the label appears with an underline
to indicate you can click on it.

2

Now that we have a label for each link, we need to add some HTML to tell the browser where the link points to:

For this link, the browser will
display an “elixirs” label that,
when clicked, will take the user

<a href=”elixir.html”>elixirs</a> to the “elixir.html” page.

The href attribute is
how you specify the

And for this link, the browser will display a
destination of the link.

“driving directions” link that, when clicked, will
take the user to the “directions.html” page.

<a href=”directions.html”>driving directions</a> 48

Chapter 2

going further with hypertext

What does the browser do?

Behind

First, as the browser renders the page, if it encounters an <a> 1
the Scenes
element, it takes the content of the element and displays it as a clickable link.

<a href=”elixir.html”>elixirs</a>

Both “elixirs” and “detailed
directions” are between the
opening and closing <a> tags,
so they end up being clickable
labels in the web page.

<a href=”directions.html”>detailed directions</a> Use the <a> element to create a hypertext link to another web page.

The content of the <a> element becomes clickable in the web page.

The href attribute tel s the browser the destination of the link.

you are here �

49

how links work

Behind
the Scenes

Next, when a user clicks on a link, the browser uses the “href”

2
attribute to determine the page the link points to.

The user clicks on either the
elixirs link or...

...on detailed directions.

When “detailed directions” is

If elixirs was clicked, the
clicked, the browser grabs the
browser grabs the href value
value of the href attribute, in

“elixir.html”...

<a href=”elixir.html”>elixirs</a>
this case “directions.html”...

...and displays the

“elixir.html” page.

<a href=”directions.html”>detailed directions</a>

...and loads “directions.html”.

50

Chapter 2

going further with hypertext

Understanding attributes

Attributes give you a way to specify additional information about an element. While we haven’t looked at attributes in detail, you’ve already seen a few examples of them:

The type attribute specifies which style
language we’re using, in this case CSS.

<style type=”text/css”>

The href attribute tells us the destination of a hyperlink.

<a href=”irule.html”>

<img src=”sweetphoto.gif”>

The src attribute specifies the filename
of the picture an img tag displays.

Let’s cook up an example to give you an even better feel for how attributes work:

What if <car> was an element?

If <car> was an element, then you’d naturally want to write some markup like this:

With no attributes, all we can supply is

<car>My Red Mini</car>
a descriptive name for the car.

But this <car> element only gives a descriptive name for your But with attributes, we can
car – it doesn’t tell us the make, precise model, whether it is a customize the element with all
convertible, or a zillion other details we might want to know. So, if kinds of information.

<car> were really an element, we might use attributes like this:

<car make=”BMW” model=”Mini Cooper” convertible=”no”>My Red Mini</car> Better, right? Now this markup tells us a lot more information in an easy to write, convenient form.

Safety

First

Do this (correct form)

<a href=”top10.html”>Great Movies</a>

Attributes are always written the same
way: first comes the attribute name,
double quote
followed by an equals sign, and then the
equals sign
attribute value
attribute value surrounded in double quotes. attribute name double quote

You may see some sloppy HTML on the Web
that leaves off the double quotes, but don’t
get lazy yourself. Being sloppy can cause you

Not this (incorrect form)

a lot of problems down the road (as we’l see
later in the book).

<a href=top10.html>Great Movies</a>

WRONG - no double quotes around the attribute value.

you are here �

51

attributes and elements
there are no

Dumb Questions

Q: Can I just make up new attributes for an

HTML element?

A: No, because Web browsers only know about
a predefined set of at ributes for each element. If you
just made up at ributes, then Web browsers wouldn’t
know what to do with them, and as you’ll see later in
the book, doing this wil very likely get you into trouble.

When a browser recognizes an element or an attribute,
we like to say that it “supports” that element or at ribute.

You should only use attributes that you know are
supported.

Q: Who decides what is “supported?”

A: There are standards commitees that worry
about the elements and attributes of HTML. These

The “href” attribute is
committees are made up of people with nothing better
pronounced “h - ref”...

to do who generously give their time and energy to
make sure there’s a common HTML roadmap that all
companies can use to implement their browsers.

...rhymes with

“space chef”.

Q: How do I know what attributes and elements
are supported? Or, can al attributes be applied to
any element?

A: Only certain attributes can be used with a given
element. Think about it this way: you wouldn’t use an
attribute “convertible” with the element <toaster>, would you? So, you only want to use attributes that make sense
and are supported by the element.

We’re going to be learning which attributes are supported
by which elements as we make our way through the
book. After you’ve finished the book there are lots of
great references you can use to refresh your memory,
such as HTML & XHTML: The Definitive Guide (O’Reilly).

52

Chapter 2

going further with hypertext

Attributes Exposed

This week’s interview:

Confessions of the href attribute

HeadFirst: Welcome, href. It’s certainly a pleasure to interview as big an attribute as you.

href: Thanks. It’s good to be here and get away from all the linking; it can wear an attribute out. Every time someone clicks on a link, guess who gets to tell the browser where to go next? That would be me.

HeadFirst: We’re glad you could work us into your busy schedule. Why don’t you take us back to the beginning... What does it mean to be an attribute?

href: Sure. Well, attributes are used to customize an element. It’s easy to wrap some <a> tags around a piece of content, like “Sign up now!” – we do it like this: <a>Sign up now!</a> – but without me, the href attribute, you have no way to tell the <a> element the destination of the link.

HeadFirst: Got it so far...

href: ...but with an attribute you can provide additional information about the element. In my case, that’s where the link points to:

<a href=”signup.html”>Sign up now!</a> . This says that the

<a> element, which is labeled “Sign up now!”, links to the “signup.html” page.

Now, there are lots of other attributes in the world, but I’m the one you use with the <a> element to tell it where it points to.

HeadFirst: Nice. Now, I have to ask, and I hope you aren’t offended, but what is with the name? href ? What’s with that?

href: It’s an old Internet family name. It means “hypertext reference”, but all my friends just call me “href ” for short.

HeadFirst: Which is?

href: A hypertext reference is just another name for a resource that is on the Internet or your computer. Usually the resource is a Web page, but I can also point to audio, video... all kinds of things.

HeadFirst: Interesting. All our readers have seen so far are links to their own pages; how do we link to other pages and resources on the Web?

href: Hey, I gotta get back to work, the whole Web is getting gunked up without me. Besides, isn’t it your job to teach them this stuff ?

HeadFirst: Okay okay, yes, we’re getting to that in a bit... thanks for joining us, href.

you are here �

53

linking back to the main page

You’ve created links to go from “lounge.html” to “elixir.html” and

“directions.html”; now we’re going to go back the other way. Below you’ll Exercise
find the HTML for “elixir.html”. Add a link with the label “Back to the Lounge” at the bottom of the elixir page that points back to “lounge.html”.

<html>

<head>

<title>Head First Lounge Elixirs</title>

</head>

<body>

<h1>Our Elixirs</h1>

<h2>Green Tea Cooler</h2>

<p>

<img src=”green.jpg”>

Chock full of vitamins and minerals, this elixir combines the healthful benefits of green tea with a twist of chamomile blossoms and ginger root.

</p>

<h2>Raspberry Ice Concentration</h2>

<p>

<img src=”lightblue.jpg”>

Combining raspberry juice with lemon grass, citrus peel and rosehips, this icy drink will make your mind feel clear and crisp.

</p>

<h2>Blueberry Bliss Elixir</h2>

<p>

<img src=”blue.jpg”>

Blueberries and cherry essence mixed into a base of elderflower herb tea will put you in a relaxed state of bliss in no time.

</p>

<h2>Cranberry Antioxidant Blast</h2>

<p>

<img src=”red.jpg”>

Wake up to the flavors of cranberry and hibiscus in this vitamin C rich elixir.

</p>

Your new HTML
goes here.

</body>

</html>

When you are done, go ahead and do the same with “directions.html” as well.

54

Chapter 2

going further with hypertext

We need some help constructing and deconstructing <a> elements. Given your new knowledge of the <a> element, we’re hoping you can help. In each row below you’ll find some combination of the label, destination, and the complete <a> element. Fill in any information that is missing. The first row is done for you.

Label

Destination

What you write in HTML

Hot or Not?

hot.html

<a href=”hot.html”>Hot or Not?</a>

Resume
cv.html
candy.html

<a href=” ”>Eye Candy</a>

See my mini
mini-cooper.html
let’s play

<a href=”millionaire.html”> </a>
there are no

Dumb Questions

Q: I’ve seen many pages where I can click on an image Q: So I can put anything between the <a> tags and it will be rather than text. Can I use the <a> element for that?

clickable? Like, say, a paragraph?

A: Yes, if you put an <img> element between the A:

<a> tags

Whoa now. Not so fast. Not every element can be placed
then your image will be clickable just like text. We’re not going to talk inside an <a> element. In general you’l just be using text and about images in depth for a few chapters, but they work just fine as images (or both) within the <a> element. What tags wil go inside links.

other tags is a whole other topic, but don’t worry; we’l get there soon enough.

you are here �

55

organizing your site with folders

Your work on the Head First

Lounge has really paid off. With
those enticing elixirs and directions, lots of
people are frequenting the place and visiting
the Web site. Now we’ve got plans for
expanding the lounge’s online content in all
sorts of directions.

Getting organized

Before you start creating more HTML pages, it’s time to get things organized. So far, we’ve been putting all our files and images in one folder. You’ll find that even for modestly-sized Web sites, things are much more manageable if you organize your Web pages, graphics, and other resources into a set of folders.

Here’s what we’ve got now:

Here are the

<html>

.

three HTML

.

.

files: for the

</html>

We’ve got a top-level folder
lounge, the
lounge.html
called “lounge” that holds all
our files in the site.

elixirs page,
and the

<html>

.

.

directions.

.

</html>
elixir.html
lounge

<html>

.

.

.

</html>
directions.html

This is often referred to as the “root” folder of
the site, which means it is the top-level folder
that contains the entire site.

green.jpg
blue.jpg

And here are all the images. See, this is
drinks.gif
getting sorta cluttered already, and we only
have three pages and a few graphics. Let’s
lightblue.jpg
red.jpg
do something about it....

56

Chapter 2

going further with hypertext

Organizing the lounge...

Let’s give the lounge site some meaningful organization now.

Keep in mind there are lots of ways to organize any site; we’re going to start simple and create a couple of folders for pages.

We’ll also group all those images into one place.

We’re going to leave the

Our root folder is still the
main “lounge.html” page in

“lounge” folder.

the “lounge” folder.

lounge

<html>

.

.

.

</html>
lounge.html
green.jpg

<html>

<html>

.

.

about
beverages
images

.

.

blue.jpg

.

.

</html>

</html>
drinks.gif
directions.html
elixir.html
lightblue.jpg
red.jpg

Let’s create a folder to
hold pages about the lounge,

We’ll also create a folder to hold

And, let’s group
like the directions. We
pages about the lounge’s beverages.

all images into
could also add new pages

Right now that’s just the elixirs, but one folder.

here about the management,
we’ll be adding more soon.

events, and so on.

there are no

Dumb Questions

Q: Since you have a folder for

Q: Or, why not put an images folder Q: “Each branch”?

images, why not have another one
in each other folder, like “about” and
called “html” and put all the HTML in

“beverages.”

that folder?

A: You can understand the way folders
are described by looking at

A:

A: Again, we could have. We expect them as upside down

You could. There aren’t any
that some of the images wil be reused
trees. At the top is the

“correct” ways to organize your files; rather, among several pages, so we put images in root and each path
you want to organize them in a way that
a folder at the root (the top level) to keep
down to a file or folder
works best for you and your users. As with
them al together. If you have a site that
is a branch.

most design decisions, you want to choose
needs lots of images in dif erent parts of
an organization scheme that is flexible
the site, you might want each branch to
enough to grow, while keeping things as
have its own image folder.

simple as you can.

you are here �

57

reorganizing and broken links

Now you need to create the file and folder structure shown on the previous page. Here’s exactly what you need to do:

Exercise

�1 Locate your “lounge” folder and create three new subfolders named “about”, “beverages”, and “images”.

�2 Move the file “directions.html” into the “about” folder.

�3 Move the file “elixir.html” into the “beverages” folder.

�4 Move all the images into the “images” folder.

�5 Finally, load your “lounge.html” file and try out the links.

Compare with how ours worked below.

Technical difficulties

It looks like we’ve got a few problems
with the lounge page after moving
things around.

We’ve got an image that
isn’t displaying. We usually
call this a “broken image”.

And, when you click on elixirs (or detailed
directions) things get much worse: we get an
error saying the page can’t be found.

Some browsers display
this error as a web page
rather than a dialog box.

58

Chapter 2

going further with hypertext

I think the problem is that
the browser thinks the files
are stil in the same folder as

“lounge.html”. We need to change
the links so they point to the files
in their new folders.

Right. We need to tell the
browser the new location
of the pages.

So far you’ve used href values that
point to pages in the same folder. Sites
are usually a little more complicated,
though, and you need to be able to
point to pages that are in other folders.

To do that, you trace the path from
your page to the destination file. That
might mean going down a folder or two,
or up a folder or two, but either way we
end up with a relative path that we can
put in the href.

you are here �

59

working with paths

Planning your paths...

What do you do when you’re planning that vacation

Okay, you’d
in the family truckster? You get out a map and
really go to
start at your current location, and then trace a path

Google maps,
to the destination. The directions themselves are
but work
relative to your location – if you were in another city, with us here!

they’d be different directions, right?

To figure out a relative path for your links, it’s the
same deal: you start from the page which has the

There are other kinds of
link, and then you trace a path through your folders
paths too. We’ll get to
until you find the file you need to point to.

those in later chapters.

Let’s work through a couple of relative paths (and
fix the lounge at the same time):

Linking down into a subfolder

1

Linking from “lounge.html” to “elixir.html”.

We need to fix the elixirs link in the “lounge.html” page. Here’s what the

<a> element looks like now:

Right now we’re just using the
filename “elixir.html”, which tells

<a href=”elixir.html”> elixirs</a>
the browser to look in the same
folder as “lounge.html”.

2

Identify the source and the destination.

When we re-organized the lounge, we left “lounge.html” in the “lounge” folder, and we put “elixir.html” in the “beverages” folder, which is a subfolder of “lounge”.

Start here...

lounge

<html>

.

.

.

</html>
lounge.html
green.jpg

<html>

<html>

.

.

about
beverages
images

.

.

blue.jpg

.

.

</html>

</html>
drinks.gif
directions.html
elixir.html
lightblue.jpg
red.jpg

...and find a
path to here.

60

Chapter 2

going further with hypertext

3

Trace a path from the source to the destination.

Let’s trace the path. To get from the “lounge.html” file to “elixir.html”, we need to go into the “beverages” folder first, and then we’ll find “elixir.html” in that folder.

First we need to
go down into the

“beverages” folder.

lounge

<html>

.

.

.

</html>
lounge.html
green.jpg

<html>

<html>

.

.

about
beverages
images

.

.

blue.jpg

.

.

</html>

</html>
drinks.gif
directions.html
elixir.html
lightblue.jpg
red.jpg

And “elixir.html” is
directly in that folder.

4

Create an href to represent the path we traced.

Now that we know the path, we need to get it into a format the browser understands. Here’s how you write the path:

Separate all parts of

Finally we hav

First we go into the
e the
the path with a “/”.

file name.

beverages folder.

beverages / elixir.html

Putting it all together...

<a href=”beverages/elixir.html”> elixirs</a> We put the relative path into the href value. Now when the link is clicked on, the browser will look for the “elixir.html” file in the “beverages” folder.

you are here �

61

a little practice with paths

Sharpen your pencil

Your turn: trace the relative path from “lounge.html” to “directions.html”. When you’ve discovered it, complete the <a> element below. Check your answer in the back of the chapter, and then go ahead and change both <a> elements in “lounge.html.”

lounge

<html>

.

.

.

</html>
lounge.html
green.jpg

<html>

<html>

.

.

about
beverages
images

.

.

blue.jpg

.

.

</html>

</html>
drinks.gif
directions.html
elixir.html
lightblue.jpg
red.jpg

<a href=” ”>detailed directions</a> YOUR ANSWER HERE

62

Chapter 2

going further with hypertext

Going the other way; linking up into a “parent” folder

1

Linking from “directions.html” to “lounge.html”.

Right now we’re just

Now we need to fix those “Back to the Lounge” links. Here’s what the <a> using the filename
element looks like in the “directions.html” file:

“lounge.html”, which tells
the browser to look in
the same folder as

<a href=”lounge.html”> Back to the Lounge</a> “directions.html”. That’s not going to work.

2

Identify the source and the destination.

Let’s take a look at the

...and find a
source and destination.

path to here.

The source is now
the “directions.html”

lounge

<html>

.

.

.

</html>
file, which is down in
lounge.html
the “about” folder. The
destination is the
green.jpg

“lounge.html” file that sits

<html>

<html>

.

.

above the “about” folder,
about
beverages
images

.

.

blue.jpg

.

.

</html>

</html>
where “directions.html”

drinks.gif
directions.html
elixir.html
is located.

lightblue.jpg
red.jpg

Start here...

3

Trace a path from the source to the destination.

Let’s trace the path.

...and “lounge.html” is

To get from the
directly in that folder.

“directions.html” file to

“lounge.html”, we need to
lounge

<html>

.

.

go up one folder into the

.

</html>

“lounge” folder, and then
lounge.html
we’ll find “lounge.html”

in that folder.

green.jpg

<html>

<html>

.

.

about
beverages
images

.

.

blue.jpg

.

.

</html>

</html>
drinks.gif
directions.html
elixir.html
lightblue.jpg

First we need to
red.jpg
go UP into the

“lounge” folder...

you are here �

63

building the href

4

Create an href to represent the path we traced.

We’re almost there. Now that you know the path, you need to get it into a format the browser understands. Let’s work through this: First you need to go up

Separate all parts of

Finally you have the
one folder. How do you
the path with a “/”.

file name.

do that? With a “..”.

That’s right, two periods.

Go with it, we’ll explain
in a sec.

.. / lounge.html

Pronounce “..” as “dot dot”.

Putting it all together...

<a href=”../lounge.html”> Back to the Lounge</a> Now when you click on the link, the
browser will look for the “lounge.html”

Dot dot
file in the folder above.

Up, down,
housewares,
lingerie?

64

Chapter 2
going further with hypertext
there are no

Dumb Questions

Q: What’s a parent folder? If I have a Q: What do you do if you need to go Q: What about in the other direction folder “apples” inside a folder “fruit”, is
up two folders instead of just one?

– is there a limit to how many folders I

“fruit” the parent of “apples”?

can go down?

A:

A: You can use “..” for each parent

Exactly. Folders (you might have
folder you want to go up. Each time you use A: Wel , you can only go down as many heard these cal ed directories) are often

“. ” you’re going up by one parent folder. So, folders as you have created. If you create described in terms of family relationships.

if you want to go up two folders, you’d type
folders that are 10 deep, then you can write

For instance, using your example, “fruit” is

“. /. ”. You stil have to separate each part
a path that takes you down 10 folders.

the parent of “apples”, and “apples” is the
with the “/”, so don’t forget to do that (the

But we don’t recommend that – when you
child of “fruit”. If you had another folder
browser won’t know what “....” means!).

have that many folder levels, it probably

“pears” that was a child of “fruit”, it would be
means your website organization is too
a sibling of “apples.” Just think of a family

Q:

complicated!

tree.

Once I’m up two folders, how do I
tell the browser where to find the file?

In addition, there is a limit to the number

Q:

of characters you can have in a path: 255

Okay, parent makes sense, but
characters. That’s a lot of characters, so
what is “..”?

A: You combine the “../..” with the
it’s unlikely you’l ever need that many, but
filename. So, if you’re linking to a file cal ed
if you have a large site, it’s something to be

A:

“fruit.html” in a folder that’s two folders up,
aware of.

When you need to tel the browser
you’d write “. /. /fruit.html”. You might expect
that the file you’re linking to is in the parent
that we’d call “../..” the “grandparent” folder,

Q: My operating system uses “\” as
folder, you use “..” to mean “move UP to the
but we don’t usual y talk about them that
a separator; shouldn’t I be using that
parent folder.” In other words, it’s browser-
way, and instead say, “the parent of the
instead of “/”?

speak for parent.

parent folder,” or “../..” for short.

In our example, we wanted to link from

“directions.html”, which is in the “about”

Q:

A:

Is there a limit to how far up I can

No; in Web pages you always use
folder, to “lounge.html”, which is in the
go?

“/”. Don’t use “\”. Various operating systems

“lounge” folder, the parent of “about”. So we
use dif erent file separators (for instance,
had to tel the browser to look UP one folder.

Windows uses “\” instead of “/”) but when

“..” is the way we tell the browser to go UP.

A: You can go up until you’re at the root it comes to the Web, we pick a common of your Web site. In our example, the root
separator and al stick to it. So, whether
was the “lounge” folder. So, you could only
you’re using Mac, Windows, Linux, or
go up as far as “lounge”.

something else, always use “/” in the paths
in your HTML.

brain
power

A

Your turn: trace the relative path from “elixir.html” to “lounge.html” from the “Back to the Lounge” link. How does it differ from the same link in the “directions.html” file?

Answer: It doesn’t, it is exactly the same.

you are here �

65

relative paths and images

Fixing those broken images...

Hey, it’s nice you fixed al those

You’ve almost got the lounge back in working order; all you links, but didn’t you forget
need to do now is fix those images that aren’t displaying.

something? Al our images are broken!

Don’t leave us hanging, we’ve got a

We haven’t looked at the <img> element in detail yet (we will business to run.

in a couple of chapters), but all you need to know for now is that the <img> element’s src attribute takes a relative path, just like the href attribute.

Here’s the image element from the “lounge.html” file:

<img src=”drinks.gif”>

Here’s the relative path, which tells the
browser where the image is located. We
specify this just like we do with the href
attribute in the <a> element.

Finding the path from “lounge.html” to “drinks.gif”

To find the path, we need to go from the “lounge.html” file to where the images are located, in the “images” folder.

Start here... (1) Go down int

GOAL: we’re in the lounge
o
the images f
folder and we need to get
older.

lounge

<html>

.

.

.

</html>
down into the images folder.

lounge.html
green.jpg

<html>

<html>

.

.

about
beverages
images

.

.

blue.jpg

.

.

</html>

</html>
drinks.gif
directions.html
elixir.html
lightblue.jpg
red.jpg

(2) There’s our
file, “drinks.gif”. ...and find a
path to here.

So putting (1) and (2) together our path looks like “images/drinks.gif ”, or:

<img src=”images/drinks.gif”>

66

Chapter 2

going further with hypertext

Finding the path from “elixir.html” to “red.jpg”

The elixirs page contains images of several drinks: “red.jpg”,

“green.jpg”, “blue.jpg”, and so on. Let’s figure out the path to

“red.jpg” and then the rest will have a similar path because they are all in the same folder:

GOAL: we’re in the
beverages folder and we

(2) And then down int
need to get over to the
o
the “images” f
images folder.

older.

lounge

<html>

.

.

.

</html>
lounge.html
green.jpg

...and find a

<html>

<html>

.

.

about
beverages
images

.

.

blue.jpg
path to here.

.

.

</html>

</html>
drinks.gif
directions.html
elixir.html
lightblue.jpg
red.jpg

(1) So we go up to the parent

Start here...

folder, “lounge”. Remember
this will be written as “..” in
the path.

(3) Finally, we find “red.jpg” .

So putting (1) , (2), and (3) together we get:

Down into

And the file

Up to the

“/” in between.

“/” in bet
the “images”

ween.

name itself.

parent folder.

folder.

.. / images / red.jpg

<img src=”../images/red.jpg”>
you are here �

67

fixing images with relative links

That covers al the links we broke when we reorganized the lounge, although you stil need to fix the images in your “lounge.html” and “elixir.html” files. Here’s Exercise
exactly what you need to do:

�1 In “lounge.html”, update the image src attribute to have the value “images/drinks.gif”.

�2 In “elixir.html”, update the image src attribute so that “../images/” comes before each image name.

�3 Save both files and load “lounge.html” in your
browser. You’ll now be able to navigate between
all the pages and view the images.

P.S. If you’re having any trouble, the folder

“chapter2/completelounge” contains a working version
of the lounge. Double-check your work against it.

You did it! Now we’ve

And then we
got organization and al our links
can take the site to
are working. Time to celebrate.

Join us and have a green tea
the next level!

cooler.

68

Chapter 2

going further with hypertext

BULLET POINTS

� When you want to link from one page to

� Use “..” to link to a file that’s one folder
another, use the <a> element.

above the file you’re linking from.

� The href attribute of the <a> element

� “..” means “parent folder.”

specifies the destination of the link.

� Remember to separate the parts of your

� The content of the <a> element is the
path with the “/” character.

label for the link. The label is what you

�
see on the Web page. By default, it’s

When your path to an image is incorrect,
underlined to indicate you can click on it.

you’ll see a broken image on your Web
page.

� You can use words or an image as the

�
label for a link.

Don’t use spaces in names when you’re
choosing names for files and folders for

� When you click on a link, the browser
your Web site.

loads the Web page that’s specified in the �
href attribute.

It’s a good idea to organize your Web site
files early on in the process of building

� You can link to files in the same folder, or
your site, so you don’t have to change a
files in other folders.

bunch of paths later when the Web site

� A relative path is a link that points to other
grows.

files on your Web site relative to the Web � There are many ways to organize a Web page you’re linking from. Just like on
site; how you do it is up to you.

a map, the destination is relative to the
starting point.

you are here �

69

The Relativity Grand Challenge

Here’s your chance to put your relativity skills to the test. We’ve got a Web site for the top 100 albums in a folder named “music”. In this folder you’ll find HTML
files, other folders and images. Your challenge is to find the relative paths we need so we can link from our Web pages to other Web pages and files.

On this page, you’ll see the Web site structure; on the next page you’ll find the tasks to test your skills. For each source file and destination file, it’s your job to make the correct relative path. If you succeed, you will truly be champion of relative paths.

Good luck!

Feel free to draw right
on this Web site picture
to figure out the paths.

<html>

.

.

.

</html>
music
top100.html

<html>

.

.

.

</html>
genres
images
logo.gif
genres.html

<html>

.

.

.

</html>
darkside.gif
floyd.gif
pinkfloyd.html
rock
cdcovers
artists

<html>

.

.

.

</html>
xandy.gif
chris.gif
coldplay.html

70

Chapter 2

going further with hypertext

It’s time for the competition to begin.

Ready... set... write!

“top100.html” is in the

Example

“music” folder, so to get

<html>
genres/genres.html

<html>
to “genres.html”, we had

.

.

.

.

.

.

to go down into the

<html>

<html>

“genres” folder.

top100.html
genres.html

Round One

<html>

.

.

.

<html>
top100.html
logo.gif

Round Two

<html>

.

.

.

<html>
genres.html
logo.gif

Round Three

<html>

<html>

.

.

.

.

.

.

<html>

<html>
top100.html
pinkfloyd.html

Bonus Round

<html>

.

.

.

<html>
coldplay.html
chris.gif
you are here �

71

some fun for your left brain

HTMLcross

How does a crossword help you learn HTML? Well, all the words are HTML-related and from this chapter. In addition, the clues provide the mental twist and turns that will help you burn alternative routes to HTML right into your brain!

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

Across

Down

1. ../myfiles/index.html is this kind of link.

2. href and src are two of these.

3. Another name for a folder.

4. Hardest working attribute on the web.

6. Flavor of blue drink.

5. Rhymes with href.

9. what href stands for.

7. Top folder of your site.

13. Everything between the <a> and </a> is this.

8. The "HT" in HTML.

16. Can go in an <a> element, just like text.

10. Healthy drink.

17. Pronounced "..".

11. A folder at the same level.

12. Use .. to reach this kind of directory.

14. Text between the <a> tags acts as a ______.

15. A subfolder is also called this.

72

Chapter 2

going further with hypertext

Exercise

Solutions

<html>

<head>

<title>Head First Lounge Elixirs</title>

</head>

<body>

<h1>Our Elixirs</h1>

<h2>Green Tea Cooler</h2>

<p>

<img src=”green.jpg”>

Chock full of vitamins and minerals, this elixir combines the healthful benefits of green tea with a twist of chamomile blossoms and ginger root.

</p>

<h2>Raspberry Ice Concentration</h2>

<p>

<img src=”lightblue.jpg”>

Combining raspberry juice with lemon grass, citrus peel and rosehips, this icy drink will make your mind feel clear and crisp.

</p>

<h2>Blueberry Bliss Elixir</h2>

<p>

<img src=”blue.jpg”>

Blueberries and cherry essence mixed into a base of elderflower herb tea will put you in a relaxed state of bliss in no time.

</p>

<h2>Cranberry Antioxidant Blast</h2>

<p>

<img src=”red.jpg”>

Wake up to the flavors of cranberry and hibiscus in this vitamin C rich elixir.

</p>

Here’s the new <a> element pointing back

<p>

<a href=”lounge.html”>Back to the Lounge</a> to the lounge.

</p>

We put the link inside its own paragraph

</body>
to keep things tidy. We’ll talk more about

</html>
this in the next chapter.

you are here �

73

exercise solutions

Exercise solutions

Label

Destination

Element

Hot or Not?

hot.html

<a href=”hot.html”>Hot or Not?</a>

Resume
cv.html

<a href=”cv.html”>Resume</a>
candy.html
candy.html

Eye Candy

<a href=” ”>Eye Candy</a>

<a href=”mini-cooper.html”>See my mini</a>

See my mini
mini-cooper.html
let’s play
let’s play
mil ionaire.html

<a href=”millionaire.html”> </a>

1

2

R

E

L A T

I

V

E

T

3D I R E C T O R Y

R

4

5

H

I

S

6

7

8

R A S

P

B

E

R

R

Y

P

H

E

U

O

A

Y

F

T

O

C

P

9

10

H Y

P

E

R

T E X T R

E

F

E

R

E N C

E

S

C

L

R

11

12

S

P

H

I

T

13

14

15

I

C

L

I

C

K A B

L

E

X

E

B

A

H

R

F

I

X

L

B

I

E

R

T

16

I M A G E

L

N

17

N

L

D O T D O T

G

74

Across

Down

Chapter 2

1. ../myfiles/index.html is this kind of link.

2. href and src are two of these. [attributes]

[relative]

4. Hardest working attribute on the web. [href]

3. Another name for a folder. [directory]

5. Rhymes with href. [spacechef]

6. Flavor of blue drink. [raspberry]

7. Top folder of your site. [root]

9. what href stands for. [hypertextreference]

8. The "H" in HTML. [hypertext]

13. Everything between the <a> and </a> is this.

10. Healthy drink. [elixir]

[clickable]

11. A folder at the same level. [sibling]

16. Can go in an <a> element, just like text. [image]

12. Use .. to reach this kind of directory. [parent]

17. Pronounced "..". [dotdot]

14. Text between the <a> tags acts as a ______.

[label]

15. A subfolder is also called this. [child]

going further with hypertext

Sharpen your pencil

Trace the relative path from “lounge.html” to “directions.html”. When you’ve discovered it, Solution
complete the <a> element below.

Here’s the solution. Did you change both <a> elements in “lounge.html”?

“about”

lounge

<html>

.

.

.

</html>
lounge.html
green.jpg

<html>

<html>

.

.

about
beverages
images

.

.

blue.jpg

.

.

</html>

</html>
drinks.gif
directions.html
elixir.html
lightblue.jpg
red.jpg

“directions.html”

about/directions.html

<a href=” ”>detailed directions</a> YOUR ANSWER HERE
you are here �

75

exercise solutions

The Relativity Grand Challenge Solution
top100.html is in the

Round One
music folder, so to
get to logo.gif, we had

<html>
images/logo.gif
to go down into the

.

.

images folder.

.

<html>
top100.html
logo.gif

Round Two
genres.html is down in
the genres directory, so
to get to logo.gif, we

<html>

../images/logo.gif
first had to go up to

.

.

music, and then down into

.

<html>
the images folder.

genres.html
logo.gif

From top100.html, we go

Round Three
down into genres, then
down into rock, and find
pinkfloyd.html.

<html>
genres/rock/pinkfloyd.html <html>

.

.

.

.

.

.

<html>

<html>
pinkfloyd.html
top100.html

This was a tricky one. From

Bonus Round
coldplay.html, which is down in
the rock folder, we had to go
up TWO folders to get to music,

<html>

../../images/artists/chris.gif

.

.

and then go down into images,

.

<html>
and finally artists to find the
coldplay.html
chris.gif
image chris.gif. Whew!

76

Chapter 2

3 building blocks

Web Page Construction

We better find some hard
hats, Betty. It’s a real
construction zone around here,
and these Web pages are
going up fast!

I was told I’d actually be creating Web pages in this book?

You’ve certainly learned a lot already: tags, elements, links, paths... but it’s all for nothing if you don’t create some killer Web pages with that knowledge. In this chapter we’re going to ramp up construction: you’re going to take a Web page from conception to blueprint, pour the foundation, build it, and even put on some finishing touches. All you need is your hard hat and your tool belt, as we’ll be adding some new tools and giving you some insider knowledge that would make Tim “The Toolman” Taylor proud.

this is a new chapter

77

meet tony and his segway

Tony

What better way to enjoy
my new Segway than to hit the open
road? I’m riding it across the entire USA
and I’ve been documenting my travels in
my journal. What I real y need to do is
get this in a Web page so my friends
and family can see it.

Tony’s Journal

Tony’s Segway

July 14, 2005
e style signs on the side of

I saw some Burma Shav

Segway’n USA
y
the road today: “Passing cars, When you can’t see,
ty.” I definitely
y trip around the US on m

Documenting m

May get you, A glimpse, Of eterni
y cars!

very own Segway!

won’t be passing an

August 20 2005

June 2, 2005
lready, and I passed
ip! I can’t believe I

Well I made it 1200 miles a
esting places on the way:

ul,

My first day of the tr
eady to go.

through some inter
finally got everything packed and r
ay, I wasn’t able to bring

Walla Walla, WA, Magic City, ID, Bountif

Because I’m on a Segw

UT, Last Chance, CO, Why, AZ and Truth or
a whole lot with me: cell phone, iPod, digital
t the essentials.

Consequences, NM.

camera, and a protein bar. Jus

As Lao Tzu would have said, “A journey of a
th one step Segway.”

thousand miles begins wi

Make sure you read through Tony’s adventures - they’ll come in handy throughout the chapter.

78

Chapter 3

building blocks

From Journal to Web site, at 12mph T
recommended
he Segway’s top speed.

Tony’s got his hands full driving across the United States on his Segway.

Why don’t you give him a hand and create a Web page for him.

Here’s what you’re going to do:

1

First, you’re going to create a rough sketch of the journal that is the basis for your page design.

2

Next, you’ll use the basic building blocks of HTML (<h1> , <h2> , <h3> , <p> , and so on) to translate your sketch into an outline (or blueprint) for the HTML page.

3

Once you have the outline, then you’re going to translate it into real HTML.

4

Finally, with the basic page done, you’ll add some enhancements and meet some new HTML elements along the way.

STOP! Do this exercise before turning the page.

Sharpen your pencil

Take a close look at Tony’s journal and
think about how you’d present the same

Your sketch
information in a Web page.

goes here.

Draw a picture of that page on the right.

No need to get too fancy, you’re just
creating a rough sketch. Assume all his
journal entries will be on one page.

Things to think about:

� Think of the page in terms of large
structural elements: headings,
paragraphs, images, and so on.

� Are there ways his journal might be
changed to be more appropriate for
the Web?

you are here �

79

making a rough sketch

The rough design sketch

Tony’s journal looks a lot like a Web page; all we need to do to create the design sketch is to get all his entries on one page and map out the general organization. It looks like, for each day Tony gave his journal a title,
that Tony creates an entry, he has a date heading, an optional

“Segway’n USA”, so let’s get that
picture, and a description of what happened that day. Let’s right at the top as a heading.

look at the sketch...

He also gave his journal a description.

We’ll capture that here as a small
paragraph at the top.

Segway’n USA

Documenting my trip around the US on my
very own Segway!

Each day, Tony creates an entry that includes

August 20, 2005
the date, usually a picture, and a description
of the day’s adventures. So, that’s a heading,
an image, and another paragraph of text.

Well I made it 1200 miles already, and I passed
through some interesting places on the way: Walla Walla,

WA, Magic City, ID, Bountiful, UT, Last Chance, CO,

Sometimes he doesn’t include a picture. In this

Why, AZ and Truth or Consequences, NM.

entry he just has a heading (the date) and a
description of the day’s events.

July 14, 2005

I saw some Burma Shave style signs on the side of
the road today: “Passing cars, When you can’t see,

The third entry should look just

May get you, A glimpse, Of eternity”. I definitely
like the first one: a heading, an
won’t be passing any cars!

image, and a paragraph.

June 2, 2005

Unlike Tony’s paper journal, our page length isn’t
limited, so we can fit many entries on one Web page.

His friends and family can just use the scroll bar to
scroll through his entries...

My first day of the trip! I can’t believe finally
got everything packed and ready to go. Because

However, notice that we reversed the order of

I’m on a Segway, I wasn’t able to bring a whole
the journal entries from newest to oldest. That
lot with me: cellphone, iPod, digital camera, and
way the most recent entries appear at the top
a protein bar. Just the essentials. As Lao Tzu
where users can see them without scrolling.

would have said, “A journey of a thousand miles
begins with one Segway.”

80

Chapter 3

building blocks

From a sketch to an outline

Now that you’ve got a sketch of the page, you can take
each section and draw something that looks more like
an outline or blueprint for the HTML page...

Here we’ve taken each area of the
sketch and created a corresponding
block in our blueprint.

h1

All you need to do now is figure out which HTML
element maps to each content area, and then you can
start writing the HTML.

EXERCISE: Web Construction

You’ve already figured out the major
architectural areas of the page; now you just
need to nail down the building materials. Use
the elements below to label each area. You
won’t use them all, so don’t worry if you have
some building materials left over. And don’t
forget to wear your hard hat.

h1h1
h1
h2
p
h2
p
h2
p
h3
img
h3
img
h3
img
h4h4
a
h4
a
a
h5h5
h5
h6h6
h6
you are here �

81

turning the outline into a web page

From the outline to a Web page

You’re almost there. You’ve created an outline of

Tony’s Web page. Now all you need to do is create
the corresponding HTML to represent the page
and fill in Tony’s text.

Before you begin, remember that every Web page
needs to start with the <html> element and include h1
the <head> and <body> elements.

p
h2
img

Now that you know
what “building blocks” make up
p
each part of the page, you can
translate this blueprint directly
into HTML.

h2
p
h2
img
p

82

Chapter 3
building blocks

Don’t forget, you always need the <html>,

<head>, <title> and <body> elements.

We’re using the title of the journal as the
title of the Web page.

<html>

<head>

<title> My Trip Around the USA on a Segway</title>

</head>

<body>

Here’s the heading and

<h1> Segway’n USA</h1>
description of Tony’s journal.

<p>

Documenting my trip around the US on my very own Segway!

</p>
heading
image

<h2> August 20, 2005</h2>

<img src=”images/segway2.jpg”>
description

Here’s Tony’s most

<p>
recent entry.

Well I made it 1200 miles already, and I passed through some interesting places on the way: Walla Walla,

WA, Magic City, ID, Bountiful, UT, Last Chance, CO,

Why, AZ and Truth or Consequences, NM.

</p>

<h2> July 14, 2005</h2>

<p>

Here’s his second

I saw some Burma Shave style signs on the side of the entry, which doesn’t
road today: “Passing cars, When you can’t see, May get
have an image.

you, A glimpse, Of eternity.” I definitely won’t be passing any cars.

</p>

And at the bottom,

<h2> June 2, 2005</h2>

Tony’s first entry,

<img src=”images/segway1.jpg”>
with the image

<p>

“segway1.jpg”.

My first day of the trip! I can’t believe I finally got everything packed and ready to go. Because I’m on a Segway, I wasn’t able to bring a whole lot with me: cellphone, iPod, digital camera, and a protein bar. Just the essentials. As Lao Tzu would have said, “A journey of a thousand miles begins with one Segway.”

</p>

Last, but not least, don’t forget to close
your <body> and <html> elements.

</body>

</html>

Go ahead and type this in. Save your file to the “chapter3/journal” folder as “journal.html”. You’ll find the images “segway1.jpg”

and “segway2.jpg” already in the “images” folder. When you’re done, give this page a test drive.

you are here �

83

test driving tony’s page

Test driving Tony’s Web page

July 14, 2005
e style signs on the side of

I saw some Burma Shav

Segway’n USA
y
the road today: “Passing cars, When you can’t see,
ty.” I definitely
y trip around the US on m

Documenting m

May get you, A glimpse, Of eterni
y cars!

very own Segway!

won’t be passing an

August 20 2005

June 2, 2005
lready, and I passed
ip! I can’t believe I

Well I made it 1200 miles a
esting places on the way:

ul,

My first day of the tr
eady to go.

through some inter
finally got everything packed and r
ay, I wasn’t able to bring

Walla Walla, WA, Magic City, ID, Bountif

Because I’m on a Segw

UT, Last Chance, CO, Why, AZ and Truth or
a whole lot with me: cellphone, iPod, digital
t the essentials.

Consequences, NM.

camera, and a protein bar. Jus

As Lao Tzu would have said, “A journey of a
th one step Segway.”

thousand miles begins wi

Look how well this page has come
together. You’ve put everything in

Tony’s journal into a readable and
well-structured Web page.

Fantastic! This looks
great; I can’t wait to
add more entries to my page.

Tony’s calling in
from the road...

84

Chapter 3

building blocks

Adding some new elements

You have the basic elements of HTML down. You’ve gone from a handwritten journal to an online version in just a few steps using the basic HTML elements <p> , <h1> , <h2>, and <img> .

Now we’re going to s-t-r-e-t-c-h your brain a little and add a few more common elements. Let’s take another look at Tony’s journal and see where we can spruce things up a bit...

Check this out: Tony has a little quote stuck
at the end of his first post. It’s his remixed
version of a Lao Tzu quote: “A journey of a
thousand miles begins with one Segway.”

HTML has an element, <q>, for just that kind of thing.

Let’s take a look on the next page...

you are here �

85

quotes in your html

Meet the <q> element

Got a short quote in your HTML? The <q> element is just what you need. Here’s a little test HTML to show you how it works:

<html>

<head>

<title> Quote Test Drive</title>

We’ve got two quotes in this HTML...

</head>

<body>

<p>

You never know when you’ll need a good quote, how
about <q> To be or not to be</q> , or <q> Wherever you go, there you are</q> .

</p>

</body>

</html>

We surround each quote with a <q> opening tag and
a </q> closing tag. Notice that we don’t put our own
double quote characters around the quotes.

...and check out the test drive...

And here’s how the quotes look in the
browser. Notice the browser has gone to
the trouble of adding the double quotes.

Some browsers, including

Internet Explorer version 6, do

Watch it!

ound
not display double quotes ar
the content in the <q> element.

This is unfortunate, because if you add your own
double quotes, some browsers wil display TWO sets
of quotes. The only way to solve this conundrum is
to use CSS to add some visual style to your quotes,
such as italics. We’l show you how to add italics to
your elements in Chapter 9.

86

Chapter 3

building blocks

Wait a sec... you removed
the double quotes and substituted a

<q> element, which just displays double
quotes? Am I supposed to be impressed?

Are you trying to make things more
complicated?

No. We’re trying to make things
more structured and meaningful.

There are lots of reasons people use double quotes in
text, but when we use <q> that means something specific

– it means the text of an actual quote (in Tony’s case, a See! Using double quotes

“remixed” quote).

doesn’t make something
an actual quote.

In other words what we’ve done is to add some
additional meaning by marking up the quote. Before we
added the <q> element, the browser just knew it had a paragraph of text with a few double quote characters
in it. Now, because we’re using the <q> element, the browser knows that some of that text is a real quote.

So what? Well, now that the browser knows this is a
quote it can display it in the best way possible. Some
browsers will display double quotes around the text,
some won’t, and in instances where browsers are using
non-English languages, other methods might be used.

And don’t forget mobile devices, like cell phones, or
audio HTML browsers for the visually impaired. It’s
also useful in other situations, such as a search engine
that scours the Web looking for Web pages with quotes.

Structure and meaning in your pages are Good Things.

One of the best reasons (as you’ll see when we get back
to presentation and CSS later in the book) is that you’ll
be able to style quotes to look just the way you want.

Suppose you want quoted text to be displayed in italics
and colored gray? If you’ve used the <q> element to structure the quoted content in your Web pages, you’ll be
able to do just that.

you are here �

87

adding a quote

Here’s Tony’s journal. Go ahead and rework his Lao Tzu quote to use the <q> element. After you’ve done it on paper, make the changes in your “journal.html”

file and give it a test drive. You’ll find the solution in the back of the chapter.

Exercise

<html>

<head>

<title> Segway’n USA</title>

</head>

<body>

<h1> Segway’n USA</h1>

<p>

Documenting my trip around the US on my very own Segway!

</p>

<h2> August 20, 2005</h2>

<img src=”images/segway2.jpg”>

<p>

Well I made it 1200 miles already, and I passed through some interesting places on the way: Walla Walla,

WA, Magic City, ID, Bountiful, UT, Last Chance, CO,

Why, AZ and Truth or Consequences, NM.

</p>

<h2> July 14, 2005</h2>

<p>

I saw some Burma Shave style signs on the side of the road today: “Passing cars, When you can’t see, May get
you, A glimpse, Of eternity.” I definitely won’t be passing any cars.

</p>

<h2> June 2, 2005</h2>

<img src=”images/segway1.jpg”>

<p>

My first day of the trip! I can’t believe I finally got everything packed and ready to go. Because I’m on a Segway, I wasn’t able to bring a whole lot with me: cellphone, iPod, digital camera, and a protein bar. Just the essentials. As Lao Tzu would have said, “A journey of a thousand miles begins with one Segway.”

</p>

</body>

</html>

88

Chapter 3

building blocks

The Case of the Elements Separated at Birth

Identical twins were born in Webville a number of years ago and by a freak accident involving an Internet router malfunction, the twins were separated shortly after birth. Both grew up without knowledge of the other, and only through another set of freak circumstances did they later meet and discover their identity, which they decided to keep secret.

After the discovery, they quickly learned that they shared a surprising number of things in common. Both were married to wives named Five-Minute

Citation. They also both had a love for quotations. The first twin, the <q> element, loved short, pithy quotes, while the second, Mystery

<blockquote> , loved longer quotes, often memorizing complete passages from books or poems.

Being identical twins, they bore a strong resemblance to each other, and so they decided to put together an evil scheme whereby they might stand in for each other now and then. They first tested this on their wives (the details of which we won’t go into) and they passed with flying colors

– their wives had no idea (or at least pretended not to).

Next they wanted to test their switching scheme in the work place where, as another coincidence, they both performed the same job: marking up quotes in HTML documents. So, on the chosen day, the brothers went to the other’s work place ful y confident they’d pul off their evil plan (after all, if their wives couldn’t tell, how could their bosses?), and that’s when things turned bad. Within 10 minutes of starting the work day, the brothers had both been found to be imposters and the standards authorities were immediately alerted.

How were the twins caught in the act?

Keep reading for more clues...

you are here �

89

creating longer quotes

Looooong Quotes

Now that you know how to do short quotes, let’s
tackle long ones. Tony’s given us a long quote
with the Burma Shave jingle.

In his journal Tony just put the Burma Shave
quote right inside his paragraph, but wouldn’t it
be better if we pulled this quote out into a “block”

of its own, like this:

I saw some Burma Shave style signs on the side of
the road today:

Passing cars,

When you can’t see,

If you don’t know what

May get you,

“Burma Shave” slogans are,

A glimpse,
we’ll tell you all about

Of eternity.

them in just a few pages...

I definitely won’t be passing any cars.

That’s where the <blockquote> element comes
in. Unlike the <q> element, which is meant for short quotes that are part of an existing paragraph,
the <blockquote> element is meant for longer
quotes that need to be displayed on their own.

It’s important
to use the right tool
for the job, and the

<blockquote> element is
perfect for this job.

90

Chapter 3

building blocks

Adding a <blockquote>

Let’s get a <blockquote> into Tony’s online journal.

1

Open your “journal.html” file and locate the July 14th
entry. Rework the paragraph to look like this:

To insert the <blockquote>

<h2> July 14, 2005</h2>
element, we need to end this

<p>
paragraph first.

I saw some Burma Shave style signs on the
side of the road today:

</p>

Next we put the Burma Shave text in the

<blockquote>

<blockquote> element.

Passing cars,

We also put each line of text on a separate

When you can’t see,
line so it reads more like a Burma Shave slogan.

May get you,

A glimpse,

Of eternity.

And finally, w

</blockquote>
e need to add a <p> tag to
start this paragraph after the <blockquote>.

<p>

I definitely won’t be passing any cars.

</p>

2

Time for another test drive. Open “journal.html” in your browser and take a look at the results of your work:

<blockquote> creates a
separate block (like <p>
does), plus it indents
the text a bit to
make it look more like
a quote. Just what we
wanted...

But our quote isn’t looking
quite like we wanted because
all the lines are running
together. We really wanted
them on different lines. o

Hmmm. Let’s come back t
that in a bit...

you are here �

91
all about quotes and blockquotes
there are no

Dumb Questions

Q:

make sense, does it?

Q:

So let me see if I have this

Q: I get that the <blockquote>

You said that we can style these
right: I use <q> when I just want to
breaks its text out into a little block of
elements with CSS, so if I want to
have some quote in with the rest of
its own and indents it, so why isn’t the
make the text in my <q> element italics
my paragraph, and I use <blockquote>

<blockquote> inside the paragraph, just and gray, I can do that with CSS. But when I have a quote that I want to break like the <q> element is?

couldn’t I just use the <em> element to
out on its own in my Web page?

italicize my quotes?

A:

A: Because the <blockquote>

You’ve got it. In general you’ll
really is like a new paragraph. Think

A: Wel, you could, but it wouldn’t
use <blockquote> if you want to quote
about this as if you were typing it into a
be the right way to do it, because you’d
something that was a paragraph or more,
word processor. When you finish one
be using the <em> element for its ef ect
while you can use <q> anytime you just
paragraph you hit the return key twice
on the display rather than because
want to throw in a quote as part of your
and start a new paragraph. To type a
you’re real y writing emphasized text. If
running text.

block quote you’d do the same thing and
the person you were quoting really did
emphasize a word, or you want to add

Q:

indent the quote. Put this in the back of
your mind for a moment; it’s an important
emphasis to make a strong point about

Multiple paragraphs in a block
point and we’re going to come back to it
the quote, then go right ahead and use
quote? How do I do that?

in a sec.

the <em> element inside your quote. But
don’t do it simply for the italics. There

A:

Also, remember that the indenting is
are easier and bet er ways to get the look

Easy. Just put paragraph
just the way some browsers display
you want for your elements with CSS.

elements inside your <blockquote>, one
a <blockquote>. Not al browsers use
for each paragraph. Do try this at home.

indentation for <blockquote>, and those
that do might not in new versions. So,

Q:

don’t rely on a <blockquote> to look the

How do I know what my quotes
same in all browsers.

or block quotes wil look like in other
browsers? It sounds like they may

Q: Can I combine quote elements?

handle it differently.

For instance, could I use the <q>

A:

element inside the <blockquote>

Yes. Welcome to the World Wide
element?

Web. You don’t real y know what your
quotes will look like without trying them

A:

out in different browsers. Some browsers

Sure. Just like you can put a
use double quotes, some use italics and

<q> element inside the <p> element, you
some use nothing at all. The only way to
can put <q> inside <blockquote>. You
real y determine how they’l look is to style might do this if you’re quoting someone them yourself, and we’l certainly be doing
who quoted someone else. But, a
that later.

<blockquote> inside a <q> doesn’t real y

92

Chapter 3

building blocks

Solved: The Case of the Elements Separated at Birth

How were the identical quote twins found to be imposters so quickly?

As you’ve no doubt guessed by now, <q> and <blockquote> were discovered as soon as they went to work and began
to mark up text. <q> ’s normally unobtrusive little Five-Minute
quotes were popping out into blocks of their own,
while <blockquote> ’s quotes were suddenly being Mystery
lost inside regular paragraphs of text. In follow-up
interviews with the victims of the pranks, one editor

Solved
complained, “I lost an entire page of liner quotes thanks
to these wackos.” After being reprimanded and sent back to their respective jobs, <blockquote> and <q> fessed up to their wives, who immediately left town together in a T-Bird convertible. But that’s a whole

’nother story (it didn’t end well).

you are here �

93

block and inline elements

The real truth behind the <q> and <blockquote> mystery Okay, it’s time to stop the charade: <blockquote> and <q> are actually different types of elements. The <blockquote> element is a block element and the <q> element is an inline element. What’s the difference? Block elements are always displayed as if they have a linebreak before and after them, while inline elements appear “in line” within the flow of the text in your page.

Block: stands on its own

Inline: goes with the flow

<h1>, <h2>, ..., <h6>, <p>, and <blockquote> are all block elements.

<q>, <a>, and <em> are inline elements.

Each block element is
displayed on its own, as if
h2
it has a linebreak before
and after it.

<q> on the other
p
p
hand, like all inline
elements, is just
q
displayed in the flow
of the paragraph
it’s in.

Block elements
blockquote
separate content
into blocks.

Remember: block elements stand on their own;
inline elements go with the f low.

94

Chapter 3

building blocks
there are no

Dumb Questions

Q: I think I know what a linebreak is; it’s like hitting the carriage return on a typewriter or the return key on a computer keyboard. Right?

A: Pretty much. A linebreak is literally a “break in the line,” like this, and happens when you hit the Return key, or on some computers, the Enter key. You already know that linebreaks in HTML files don’t show up visual y when the browser displays a page, right? But now you’ve also seen that any time you use a block element, the browser uses linebreaks to separate each “block”.

Once again, this
all sounds great,
but why is all this talk of
linebreaks, blocks, and inline
elements useful? Can we get
back to Web pages?

Don’t underestimate the power of knowing how HTML
works. You’re soon going to see that the way you
combine elements in a page has a lot to do with whether
elements are block or inline. We’ll get to all that.

In the meantime, you can also think about block versus
inline this way: block elements are used as the major
building blocks of your Web page, while inline elements
mark up small pieces of content. When you’re designing
a page, you typically start with the bigger chunks (the
block elements) and then add in the inline elements as
you refine the page.

The real payoff is going to come when we get to
controlling the presentation of HTML with CSS. If you
know the difference between inline and block, you’re
going to be sipping martinis while everyone else is still
trying to get their layout right.

you are here �

95

inline versus block

Tonight’s talk: Inline and Block air their differences.

Inline

Block

Hey there, Block. I’m kind of surprised to see
you here.

Why’s that?

Because you’re kind of a loner. You’ve always
got those linebreaks hanging around keeping
everyone away from you, like they’re your body
guards or something.

I’m just a busy guy. Block elements are really
the major building blocks of all these Web sites.

If you didn’t have me, these pages would just
crumble.

Don’t get too big on yourself over there. Yeah,
you’re great, but where would you be without
inline content? Paragraphs and headings and all
that are kind of pointless without text and inline
content like links.

I agree <a> is an important element, and
we’ve actually been trying to recruit him over
to our side. But the most important part
of a page is that it be designed well at the
foundation, and that takes block elements. You
can’t just take a bunch of links and make a real
page, now can you?

I’ll tell you right now <a> isn’t going anywhere.

He’s born and bred inline. And if your pages
don’t have <a> , <em> , <q> , and al the other inline elements, you’re not going to have very
interesting pages, even if you have a good
foundation.

96

Chapter 3
building blocks

Inline

Block

We may not get <a> , but I’ve been telling

<img> he should come over to our side for
years. He’d make a great block element.

Wel , a lot of people do think at first that the

<img> element is block, but he’s not, and he
makes much more sense as an inline element.

People like images mixed in with al their text
and links.

We’ll see about that. I’ll tell you another thing,
this <blockquote> versus <q> thing is silly.

We’ve got a perfectly good block quote; why do
we need <q> ?

Because people like to use smal quotes
inline with their text. I’ve got no issue with

<blockquote> , so why are you picking on

<q> ? You know, for thinking inline elements
aren’t very important, you sure are recruiting a
lot of them.

Where are those linebreak body guards when

I need them? Look how behind I am now. I
gotta get back to building some pages.

Oh, how convenient. Let me know how al that
page building goes without any inline elements.

I’m sure those are going to be some useful pages.

Not!

you are here �

97

carriage returns and the br element

I’ve been thinking about the

Burma Shave lines. I wasn’t
surprised that they weren’t
broken up because we’ve said from
the beginning that whitespace and
linebreaks aren’t displayed by
the browser...

. . but the only way I can
think of to fix this is to put
each one in a block element
like a paragraph. Otherwise, how
can you get the browser to add
linebreaks?

What if you had an element
whose only job was to give you a
linebreak when you needed one?

Wouldn’t that be nice? You’d actually be able to make
the browser pay attention and insert some carriage
returns for a change.

Turns out there is an element, the <br> element, just for that purpose. Here’s how you use it:

<h2> July 14, 2005</h2>

<p>

I saw some Burma Shave style signs on the
side of the road today:

</p>

<blockquote>

Add a <br> element to any line

Here’s the July

Passing cars, <br>
when you want to break the

14th snippet from

When you can’t see, <br>
flow and insert a “linebreak.”

Tony’s page.

May get you, <br>

A glimpse, <br>

Of eternity. <br>

</blockquote>

<p>

I definitely won’t be passing any cars.

</p>

98

Chapter 3

building blocks

Go ahead and add the <br> elements to Tony’s journal. After you make the changes, save the file, and give it a test drive.

Exercise

Here’s what the changes should
look like. Now it reads like a

Burma Shave slogan should read!

Each line now has a
linebreak after it.

you are here �

99

empty elements have no closing tag

In Chapter 1 we said that
an element is an opening tag +
content + closing tag. So how is

<br> an element? It doesn’t have
any content, and it doesn’t even
have a closing tag.

Exactly, it doesn’t have any content.

The <br> element is an element that doesn’t have any content. Why? Because it’s just meant to be a linebreak, nothing else. So, when an element doesn’t have any real content by design, we just use a shorthand to represent the element and it ends up looking like

<br> . After all, if we didn’t have this shorthand, you’d be writing <br></br> every time you needed a linebreak, and how much sense does that make?

<br> isn’t the only element like this; there are others, and we have a name for them: empty elements. In fact, we’ve already seen another empty element, the <img> element.

We’ll be coming back to look at the <img> element in detail in a couple chapters.

Keep in mind, the reason for the shorthand isn’t laziness so much as it is efficiency. It’s more efficient to represent empty elements this way (efficient in typing, in the number of characters that end up in a page, and so on). In fact, after reading HTML for a while, you’ll find that it is easier on your eyes too.

Content? Hmm, the whole point of
this element is to insert a linebreak.

There’s really no content.

Here’s the closing tag.

Here’s the opening tag.

<br> </br>

Okay, typing this in is REALLY silly.

We know ther

<br> </br>
e’s never going to be any
content between those tags.

I’m half the
element I used to

Yeah, if we just type this
be... (sniff sniff).

<br>
then it really represents
the same thing.

100

Chapter 3
building blocks
there are no

Dumb Questions

Q: So, the only purpose of <br> is to A: Yes, there are a few of them. You’ve insert a linebreak?

already seen us use the <img> element, and we’ll
be get ing to the details of this element soon.

A: Right; the only place the browser typicaly Q:

inserts breaks in your content is when you start a

Can I make any element empty? For
new block element (like <p>, <h1>, and so on). If instance if I have a link, and don’t want to give
you want to insert a linebreak into your text, then
it any content, can I just write
you use the <br> element.

<a href=“mypage.html”> instead?

Q:

A:

Why is <br> cal ed an “empty”

No. There are two types of elements in
element?

the world: normal elements, like <p>, <h1>, and

<a>, and then there are empty elements, like

A:

<br> and <img>. You don’t switch back and forth Because it has no content, as in
between the two. For instance, if you just typed
element = opening tag + content + closing tag. <a href=”mypage.html”>, that’s not an empty So, it’s empty because there’s no content.

element – it’s an opening tag without content and
a closing tag.

Q: I stil don’t get it. Explain why the

<br> element is “empty”?

A: Think about an element like <h1> (or <p>

Elements that don’t have any HTML
or <a>). The whole point of the element is to tag
some content, like:

content by design are called empty

<h1>Don’t wait, order now</h1>

With the <br> element, the point is just to insert
elements. When you need to use an
a linebreak into your HTML. There is no content
you are trying to mark up, so it’s empty. Since
empty element, like <br> or <img>,
it is empty, we don’t need al the extra brackets
and markup, so we just shorten it into a more
you only use an opening tag. This is a
convenient form.

convenient shorthand that reduces the

If an element doesn’t need to mark up some text,
then it is probably an empty element.

amount of markup in your HTML.

Q: Are there any other empty elements?

I think <img> must be an empty element, too,
right?

you are here �

101

we need a list for tony’s site

Meanwhile, back at Tony’s site...

You’ve come a long way already in this chapter: you’ve
designed and created Tony’s site, you’ve met a few new
elements, and you’ve learned a few things about elements
that most people creating pages on the Web don’t even
know (like block and inline elements, which are really
going to come in handy in later chapters).

But you’re not done yet. We can take Tony’s site from
good to great by looking for a few more opportunities to
add some markup.

Like what? How about lists? Check this out:

There’s a list right here. Tony wrote
the list of cities that he’s been
through in his August journal entry.

Wouldn’t it be great if we could mark up this text so the
browser knows this text is a list? Then the browser could
display the list items in a more useful way. Something like this: Well I’ve made it 1200 miles already, and I passed
through some interesting places on the way:

1. Walla Walla, WA

2. Magic City, ID

3. Bountiful, UT

Note that not only is this a

4. Last Chance, CO
list, but it’s an ordered list.

Tony visited these cities in a

5. Why, AZ
particular order.

6. Truth or Consequences, NM

102

Chapter 3

building blocks

Of course, you could use the <p>
element to make a list...

It wouldn’t be hard to make a list using the <p> element.

It would end up looking something like this:

<p>

1. Red Segway

Top two preferred

</p>
colors for Segway.

<p>

2. Blue Segway

</p>

But there are lots of reasons not to.

You should be sensing a common theme by now. You
always want to choose the HTML element that is closest
in meaning to the structure of your content. If this is a list, let’s use a list element. Doing so gives the browser and you (as you’ll see later in the book) the most power and

Remember, it’s
flexibility to display the content in a useful manner.

important to use the
right tool for the job,
and the <p> element is

NOT the right tool
brain
for this job.

power

?

Why not use <p> to make lists?

(Choose all that apply.)

❏ A. HTML has an element for lists. If you
use that, then the browser knows the
text is a list, and can display it in the
best way possible.

❏ B. The paragraph element is really meant
for paragraphs of text, not lists.

❏ C. It probably wouldn’t look much like
a list, just a bunch of numbered
paragraphs.

❏ D. If you wanted to change the order of
the list, or insert a new item, you’d
have to re-number them all. That
would suck.

, C, & D

: A, B
wer

Ans
you are here �

103
constructing a list

Constructing HTML lists in t wo easy steps

Creating an HTML list requires two elements that, when used together, form the list. The first element is used to mark up each list item. The second determines what kind of list you’re creating: ordered or unordered.

Let’s step through creating Tony’s list of cities in HTML.

Step One:

Put each list item in an <li> element.

To create a list, you put each list item in its own <li> element, which means enclosing the content in an opening <li> tag and a closing </li> tag. As with any other HTML element, the content between the tags can be as short or as long as you like and broken over multiple lines.

Locate this HTML in your “journal.html” file and keep

We’re just showing a fragment of the HTML
up with the changes as we make them.

from Tony’s journal here.

<h2>August 20, 2005</h2>

<img src=”images/segway2.jpg” />

<p>

Well I’ve made it 1200 miles already, and I passed
through some interesting places on the way:

First move the list items outside of the paragraph. The list is going to stand on its own.

</p>

...and then enclose each list i

<li> Walla Walla, WA</li>
tem
with an <li>, </li> set of tags.

<li> Magic City, ID</li>

<li> Bountiful, UT</li>

<li> Last Chance, CO</li>

Each of these <li>

<li> Why, AZ</li>
elements will become an

<li> Truth or Consequences, NM</li>
item in the list.

<h2> July 14, 2005</h2>

<p>

I saw some Burma Shave style signs on the side of
the road today:

</p>

104

Chapter 3

building blocks

Step Two:

Enclose your list items with either the <ol> or <ul> element.

If you use an <ol> element to enclose your list items, then the items will be displayed as an ordered list; if you use <ul> , the list will be displayed as an unordered list. Here’s how you enclose your items in an <ol> element.

Again, we’re just showing a fragment of the

HTML from Tony’s journal here.

<h2> August 20, 2005</h2>

<img src=”images/segway2.jpg” />

<p>

Well I’ve made it 1200 miles already, and I passed
through some interesting places on the way:

</p>

We want this to be an ordered list, because Tony visited the cities in a specific order. So we use an <ol> opening tag.

<ol>

<li> Walla Walla, WA</li>

<li> Magic City, ID</li>

All the list items sit in the

<li> Bountiful, UT</li>
middle of the <ol> element and

<li> Last Chance, CO</li>
become its content.

<li> Why, AZ</li>

<li> Truth or Consequences, NM</li>

</ol>

And here we close the <ol> element.

<h2> July 14, 2005</h2>

<p>

I saw some Burma Shave style signs on the side of
the road today:

</p>

HTML
is for
structure

Make it Stick

Wash

Us
t
e
he
ul o
c
r o
a
l
t
brain
for lists
power

A
unordered list = ul

Is <ol> a block element or inline? What about <li> ?

ordered list = ol
list item = li
you are here �

105

testing out the list

Taking a test drive through the cities

Make sure you’ve added all the HTML for the list, reload your

“journal.html” file and you should see something like this: Here’s the new and
improved list of cities.

There’s a linebreak before the list starts,
so <ol> must be a block element.

But there’s also a linebreak after each item,
so <li> must be a block element too!

Notice that the browser takes care of
automatically numbering each list item

(so you don’t have to).

Sharpen your pencil

It turns out Tony actually
visited Arizona after New

Mexico. Can you rework
the list so the numbering
is correct?

106

Chapter 3

building blocks

Here’s another list from Tony’s journal: cel phone, iPod, digital camera, and a protein bar. You’ll find it in his June 2nd entry. This is an unordered list of items.

Exercise

The HTML for this entry is typed below. Go ahead and add the HTML to change the items into an HTML unordered list (remember, you use <ul> for unordered lists). We’ve already reformatted some of the text for you.

When you’ve finished, check your answers in the back of the chapter. Then make these changes in your “journal.html” file and test.

<h2> June 2, 2005</h2>

<img src=”segway1.jpg”>

<p>

My first day of the trip! I can’t believe I finally got everything packed and ready to go. Because I’m on a Segway, I wasn’t able to bring a whole lot with me:

cell phone
iPod
digital camera
and a protein bar

Just the essentials. As

Lao Tzu would have said, <q> A journey of a
thousand miles begins with one Segway. </q>

</p>
you are here �

107
more about lists
there are no

Dumb Questions

Q: Do I always have to use <ol> and <li> together?

Q: I think I basicaly understand block elements and inline elements, but I’m total y confused about what elements can A:

go inside other elements, or, as you say, what can be “nested”

Yes, you should always use <ol> and <li> together (or <ul> inside of what.

and <li>). Neither one of these elements real y makes sense without the other. Remember, a list is really a group of items: the <li> A:

element is used to identify each item, and the <ol> element is used That’s one of the hardest things to get straight with HTML.

to group them together.

This is something you’re going to be learning for a few chapters, and we’l show you a few ways to make sure you can keep the Q:

relationships straight. But, we’re going to back up and talk about Can I put text or other elements inside an <ol> or <ul> nesting a lit le more first. In fact, since you brought it up, we’l do element?

that next.

A:

Q:

No, the <ol> and <ul> elements are designed to work only So HTML has ordered and unordered lists. Are there any
with the <li> element.

other list types?

Q: What about unordered lists? Can I make the bulet look A: Actually there is another type: definition lists. A definition list different?

looks like this:

Each item in the list
has a term, <dt>, and a

A:

description, <dd>.

Yes. But hold that thought. We’ll come back to that when
we’re talking about CSS and presentation.

<dl>

<dt> Burma Shave Signs</dt>

Q:

<dd> Road signs common in the U.S. in the 1920s and 1930s advertising shaving products. </dd>

What if I wanted to put a list inside a list? Can I do that?

<dt> Route 66</dt>

<dd> Most famous road in the U.S. highway
system. </dd>

A:

</dl>

Yes, you sure can. Make the content of any <li> either <ol> Type this in and
or <ul> and you’ll have a list within a list (what we call a nested list).

give it a try.

<ol>

Nested list

Q: Burma Shave?

<li> Charge Segway</li>

Here’s the

<li> Pack for trip

<ul>

<li>. It

A: Burma Shave was a company that made brushless shaving

<li> cell phone</li>
encloses
cream in the early part of the 20th century. They began advertising

<li> iPod</li>
the nested
their product using roadside signs in 1925, and these signs proved to

<li> digital camera</li>
list.

be very popular (if somewhat distracting for drivers).

<li> a protein bar</li>

The signs were grouped in bunches of four, five or six, each with one

</ul>
line from the slogan. At one point, there were 7,000 of these signs

</li>

<li>Call mom</li>
on roadsides throughout the United States. Most are gone now, but there are stil a few left, here and there.

</ol>

108

Chapter 3

building blocks

<html>

<body> <p>

<q>

Putting one element inside
another is called “nesting”

When we put one element inside another element, we
call that nesting. We say, “the <p> element is nested inside the <body> element.” At this point, you’ve already seen lots of elements nested inside other
elements. You’ve put a <body> element inside an

<html> element, a <p> element inside a <body> element, a <q> element inside a <p> element, and so on. You’ve also put a <head> element inside the

<html> element, and a <title> element inside the

<head> . That’s the way HTML pages get constructed.

The more you learn about HTML, the more
important having this nesting in your brain becomes.

But no worries – before long you’ll naturally think
about elements this way.

<q> nested inside <p>,
nested inside <body>,
nested inside <html>.

you are here �

109

understanding nesting by drawing

To understand the nesting
relationships, draw a picture

<html>

<head>

Drawing the nesting of elements in a Web

<title> Musings</title>

</head>
page is kind of like drawing a family tree. At

<body>
the top you’ve got the great-grandparents,

<p>
and then all their children and grandchildren

To quote Buckaroo,
below. Here’s an example...

<q> The only reason
for time is so

Simple Web page.

that everything
doesn’t happen
at once. </q>

</p>

</body>

</html>

Let’s translate this into
a diagram, where each
element becomes a box, and

<html> is always the
each line connec
element a
ts the element
t the root of
to another element tha
the tree.

t is nested
within it.

<html> has two nested
elements: <head> and <body>.

You can call them both

“children” of <html>.

<body> is nested within the <html>
html
element, so we say <body> is the “child”

of <html>.

head
body

<title> is nested within the
title
p

<head> element.

The parent of <q> is <p>,
q
the parent of <p> is <body>, the
parent of <body> is <html>.

110

Chapter 3

building blocks

Using nesting to make sure your tags match

Your first payoff for understanding how elements are nested is that you can avoid mismatching your tags. (And there’s gonna be more payoff later, just wait.)

What does “mismatching your tags” mean and how could that
happen? Take a look at this example:

SAFETY FIRST

Properly

<p> I’m so going to blog <em> this</em></p> nest
p
your

Here’s how this HTML looks,

<em> is nested inside <p>.

elements
em

So far, so good, but it’s also easy to get sloppy and write some HTML
that looks more like this:

WRONG: the <p> tag
ends before the <em>

<p> I’m so going to blog <em> this</p></em> tag! The <em> element is supposed to be inside
the <p> element.

Given what you now know about nesting, you know the <em> element needs to be nested fully within, or contained in, the <p> element.

p
p
em
em

GOOD: here the <em> element is

BAD: here the <em> element has leaked outside of the <p> nested inside the <p>.

element, which means it’s not properly nested inside it.

So what?

It’s okay to mess up your nesting if you like playing Russian roulette. If you write HTML
without properly nesting your elements, your pages may work on some browsers but not on others. By keeping nesting in mind, you can avoid mismatching your tags and be sure that your HTML will work in all browsers. This is going to become even more important as we get more into “industrial strength HTML” in later chapters.

you are here �

111

catching mismatched tags

BE the Browser

Below, you’ll find an HTML file
with some mismatched tags in it.

Your job is to play like you’re the
browser and locate all the errors.

After you’ve done the
exercise look at the
end of the chapter to

<html>

<head>
see if you caught all

<title> Top 100</title>
the errors.

<body>

<h1> Top 100

<h2> Dark Side of the Moon</h2>

<h3> Pink Floyd</h3>

<p>

There’s no dark side of the moon; matter of fact <q> it’s all dark.

</p></q>

<ul>

<li> Speak to Me / Breathe</li>

<li> On The Run</li>

<li> Time</li>

<li> The Great Gig in The Sky</li>

<li> Money</li>

<li> Us And Them</em>

<li> Any Colour You Like</li>

<li> Brain Damage</li>

<li> Eclipse</li>

</ul>

</p>

<h2> XandY</h3>

<h3> Coldplay</h2>

<ol>

<li> Square One

<li> What If?

<li> White Shadows

<li> Fix You

<li> Talk

<li> XandY

<li> Speed of Sound

<li> A Message

<li> Low

<li> Hardest Part

<li> Swallowed In The Sea

<li> Twisted Logic

</ul>

</body>

</head>

112

Chapter 3

building blocks

Who am I?

A bunch of HTML elements, in full costume, are playing a party game, “Who am I?” They’ll give you a clue – you try to guess who they are based on what they say. Assume they always tel the truth about themselves. Fill in the blanks to the right to identify the at endees. Also, for each at endee, write down whether or not the element is inline or block.

Tonight’s attendees:

Any of the charming HTML elements you’ve seen so far just might show up!

Inline or

Name
block?

I’m the #1 heading.

I’m all ready to link to another page.

Emphasize text with me.

I’m a list, but I don’t have my affairs in order.

I’m a real linebreaker.

I’m an item that lives inside a list.

I keep my list items in order.

I’m all about image.

Quote inside a paragraph with me.

Use me to quote text that stands on its own.

you are here �

113

character entities are for special characters

I was just creating a Web
page explaining everything I was
learning from this book, and I wanted
to mention the <html> element inside
my page. Isn’t that going to mess up
the nesting? Do I need to put double
quotes around it or something?

You’re right, that can cause problems.

Because browsers use < and > to begin and end tags, using them in the content of your HTML can cause problems.

But, HTML gives you an easy way to specify these and other
special characters using a simple abbreviation called a character entity. Here’s how it works: for any character that is considered

“special” or that you’d like to use in your Web page, but that may not be a typeable character in your editor (like a copyright symbol), you just look up the abbreviation and then type it into your HTML. For example, the > character’s abbreviation is

&gt; and the < character’s is &lt; .

So, say you wanted to type “The <html> element rocks.” in your page. Using the character entities, you’d type this instead: The &lt;html&gt; element rocks.

Another important special character you should know about
is the & character. If you’d like to have an & in your HTML
content, use the character entity &amp; instead of the & character itself.

So what about the copyright symbol? And all those other
symbols and foreign characters? You can look common ones
up at this URL:

http://www.w3schools.com/tags/ref_entities.asp
or, for a more exhaustive list, use this URL:

http://www.unicode.org/charts/

114

Chapter 3

building blocks
there are no

Dumb Questions

Q:

Wow, I never knew the browser
something about your users, you should

Just remember to use & anytime you type
could display so many different
have a good idea of what kind of foreign
in an entity, and if you really need an & in
characters. There are a ton of different language characters are going to be your content, use &amp; instead.

characters and languages at the
common on their machine.

www.unicode.org site.

Q:

Q: When I looked up the entities

A:

You said that & is special and
at the www.w3cschools.com, I noticed

I need to use the entity &amp; in its
that each entity has a number too.

Be careful. Your browser will
place, but to type in any entity I have

What do I use that for?

only display all these characters if your
to use a &. So for, say, the > entity, do I
computer or device has the appropriate
need to type &amp;gt;?

fonts instal ed. So, while you can

A: You can use either the number,
probably count on the basic entities
like &#100 or the name of an entity in
from the www.w3schools.com page to

A: No, no! The reason & is special is your HTML (they do the same thing).

be available on any browser, there is no
precisely because it is the first character

However, not all entities have names, so
guarantee that you can display all these
of any entity. So, it’s perfectly fine to use
in those cases your only choice is to use
entities. But, assuming you know

& in your entity names, just not by itself.

the number.

Crack the Location Challenge

Dr. Evel, in his quest for world domination, has put up a private Web page to be used by his evil henchmen. You’ve just received a snippet of intercepted HTML
that may contain a clue to his whereabouts. Given your expert knowledge of HTML, you’ve been asked to crack the code and discover his location. Here’s a bit of the text from his home page:

There’s going to be an evil henchman meetup
next month at my underground lair in

&#208;&epsilon;&tau;&#114;&ouml;&igrave;&tau;.

Come join us.

Hint: visit http://www.w3schools.com/tags/ref_entities.asp and/or type in the HTML and see what your browser displays.

you are here �

115

tasting a few elements

Use this <em>
element to

<strong> Use this element to mark up

Element
mark up text
text you want emphasized with
you want
extra strength.

emphasized.

Soup

Use this element for

Whenever you want to make

<pre> formatted text when you want
a link, you’ll need the <a>
the browser to show your text
element.

<address>
exactly as you typed it.

This element tells the browser

<a>
that the content is an address,
like your contact info.

An empty element for
making linebreaks...

Use this element for short
quotes... you know, like “to be or
not to be”, or “No matter where

<ul>

<br> ... and another one for
you go, there you are.”

Need to display a list? Say, a list of
making horizontal lines
ingredients in a recipe or a todo lis

(called “horizontal
the <ul> element.

t? Use
rules”), like to start a

<q>
new section without a

<p>

<hr> heading.

Just give me a

If you need an ordered
paragraph, please.

list instead, use the <ol>

<ol>

Blockquote is for lengthy quotations.

element.

Something that you want to

The code element is used
highlight as a longer passage, say,
for displaying code from a
from a book.

computer program.

For items in lists,

<code>
like chocolate, hot
chocolate, chocolate
syrup ...

<li>

<blockquote>

Here’s a bunch of elements you
already know, and a
few you don’t.

Remember, half the fun of HTML
is experimenting! So make
some files of your own and try
these out.

116

Chapter 3

building blocks

Rockin’ page. It’s perfect
for my trip and it real y does a
good job of providing an online version
of my journal. You’ve got the HTML
wel -organized too, so I should be able
to add new material myself. So,
when can we actual y get this off
your computer and onto the

Web?

BULLET POINTS

n

Plan the structure of your Web pages before
n <br> is an “empty element.”

you start typing in the content. Start with a
sketch, then create an outline, and finally write n Empty elements have no content.

the HTML.

n

An empty element consists of only one tag.

n

Plan your page starting with the large, block
n

A nested element is an element contained
elements, and then refine with inline elements.

completely within another element. If your
elements are nested properly, all your tags will

n

Remember, whenever possible, use elements
to tell the browser what your content means.

match correctly.

n

You make an HTML list using two elements in

n

Always use the element that most closely
matches the meaning of your content. For
combination: use <ol> with <li> for an ordered
example, never use a paragraph when you
list; use <ul> with <li> for an unordered list.

need a list.

n

When the browser displays an ordered list, it
creates the numbers for the list so you don’t

n

<p>, <blockquote>, <ol>, <ul>, and <li> are all block elements. They stand on their own and
have to.

are displayed with space above and below the n You can specify your own ordering in an content within them.

ordered list with the start attribute. To change
the values of the individual items, use the

n

<q>, <em>, and <a> are all inline elements.

The content in these elements flows in line
value attribute.

with the rest of the content in the containing
n

You can build nested lists within lists by
element.

putting <ol> or <ul> elements inside your <li> elements.

n

Use the <br> element when you need to insert
your own linebreaks.

n

Use entities for special characters in your

HTML content.

you are here �

117

left brain resting station

HTMLcross

It’s time to give your right brain a break and put that left brain to work: all the words are HTML-related and from this chapter.

1

1

2

3

2

3

4

5

6

4

5

6

7

7

8

8

9

9

10

10

11

12

11

12

13

13

14

14

15

15

Across

Down

Across

Down

2. Block element for quotes.

1. Left together in a T-Bird.

2. Block element for quotes.

7. Major building blocks of your pages.

1. Left together in a T-Bird.

3. Use <ol> for these kinds of lists.

7. Major building blocks of your pages.

9. Requires two elements.

3. Use <ol> for these kinds of lists.

4. Empty elements have none.

9. Requires two elements.

10. Element without content.

4. Empty elements have none.

5. Putting one element inside another is called this.

10. Element without content.

11. <q> is this type of element.

5. Putting one element inside another is called this.

6. Use <ul> for these kinds of lists.

11. <q> is this type of element.

13. Famous catchy road signs.

6. Use <ul> for these kinds of lists.

8. Max speed of Segway.

13. Famous catchy road signs.

14. Tony's transportation.

8. Max speed of Segway.

12. Tony won't be doing any of this.

14. Tony's transportation.

15. Another empty tag.

12. Tony won't be doing any of this.

15. Another empty tag.

118

Chapter 3

building blocks

Here’s the rework of Tony’s Lao Tzu quote using the <q> element.

Did you give your solution a test drive?

Exercise

Solutions

Here’s the part that changes...

<p>

My first day of the trip! I can’t believe I finally got
everything packed and ready to go. Because I’m on a Segway, I wasn’t able to bring a whole lot with me:

We’ve added the <q> opening tag
cellphone, iPod, digital camera, and a protein bar. Just
before the start of the quote
the essentials. As Lao Tzu would have said, <q> A journey and the </q> closing tag at the
of a thousand miles begins with one Segway. </q>
very end.

</p>

Notice that we also
removed the double quotes.

And, here’s the test drive...

Okay, it doesn’t LOOK any
different, but don’t you FEEL
better now?

you are here �

119

exercise solutions

Here’s another list from Tony’s journal: cel phone, iPod, digital Exercise
camera, and a protein bar. You’ll find it in his July 14th entry.

This is an unordered list of items.

Solutions

Make these changes in your “journal.html” file, too. Does it look like you expected?

<h2> June 2, 2005</h2>

<img src=”segway1.jpg”>

<p>

My first day of the trip! I can’t believe I finally got everything packed and ready to go. Because I’m on a Segway, I wasn’t able to bring a whole lot with me:

</p>

First end the previous paragraph.

<ul>

Start the unordered list.

<li> cell phone</li>

<li> iPod </li>

Put each item into an <li> element.

<li> digital camera</li>

<li> and a protein bar</li>

End the unordered list.

</ul>

And, w

<p>
e need to start a new paragraph.

Just the essentials. As

Lao Tzu would have said, <q> A journey of a
thousand miles begins with one Segway. </q>

</p>

120

Chapter 3

building blocks

BE the Browser

Solution

<html>

<head>

Missing </head> closing tag.

<title> Top 100</title>

<body>

Missing </h1> closing tag.

<h1> Top 100

<h2> Dark Side of the Moon</h2>

<h3> Pink Floyd</h3>

<p>

There’s no dark side of the moon; matter of fact <q> it’s all dark.

</p></q>

<p> and <q> are not nested properly:

<ul>
the </p> tag should come after the

<li> Speak to Me / Breathe</li>

</q> tag.

<li> On The Run</li>

<li> Time</li>

<li> The Great Gig in The Sky</li> We have a closing </em> where we should

<li> Money</li>
have a closing </li> tag.

<li> Us And Them</em>

<li> Any Colour You Like</li>

<li> Brain Damage</li>

<li> Eclipse</li>

Here’s a closing </p> that doesn’t match

</ul>
any opening <p> tag.

</p>

<h2> XandY</h3>

We mixed up the closing </h2> and </h3> tags on these headings.

<h3> Coldplay</h2>

<ol>

We started an <ol> list, but it’s matched

<li> Square One
with a closing </ul> tag.

<li> What If?

<li> White Shadows

<li> Fix You

We’re missing all our

<li> Talk

<li> XandY
closing </li> tags.

<li> Speed of Sound

<li> A Message

<li> Low

<li> Hardest Part

<li> Swallowed In The Sea

<li> Twisted Logic

This doesn’t match the opening <ol> tag at the start of the list, above.

</ul>

</body>

Here’s our missing </head> tag; but we’re missing a closing </html> tag.

</head>
you are here �

121

exercise solutions

Who am I?

Exercise

Solutions

A bunch of HTML elements, in full costume, are playing a party game “Who am I?” They gave you a clue – you tried to guess
who they were based on what they said.

Tonight’s attendees:

Quite a few of the charming HTML elements you’ve seen so far showed up for the party!

Inline or

Name
block?

I’m the #1 heading.

h1
block

I’m all ready to link to another page.

a
inline
em
inline

Stumped?

Emphasize text with me.

<br> is in
limbo land
between block

I’m a list, but I don’t have my affairs in order.

ul
block
and inline. It
does create a
br
linebreak, but

I’m a real linebreaker.

isn’t typically
displayed with
space above
li
and below

I’m an item that lives inside a list.

block
it, like block
elements are.

ol
block

I keep my list items in order.

We haven’t
talked about
img
inline
this in detail

I’m all about image.

yet, but, yes,

<img> is inline.

q
inline

Give it some

Quote inside a paragraph with me.

thought and
we’ll come
blockquote
back to this in

Use me to quote text that stands on its own.

block

Chapter 5.

122

Chapter 3

building blocks

1W

I

V

Exercise

2

3

B

L O C

K Q U O T E

Solutions

R

S

4

5

6

C

N

D

U

7B L O C K E L E M E N T S

8

N

S

R

O

1

9 L I S T S

T

E

R

2

10

E

I

D

D

E M P

T Y

11

12

I N L

I N E

E

P

P

13

T

G

B U R M A S H A V E

E

S

14

D

S

E

G W A Y

I

N

15

I M G

Across

Down

2. Block element for quotes. [blockquote]

1. Left together in a T-Bird. [wives]

7. Major building blocks of your pages.

3. Use <ol> for these kinds of lists. [ordered]

[blockelements]

4. Empty elements have none. [content]

9. Requires two elements. [lists]

5. Putting one element inside another is called this.

Crack the Location Challenge

10. Element without content. [empty]

[nesting]

11. <q> is this type of element. [inline]

6. Use <ul> for these kinds of lists. [unordered]

13. Famous catchy road signs. [burmashave]

8. Max speed of Segway. [12mph]

14. Tony's transportation. [Segway]

12. Tony won't be doing any of this. [passing]

15. Another empty tag. [img]

You could have looked up each entity, or
typed them in. In either case, the answer
looks like Detroit!

There’s going to be an evil henchman meetup
next month at my underground lair in

&#208;&epsilon;&tau;&#114;&ouml;&igrave;&tau;.

Come join us.

you are here �

123

4 getting connected

A Trip to Webville

We’re going to

Webville! We’re leaving our
dusty ol’ local file system
behind for good.

Web pages are a dish best served on the Internet. So far you’ve only created HTML pages that live on your own computer. You’ve also only linked to pages that are on your own computer. We’re about to change all that. In this chapter we’ll encourage you to get those Web pages on the Internet where all your friends, fans, and customers can actually see them. We’ll also reveal the mysteries of linking to other pages by cracking the code of the h, t, t, p,

:, /, /, w, w, w. So, gather your belongings; our next stop is Webville.

WARNING: once you get to Webville, you may never come back. Send us a postcard.

this is a new chapter

125

getting on the web

Remember me from way
back in Chapter 1? You were
going to get the Starbuzz Web
site online so our customers
could actually see it.

Getting Starbuzz (or yourself)

onto the Web

You’re closer to getting Starbuzz – or even better, your own site

– on the Web than you might think. All you need to do is find a “Web Hosting Company” (we’ll call this a “hosting company”

from now on) to host your pages on their servers, and then copy your pages from your computer to one of those servers.

Of course it helps to understand how your local folders are going to “map” to the server’s folders, and once you put your pages on the server, how you point a browser to them. But we’ll get to all that. For now, let’s talk about getting you on the Web.

Here’s what you’re going to need to do:

1

Find yourself an hosting company.

2

Choose a name for your site (like

“www.starbuzzcoffee.com”).

3

Find a way to get your files from your
computer to a server at the hosting
company (there are a few ways).

4

Point your friends, family, and fans
to your new site and let the fun
begin.

We’re going to take you through each of these steps, and even if you’re not going to set up a Web site online right now, follow along because you’ll learn some important things you’ll need to know later. So, get ready for a quick detour from HTML... A Web Detour 126

Chapter 4

getting connected

A Web Detour

Finding a hosting company

One minute hosting guide

To get your pages on the Web, you need a server that

We can’t tell you everything you need to know
actually lives on the Web full-time. Your best bet is to find a hosting company and let them worry about the details
about getting a hosting company (after all,
of keeping a server running. No worries, though; finding a this book is about HTML and CSS), but we’re
hosting company is fairly straightforward and inexpensive.

going to give you a good push in the right
direction. Here are some features to think

Which company? Well, we’d love to sign you up for Web hosting at Head First Hip Web Hosting, Inc., but that doesn’t about while you’re shopping.

really exist. So, you’re going to have to do a little homework

� Technical support: Does the hosting
on your own. While finding a company to host your pages
company have a good system for handling
isn’t difficult, it’s kind of like choosing a cable TV company: your technical questions? The better ones
there are lots of options and plans. You really have to shop will answer your questions quickly either
around for the best deals and for the service that works for over the phone or via email.

you.

� Data transfer: This is a measure of the

The good news is that you should be able to get started for amount of pages and data the hosting
almost nothing out of your pocket, and you can always
upgrade later if you need additional features. While we
company will let you send to your visitors
can’t suggest a particular provider, we can tell you a few
during a given month. Most hosting
things to look for in a provider, and we also list a few of the companies offer reasonable amounts of
more popular providers at:

data transfer for small sites in their most
http://www.headfirstlabs.com/providers.html
basic plans. If you’re creating a site that

Note
you expect will have lots of visitors, you
from marketing:

if a hosting company
may want to carefully look into this.

writes a big enough

� Backups: Does the hosting company
check we can!

regularly make a backup of your pages
and data that can be recovered in the
event that the server has a hardware
failure?

You don’t have to

� Domain names: Does the hosting

Relax get your pages on
the Web to finish
company include a domain name in its
this book.

pricing? More about these on the next
page.

While it’s a lot more fun if your pages

� Reliability: Most hosting companies report
are actually on the Web, you can finish
the rest of this book by working on
keeping Web sites up 99% of the time or
your own computer.

better.

In either case, follow along for the next

� Goodies: Does your package include
few pages so you know how everything
other goodies such as email addresses,
fits together.

forums, or support for scripting languages

(something that may become important to
you in the future)?

you are here �

127

what’s the goal

A Web Detour
domain

HELLO, my name is...

Even if you’ve never heard of a domain name, you’ve seen and used a zillion of them; you know... google.com, yahoo.com, amazon.com, disney.com, and a maybe a few you wouldn’t want us to mention.

So what is a domain name? Just a unique name that is used to locate your site. Here’s an example:

This part is the domain name.

www.starbuzzcoffee.com

There are different domain “endings”

This part is the
for different purposes: .com, .org, .gov,
name of a specific

.edu; and also for different countr
server IN the
ies:

.co.uk, .co.jp, and so on. W
domain.

hen choosing a
domain, pick the one that best fits you.

After years of
struggling, we final y

There are a couple of reasons you should care about domain have our very own
names. If you want a unique name for your site, you’re going to domain name.

need your own domain name. Domain names are also used to link your pages to other Web sites (we’ll get to that in a few pages).

There is one other thing you should know. Domain names are controlled by a centralized authority (called ICANN) to make sure that only one person at a time uses a domain name. Also (you knew it was coming), you pay a small annual registration fee to keep your domain name.

How can you get a domain name?

The easy answer is to let your hosting company worry about it.

They’ll often throw in your domain name registration with one of their package deals. However, there are hundreds of companies that would be glad to help – you can find a list of them at http://www.internic.net/regist.html

As with finding a hosting company, we’re afraid we’ll have to leave you to find and register your own domain name. You’ll probably find that going through your hosting company is the easiest way to get that done.

128

Chapter 4

getting connected

A Web Detour
there are no

Dumb Questions

Q:

Why is it called a “domain name”

A: Again, don’t confuse a domain name should you ever want to choose another rather than a “Web site name”?

with a Web site name: starbuzzcof ee.com is hosting company, or should that hosting a domain name, while www.starbuzzcoffee.

company go out of business, then everyone

A:

com is the name of a Web site. Buying
who knows your site wil no longer be able

Because they are dif erent things.

a domain is like buying a piece of land,
to easily find it. If, on the other hand, you

If you look at www.starbuzzcof ee.com,
let’s say, 100mainstreet.com. On that land
have a domain name, you can just take that
that’s a Web site name, but only the
you can build as many Web sites as you
with you to your new hosting company (and

“starbuzzcof ee.com” part is the domain
like, for example: home.100mainstreet.

your users wil never even know you’ve
name. You could also create other Web
com, toolshed.100mainstreet.com and
switched).

sites that use the same domain name, like
outhouse.100mainstreet.com. So www.

corporate.starbuzzcoffee.com or employees.

starbuzzcof ee.com is just one Web site in

Q: If domain names are unique, that
starbuzzcof ee.com. So the domain name
the starbuzzcoffee.com domain.

means someone might already have
is something you can use for a lot of Web
mine. How can I find out?

sites.

Q: What’s so great about a domain

Q:

name anyway? Do I real y need one? My

A:

If I were going to get the domain
hosting company says I can just use their

Good question. Most companies
name for Starbuzz, wouldn’t I want to
name, “www.dirtcheaphosting.com”?

that provide registration services for domain
get the name www.starbuzzcoffee.com?

names al ow you to search to see if a name

Everyone seems to use Web sites with
is taken (kind of like searching for vanity
the www at the front.

A: If that meets your needs there is license plates). You’l find a list of these nothing wrong with using their name. But
companies at

(and it’s a big but) here’s the disadvantage:

http://www.internic.net/regist.html

Here’s an exercise you really need to go off and do on your own. We’d love to personally help but there’s only so much you can ask of book authors (and feeding the cat while you’re on vacation is probably out too).

DO try this at home

It’s time to seek out a hosting company and grab a domain name for your site. Remember, you can visit Head First Labs for some suggestions and resources. Also, remember that you can complete the book without doing this (even though you really should!).

My Web Hosting Company:

My Domain Name:

you are here �

129

what’s the goal

A Web Detour

Moving in

Congratulations! You’ve got your hosting company
lined up, you’ve found a domain name, and you’ve
got a server all ready for your Web pages. (Even
if you don’t, keep following along because this is
important stuff.)

Now what? Well, it’s time to move in, of course.

So, take that For Sale sign down and gather up all
those files, we’re going to get them moved to the
new server. Like any move, the goal is to get things
moved from, say, the kitchen of your old place to
the kitchen of your new place. On the Web, we’re
just worried about getting things from your own root
folder to the root folder on the Web server. Let’s get
back to Starbuzz and step through how we do this.

Here’s what things look like now:

Here’s the root folder
for Starbuzz.

Remember your

<html>

Starbuzz pages? There

.

.

are two: the main page

.

</html>

(index.html) and the
starbuzz
index.html
page that contains
the mission statement

<html>

.

(mission.html).

.

.

</html>
index.html

Here’s the new W
mission.html
starbuzz
eb server. The
mission.html
hosting company has already
created a root folder for you,
which is where all your pages
are going to go.

Your computer, where the

Starbuzz pages currently live.

starbuzz

Here’s the new Web site name.

We’re using the starbuzzcoffee.com
domain (since we beat you to it,
you’ll have to use your own domain
name instead).

www.starbuzzcoffee.com

130

Chapter 4

getting connected

A Web Detour

Q:

there are no

Wait a sec, what’s the “root

Dumb Questions A: Exactly. You’re going to take all
folder” again?

A:

the pages on your own computer, and put
them al inside your site’s root folder on the

A:

Not at al . Hosting companies call
hosting company server.

Up until now the root folder has
root folders lots of dif erent things. The
just been the top-level folder for your
important thing is that you know where

Q:

pages. On the Web server, the root folder
your root folder is located on the server,

What about subfolders, like the
becomes even more important because
and that you can copy your files to it (we’ll

“images” folder. Do I copy those too?

anything inside the root folder is going to
get to that in a sec).

be accessible on the Web.

Q:

A: Yes, you’re basicaly going to

Q:

So let me make sure I
replicate al the pages, files, and folders

My hosting company seems to
understand. We’ve been putting al our

in your own root folder onto the server. So
have cal ed my root folder
pages for the site in one folder, which
if you’ve got an “images” folder on your

“mydomain_com”. Is that a problem?

we call the root folder. Now we’re going
computer, you’l have one on the server
to copy al that over to the server’s root
too.

folder?

Getting your files to the root folder

You’re now one step away from getting Starbuzz Coffee on the Web: you’ve identified the root folder on your hosting company’s server and all you need to do is copy your pages over to that folder. But The files are sitting
how do you transfer files to a Web server? There are a variety of on your computer.

ways, but most hosting companies support a method of file transfer called FTP, which stands for File Transfer Protocol. You’ll find a number of applications out there that will allow you to transfer your index.html
starbuzz
files via FTP; we’ll take a look at how that works on the next page.

mission.html

Here’s the root folder
on the server.

<html>

.

You need to transfer them

.

.

<html>
to the server, and then
index.html
they’ll be “live” on the Web.

starbuzz

<html>

.

.

.

<html>
mission.html
www.starbuzzcoffee.com
you are here �

131

what’s the goal

A Web Detour

As much FTP as you can possibly fit in t wo pages

Seriously, this really is an HTML and CSS book, but we didn’t want to leave you up a creek without a paddle. So, here’s a very quick guide to using FTP to get your files on the Web. Keep in mind your hosting company might have a few suggestions for the best way to transfer your files to their servers (and since you are paying them, get their help). After the next few pages, we’re off our detour and back to HTML and CSS until we reach the end of the book (we promise).

We’ll assume you’ve found an FTP application. Some are command-line driven, some have complete graphical interfaces, and some are even built into applications like Dreamweaver and GoLive. They all use the same commands, but with some applications you type them in yourself, while in others you use a graphical interface. Here’s how FTP works from 10,000 feet: To connect, you’ll need a
username and password supplied

The words “folder”

1

First connect to your server using FTP.

by your hosting company.

and “directory” are
interchangeable. Most

FTP applications use
ftp www.starbuzzcoffee.com
the word “directory”.

starbuzz
www.starbuzzcoffee.com

In other words, make sure you’re in the
folder “starbuzz” on the server before you

2

Use the “cd” command to change your current directory transfer your files there.

to the directory where you want to transfer files.

cd starbuzz

Changes your
directory to
index.html
starbuzz
starbuzz
mission.html
starbuzz
www.starbuzzcoffee.com

Transfers a copy of the

3

Transfer your files to the server using the “put” command.

“index.html” file into
the current directory
on the server.

put index.html

<html>

.

.

<html>

.

index.html

.

starbuzz

</html>
starbuzz

.

mission.html

.

</html>
index.html
index.html
www.starbuzzcoffee.com

132

Chapter 4

getting connected

A Web Detour

4

You can also make a new directory on the server This is jus with the “mkdir” command.

t like making a new folder, only you’re
doing it on the server, not your own computer.

mkdir images

<html>
index.html

.

starbuzz

.

starbuzz
mission.html

.

</html>

Creates a new
index.html
directory called
www.starbuzzcoffee.com

“images”, inside the
images
starbuzz directory
on the server.

5

You can retrieve files too, with the “get” command.

get index.html

<html>
index.html
starbuzz
starbuzz

.

.

mission.html

.

</html>
index.html

<html>

.

.

.

Transfers a copy of the

</html>
www.starbuzzcoffee.com
file from the serv
images
er
index.html
back to your computer.

Let’s put all that together. Here’s an example of

Most FTP applications come with much friendlier

FTP being used from a command-line application:

graphical interfaces, so feel free to skip right
over this if you’re using one of those.

FTP commands

File Edit Window Help Jam

%ftp www.starbuzzcoffee.com

Connected to www.starbuzzcoffee.com

Connect and login.

Whether you’re typing in FTP commands

Name: headfirst
on the command-line, or using an FTP

Password:******

Get a directory of
application with a graphical interface, the

230 User headfirst logged in.

what is there. One
commands or operations you can perform
ftp> dir
directory
are pretty much the same.

drwx------ 4096 Sep 5 15:07 starbuzz
called

� dir: get a listing of the current directory.

ftp> cd starbuzz

Change to the
starbuzz.

CWD command successful
starbuzz directory.

� cd: change to another directory. “..”

ftp> put index.html
means up one directory here, too.

Transfer index.html

Transfer complete.

there.

� pwd: display the current directory you’re
ftp> dir
in.

-rw------- 1022 Sep 5 15:07 index.htmlLook at the

� put <filename>: transfers the specified
ftp> mkdir images
directory, there’s
filename to the server.

Directory successfully created

� get <filename>: retrieves the specified
ftp> cd images
index.html.

filename from the server

CWD command successful

Make a directory for images, and

, back to your
computer.

ftp> bye
then quit using the bye command
you are here �

133

A Web Detour
there are no

Dumb Questions

Q: My hosting company told

A: Yes, for smal sites, that is normaly Q: Can I edit my files directly on the me to use SFTP, not FTP. What’s the
the way you do things. Use your computer

Web server?

difference?

to test your changes and make sure things
are working the way you want before

A:

transferring your files to the server. For

A: That usualy isn’t a good idea

SFTP, or Secure File Transfer
larger Web sites, organizations often create
because your visitors will see all your

Protocol, is a more secure version of FTP,
a test site and a live site so that they can
changes and errors before you have time to
but works mostly the same way. Just make
preview changes on the test site before they preview and fix them.

sure your FTP application supports SFTP
are moved to the live site.

That said, some hosting companies will
before you make a purchase.

If you’re using a tool like Dreamweaver or
al ow you to log into the server and make

Q:

GoLive, these tools wil al ow you to test
changes on the server. To do that you

So do I edit my files on my
your changes on your own computer, and
usual y need to know your way around a
computer and then transfer them each
then when you save your files, they are

DOS or Linux command prompt, depending
time I want to update my site?

automatically transferred to the Web site.

on what kind of operating system your
server is running.

Popular FTP applications

Here’s a few of the most popular FTP applications for Mac and Most FTP

Windows:

applications have

For Mac OS X:

a trial version you
can download to
ß Fetch (http://fetchsoftworks.com/) is one of the most popular try before you buy.

FTP applications for Mac. $
ß Transmit (http://www.panic.com/transmit/) $
ß Cyberduck (http://cyberduck.ch/) FREE

For Windows:

ß Smart FTP (http://www.smartftp.com/download/) $
ß WS_FTP (http://www.ipswitch.com/products/file-transfer.

asp). FREE for the basic version, $ for the Pro version

134

Chapter 4

getting connected

DO try this at home

It’s another homework assignment for you (check each item as you do it):

® Make sure you know where your root folder is on the server at your hosting company.

® Figure out the best way (and the best tool to use) to transfer files from your computer to the server.

® For now, go ahead and transfer the Starbuzz “index.html” and

“mission.html” files to the root folder of the server.

End of Web Detour

Back to business...

That’s the end of the detour and we’re back on the Web
superhighway. At this point you should have the two

Starbuzz pages, “index.html” and “mission.html”, sitting
under your root folder on a server (or if not, you’re at least following along).

After all this work, wouldn’t it be satisfying to
make your browser retrieve those pages over

<html>
the Internet and display them for you? Let’s

.

.

.

figure out the right address to type into your

</html>
browser...

index.html
starbuzz

<html>

.

.

.

</html>
mission.html
www.starbuzzcoffee.com

All Web page addresses
start with this, right?

We’ll look into what http
means in a sec.

http://
www.starbuzzcoffee.com /
index.html

For the root folder

And here’s the

Here’s the Web site name.

we just use “/”.

page file name.

you are here �

135

uniform resource locators

URL

Mainstreet, USA

You’ve probably heard the familiar “h” “t” “t” “p” “colon”

“slash” “slash” a zillion times, but what does it mean? First, of all, the Web addresses you type into the browser are called URLs or Uniform Resource Locators.

If it were up to us we would have called them “Web addresses,”

A Uniform Resource
but no one asked, so we’re stuck with Uniform Resource

Locator (URL) is a

Locators. Here’s how to decipher a URL:

global address that
http://www.starbuzzcoffee.com/index.html
can be used to locate

The first part of

The second part is

And the third part is
anything on the Web,
the URL tells you
the Web site name.

the absolute path to
the protocol that

At this point you
the resource from the
including HTML
needs to be used
know all about that.

root folder.

to retrieve the
pages, audio, video,
resource.

and many other forms

To locate anything on the Web, as long as you know the server of Web content.

that hosts it, and an absolute path to the resource, you can create a URL and most likely get a Web browser to retrieve it for you using some protocol – usually HTTP.

In addition to
specifying the location
of the resource, a

Come on down

URL also names the
to
http://www.earlsautos.com
protocol that you can
use to retrieve that
resource.

136

Chapter 4

getting connected

What is the HTTP Protocol?

HTTP is also known as the HyperText Transfer Protocol. In other words, it’s an agreed-upon method (a protocol) for transferring hypertext documents around the Web. While “hypertext documents” are usually just HTML pages, the protocol can also be used to transfer images, or any other file that a Web page might need.

HTTP is a simple request and response protocol. Here’s how it works: HTTP Request: could I please
have the file /index.html?

HTTP response: I found
that file, here it is.

Whatever you do,
www.starbuzzcoffee.com
don’t pronounce URL as

“Earl,” because that’s my

So each time you type a URL into your browser’s address bar, the name. It’s pronounced
browser asks the server for the corresponding resource using the HTTP

U-R-L.

protocol. If the server finds the resource, it returns it to the browser and the browser displays it. What happens if the server doesn’t find it?

HTTP Request: could I please have
the file /hardtofind.html?

HTTP response: error

#404, I can’t find it.

www.starbuzzcoffee.com

If the resource can’t be found, you’ll get the familiar “404 Error”, which the server reports back to your browser.

you are here �

137

absolute paths to your files

What’s an Absolute Path?

The last time we talked about paths we were writing HTML to make links with the <a> element. The path we’re going to look at now is the absolute path part of a URL, the last part that comes after the protocol (http) and the Web site name (www.starbuzzcoffee.com).

An absolute path tells the server how to get from your root folder to a particular page or file. Take Earl’s Autos site, for example. Say you want to look in Earl’s inventory to see if your new Mini Cooper has come in. To do that, you’ll need to figure out the absolute path to the file “inventory.html” that is in the “new”

folder. All you have to do is trace through the folders, starting at the root, to get to the “new” folder where his “inventory.html” file is located. The path is made up of all the folders you go through to get there.

So, that looks like root (we represent root with a “/”), “cars”, “new”, and finally, the file itself, “inventory.html”. Here’s how you put that all together: Earl’s Autos

Always start
root folder.

at the root.

“/”

earls_autos

Add on each folder
cars
as you navigate to
the file.

/
cars
new

In between the folder
names, put a “/” to

<html>

<html>
keep them separate.

.

new

.

.

.

.

.

used

</html>

</html>

/
inventory.html
inventory.html

And then add on
the filename.

inventory.html

Absolute path to

“inventory.html”.

/cars/new/inventory.html

138

Chapter 4

getting connected
there are no

Dumb Questions

Q: What is important about the

A: If you add all those things together A: Wow, great question. When you absolute path?

you have a URL, and with a URL you
click on a link that is relative, behind the
can ask a browser to retrieve a page (or
scenes the browser creates an absolute

A:

other kinds of resources) from the Web.

path out of that relative path and the path of

The absolute path is what a server

How? The protocol part tells the browser
the page that you click on. So, al the Web
needs to locate the file you are requesting.

the method it should use to retrieve the
server ever sees are absolute paths, thanks

If the server didn’t have an absolute path, it
resource (in most cases, this is HTTP).

to your browser.

wouldn’t know where to look.

The Web site part (which consists of the

Q:

server name and the domain name) tel s

Q:

the browser which computer on the Internet

Would it help the browser if I put

I feel like I understood the pieces
to get the resource from. And the absolute
absolute paths in my HTML?

(protocols, servers, Web sites, and
path tells the server what page you’re after.

absolute paths), but I’m having trouble
connecting them.

Q:

A: Ah, another good question, but hold

We learned to put relative paths
that thought, we’ll get back to that in a sec.

in the href attribute of our <a> elements.

How can the server find those links if
they aren’t absolute?

Sharpen your pencilYou’ve waited long enough. It’s time to give your new URL a spin. Before you do, fil in the blanks below and then type in the URL (like you haven’t already). If you’re having any problems, this is the time to work with your hosting company to get things sorted out. If you haven’t set up an hosting company, fil in the blanks for www.starbuzzcoffee.com, and type the URL into your browser anyway.

://
protocol

Web site name
absolute path
you are here �

139

easier urls

I’d like my visitors to be able to
type “http://www.starbuzzcoffee.com”

Remember, when we’re
and not have to type the “index.html”. Is
talking about Web servers
there a way to do that?

or FTP, we usually use the
term “directory” instead
of “folder.” But they’re

Yes, there is. One thing we haven’t talked about is what
really the same thing.

happens if a browser asks for a directory rather than a file from a Web server. For instance, a browser might ask for:

http://www.starbuzzcoffee.com/images/

The images directory in
the root directory.

or
http://www.starbuzzcoffee.com/

The root directory itself.

When a Web server receives a request like this, it tries to locate a default file in that directory. Typically a default file is called “index.html” or “default.htm” and if the server finds one of these files, it returns the file to the browser to display. But, you need to find out So, to return a file by default from your root directory (or what your hosting company
any other directory), just name the file “index.html” or
wants you to name your

“default.htm”.

default file, because it
depends on the type of
server they use.

But I asked about

“http://www.starbuzzcoffee.com”,
which looks a little different. It
doesn’t have the ending “/”.

Oops, you sure did. When a server receives a request like
yours without the trailing “/” and there is a directory with that name, then the server will add a trailing slash for you.

So if the server gets a request for:

http://www.starbuzzcoffee.com
it will change it to:

http://www.starbuzzcoffee.com/
which will cause the server to look for a default file, and in the end it will return the file as if you’d originally typed: http://www.starbuzzcoffee.com/index.html

140

Chapter 4

getting connected

How default pages work

Behind

The user types

1
the Scenes
http://www.starbuzzcoffee.com/drinks/
into the browser.

2 HTTP Request: could I please
have the file “/drinks/”?

3 The server says “that
looks like a directory,
is there a default file

5 HTTP response: you asked for a
in that directory?”

directory, but I found “index.html”

in that directory, so that’s what

I’m sending back.

starbuzz

<html>

.

.

.

</html>
drinks
index.html
www.starbuzzcoffee.com

4 Server locates a
default file called

“index.html” in the
drinks directory.

Q:

there are no

So anyone who comes to my site

Dumb Questions

Q: So when I’m giving someone my
with the URL http:/ www.mysite.com is

URL, is it better to include the
going to see my “index.html” page?

“index.html” part or not?

A:

Right. Or, possibly “default.htm”

There are other possible default filenames,

A: Not. It’s always better to leave it off.

depending on which kind of Web server
like “index.php”, that come into play if you

What if, in the future, you change to another
your hosting company is using. (Note that
start writing scripts to generate your pages.

Web server and it uses another default file

“default.htm” usually has no “l” on the end.

That’s way beyond this book, but that
name like “default.htm”? Or you start writing

This is a Microsoft Web Server oddity.)

doesn’t mean you won’t be doing it in the
scripts and use the name “index.php”? Then

future.

the URL you originally gave out would no

longer be valid.

you are here �

141

Earl needs a little help with his URLs

Earl may know Earl, but he doesn’t know U-R-L. He needs a little help figuring out the URL
for each of the files below, labeled A, B, C, D, and E. On the right, write in the URL needed to retrieve each corresponding file from www.earlsautos.com.

Earl’s root folder.

<html>

.

.

A

.

</html>
earls_autos
index.html

<html>

.

.

B

.

</html>
directions.html
cars

<html>

<html>

.

.

.

.

C

.

.

</html>

</html>
new
index.html
used
index.html

<html>

<html>

.

.

.

.

D

.

.

</html>

</html>
inventory.html
inventory.html

E
images
images
minicooper.gif
thunderbird.gif
element.gif
mustang.gif

142

Chapter 4

getting connected

Write the URL here.

A

B

C

D

E
you are here �

143

linking to other web pages

Fantastic! We’re up and
running on the Web. I’m
already hearing great buzz
about our site in the stores.

By the way, we’ve got a new
caffeine awareness program; we
figure if we’re going to be pumping people
ful of caffeine we want them to know
how to take it to the limit. Can we point
people to the caffeine information
over on buzz.headfirstlabs.com from
our site?

How do we link to other Web sites?

URLs aren’t just for typing into browsers; you can use them right in your HTML. And, of course, right on cue, the Starbuzz CEO has a new task for you: make a link from the main Starbuzz page over to the caffeine information at http://buzz.headfirstlabs.com. As you can probably guess, we’re going to throw that URL right into an <a> element.

Here’s how:

<a href=”http://buzz.headfirstlabs.com”>Caffeine Buzz</a> An everyday, normal, garden-variety <a> element.

We’ve put a URL in the href. Clicking on the label “Caffeine Buzz”

will retrieve a page from buzz.headfirstlabs.com.

That’s all there is to it. To link to any resource on the Web, all you need is its Uniform Resource Locator, which goes in the <a> element as the value of the href attribute. Let’s go ahead and add this in the Starbuzz “index.html” page.

144

Chapter 4

getting connected

Linking to Caffeine Buzz

Open your Starbuzz “index.html” file in the “chapter4/starbuzz” folder, and scan down to the bottom. Let’s add two new links: a relative link to the mission statement in

“mission.html”, and a link to Caffeine Buzz. Make the changes below, then save and load your “index.html” file in your browser. Click on the link and enjoy the Caffeine Buzz.

<html>

<head>

<title>Starbuzz Coffee</title>

<style type=”text/css”>

body {

background-color: #d2b48c;

margin-left: 20%;

margin-right: 20%;

border: 1px dotted gray;

padding: 10px 10px 10px 10px;

font-family: sans-serif;

}

</style>

</head>

<body>

<h1>Starbuzz Coffee Beverages</h1>

<h2>House Blend, $1.49</h2>

<p>A smooth, mild blend of coffees from Mexico,

Bolivia and Guatemala.</p>

<h2>Mocha Cafe Latte, $2.35</h2>

<p>Espresso, steamed milk and chocolate syrup.</p>

<h2>Cappuccino, $1.89</h2>

<p>A mixture of espresso, steamed milk and foam.</p> Here’s the link to the “mission.

<h2>Chai Tea, $1.85</h2>

<p>A spicy drink made with black tea, spices,
html” file. This uses a
milk and honey.

relative path to link to

</p>

“mission.html”. We added a <br> to

<p>
put the links on two

<a href=”mission.html”>Read about our Mission</a> different lines.

<br>

Read the <a href=”http://buzz.headfirstlabs.com”>Caffeine Buzz</a>

</p>

</body>

Here’s where we’ve

</html>
added the link t

And we’ve added some struc
o the
ture
bu
her
zz.headfir
e by grouping the link
stlabs.com page.

s and
text into a paragraph.

you are here �

145

testing those links

And now for the test drive...

Here’s the page with the
new link, just as we planned.

Here’s the new link. Notice, we only
linked the words “Caffeine Buzz” so
it looks a little different from the
other link.

And when you click on the link,
your browser will make an HTTP
request to buzz.headfirstlabs.com
and then display the result.

146

Chapter 4

getting connected
there are no

Dumb Questions

Q:

It seems like there are two ways for example, “file:///chapter4/starbuzz/

At Caffeine Buzz we use relative
to link to pages now: relative paths and index.html”, tells the browser that the links to other pages on our site,

URLs.

file “index.html” is located at the path

“/chapter4/starbuzz/”. This path may look
and URLs to link offsite, like
www.caffeineanonymous.com.

A:

different depending on your operating

Well, relative paths can only be
system.

used to link to pages within the same Web One important thing to notice in case you site, while URLs are typical y used to link
try to type in a file URL is that the file URL
to other Web sites.

has three slashes, not two, like HTTP.

Q:

Remember it this way: if you take an HTTP

URL and delete the Web site name you’ll

Wouldn’t it be easier if I just
have three slashes, too.

stuck with URLs for links to my own
pages and outside pages? That would

Q:

work wouldn’t it?

Are there other protocols?

A: Sure, it would work, but there’s A: Yes, many browsers can support a couple of reasons you don’t want to go
retrieval of pages with the FTP protocol,
there. One problem is that URLs are hard
and there is a mail protocol that can send
to manage when you have a lot of them in
data via email. HTTP is the protocol you’ll
a Web page: they’re long, difficult to edit,
be using most of the time.

and they make HTML more difficult to read

(for you, the page author).

Q: I’ve seen URLs that look like

Also, if you have a site with nothing but
this: http://www.mydomain.com:8000/

URLs that link to local pages and you
index.html. Why is there a “:8000” in
move the site or change its name, you
there?

have to go change all those URLs to
reflect the new location. If you use relative
paths, as long as your pages stay in the

A: The “:8000” is an optional “port”

same set of folders – because the links
that you can put in an HTTP URL. Think
are al relative – you don’t have to make
of a port like this: the Web site name is
any changes to your <a> element href
like an address, and the port is like a
attributes.

mailbox number at an address (say, in an

So, use relative links to link to your own
apartment complex). Normal y everything
pages in the same site, and URLs to link
on the Web is delivered to a default port
to pages at other sites.

(which is 80), but sometimes Web servers

Q:

are configured to receive requests at a
dif erent port (like 8000). You’l most likely

Haven’t we seen one other
see this on test servers. Regular Web
protocol? I kept seeing “file:/ ” before
servers almost always accept requests
we started using a Web server.

on port 80. If you don’t specify a port, it
defaults to 80.

A: Yes; good catch. The file protocol
is used when the browser is reading files
right off your computer. The file URL,
you are here �

147

time for a little mystery

The Case of Relatives and Absolutes

PlanetRobots, Inc., faced with the task of developing a Web site for each of its two company divisions – PlanetRobot Home and PlanetRobot Garden – decided to contract with two firms to get the work done.

RadWebDesign, a seemingly experienced firm, took on the Home division’s Web site and proceeded to write the site’s internal links using only URLs (after all, they’re more complicated, they must be better). A less experienced, but wel -schooled firm, CorrectWebDesign, was Five-Minute
tasked with PlanetRobot’s Garden site, and used relative paths for links between all the pages within the site.

Mystery

Just as both projects neared completion, PlanetRobots called with an urgent message: “We’ve been sued for trademark infringement, so we’re changing our domain name to RobotsRUs. Our new Web server is going to be www.robotsrus.com.” CorrectWebDesign made a couple of small changes that took all of five minutes and was ready for the site’s unveiling at the RobotsRUs corporate headquarters.

RadWebDesign, on the other hand, worked until 4 a.m. to fix their pages but luckily completed the work just in time for the unveiling. However, during a demo at the unveiling, the horror-of-horrors occurred: as the team leader for RadWebDesign demonstrated the site he clicked on a link that resulted in a “404 - Page Not Found” error. Displeased, the CEO
of RobotsRUs suggested that RadWebDesign might want to consider changing their name to BadWebDesign and asked CorrectWebDesign if they were available to consult on fixing the Home site.

What happened? How did RadWebDesign flub things up so
badly when all that changed was the name of the Web server?

148

Chapter 4

getting connected

Web page fit and finish

Can you say “Web career?” You’ve certainly delivered everything the Starbuzz CEO has asked for, and you’ve now got a high profile Web site under your belt (and in your portfolio).

But you’re not going to stop there. You want your Web sites to have that professional “fit and finish” that makes good sites into great ones. You’re going to see lots of ways to give your sites that extra “polish” in the rest of this book, but let’s start here with a way to improve your links.

Improving accessibility by adding a title to your links

Wouldn’t it be nice if there was a way to get more information about the link you’re about to click on? This is especially important for the visually impaired using screen readers because they often don’t want the entire URL spoken to them: (“h” “t” “t” p” “:” “slash” “slash” “w” “w” “w” “dot”) and yet the link’s label usually only gives a limited description, like “Caffeine Buzz”.

The <a> element has an attribute called title just for this purpose. Some people are confused by this attribute name because there’s an element called

<title> that goes in the <head> . They have the same name because they are related – it is often suggested that the value of the title attribute be the same as value of the <title> element of the Web page you are linking to. But that isn’t a requirement and often it makes more sense to provide your own, more relevant description in the title attribute.

Here’s how you add a title attribute to the <a> element: Read the <a href=”http://buzz.headfirstlabs.com”

title=”Read all about caffeine on the Buzz”>Caffeine Buzz</a> The title element has a value that is a textual
description of the page you are linking to.

Now that we’ve got a title at ribute, let’s see how your visitors would make use of it. Dif erent browsers make dif erent use of the title, but many display a Exercise
tool tip. Add the changes above to your “index.html” file and reload the page to see how it works in your browser.

you are here �

149

best practices for your links

The title test drive...

For most browsers, the title is displayed
as a “tool tip” when you pass the
mouse over a link. Remember that
browsers for the visually impaired may
read the link title aloud to a visitor.

The title is displayed
as a “tool tip” in
most browsers. Just
pass your mouse over
the link and hold it
there a second to see
the tool tip.

The Head First Guide to Better Links

Here are a few tips to keep in mind to further improve the fit and finish of your links: b Ke p your link labels concise. Don’t make entire sentences or large pieces of text into links. In general, keep them to a few words. Provide additional information in the title attribute.

b Ke p your link labels meaningful. Never use link labels like “click here” or “this page”. Users tend to scan pages for links first, and then read pages second. So, providing meaningful links improves the usability of your page. Test your page by reading just the links on it; do they make sense? Or do you need to read the text around them?

b Avoid placing links right next to each other; users have trouble distinguishing betwe n links that are placed closely together.

150

Chapter 4

getting connected

Open your Starbuzz “index.html” file and add a title to the link to Exercise

“mission.html” with the text “Read more about Starbuzz Coffee’s important mission”. Notice that we didn’t make the mission link’s label as concise as it should be. Shorten the link label to “our Mission”.

Check the back of the chapter for the answer, and test your changes.

Great job on the links. I’d
really like for people to link
directly to the coffee section
of the Buzz site. Is that
possible?

Linking into a page

So far, whenever you’ve linked to another page, the page loads and your browser displays it from the top.

But, the CEO’s asking you to link into a particular spot in the page: the Coffee section.

Sound impossible? Come on, this is Head First – we’ve got the technology. How? Well, we haven’t told you everything about the

<a> element yet. Turns out the <a> element can play two roles: you’ve already seen it act as the jumping off point for traveling from one page to another, but it can also act as a landing point or
destination of a link.

you are here �

151

creating destinations

Using the <a> element to create a destination

When you use an <a> element to create a destination, we call that a

“destination anchor.” Creating a destination anchor is straightforward.

Here’s how you can do it in three short steps:

1

Find the location in the page where you’d like to
create a landing spot. This can be any text on
the page, but often is just a short piece of text in
a heading.

2

Wrap the text within an <a> element.

3

Choose a identifier name for the destination, like

“coffee” or “summary” or “bio”, and insert an id
attribute into your <a> element.

Let’s give it a try. Say you want to provide a way to link to the Chai Tea item on the Starbuzz page. Here’s what it looks like now:

Here’s the snippet
from “index.html”

<h2> Chai Tea, $1.85</h2>
with the Chai heading

<p> A spicy drink made with black tea, spices, milk and and description.

honey. </p>

Following the three steps above, we get this:

Add the <a> opening

And we’ll give this And then end
tag before the text.

destination the
the element with
identifier “chai”.

a closing tag.

Make sure your <a>
element is properly
nested inside y

<h2><a id=”chai”> Chai Tea, $1.85</a></h2> our

<h2> element.

<p> A spicy drink made with black tea, spices, milk and honey. </p>

You’ve made a destination anchor
out of the Chai Tea heading in
the “index.html” page.

152

Chapter 4

getting connected

How to link to destination anchors

You already know how to link to pages using either relative links or URLs. In either case, to link more specifically to a destination anchor in a page, just add a # on the end of your link, followed by the destination anchor identifier.

So if you wanted to link from any Starbuzz Coffee Web page to the “chai”

destination anchor you’d write your <a> element link this:

<a href=”index.html#chai”>See Chai Tea</a>

Unfortunately, linking to Chai Tea with a destination anchor isn’t very The main benefit of
impressive because the whole page is small enough that it easily fits in the destination anchors is to
browser. Let’s link to the Coffee section of http://buzz.headfirstlabs.com link to locations in long files
instead. Here’s what you’re going to do:

so your visitors don’t have
to scroll through the file
looking for the right section.

1

Figure out the id of the destination anchor.

2

Alter the existing <a> element in the Starbuzz Coffee

“index.html” file to point to the destination anchor.

3

Reload your “index.html” page and test out the link.

Finding the destination anchor

To find the destination anchor, you’re going to have
to look at the buzz.headfirstlabs.com page and view
their HTML. How? Almost all browsers have a

“View Source” option. So, visit the page and when
it is fully loaded, choose the “View Source” option,
and you’ll see the markup for the page.

In most browsers, you can
right-click to “View Source”.

You’ll also find “View Source”

in the browser menu, usually
under “View”.

you are here �

153

linking to a destination anchor

Now that you’ve got your hands on their HTML...

Scroll down until you see the Coffee section; it looks like this: Just a small snippet from
the Caffeine Buzz page.

This is similar to the naming problem
with <b>mateine</b> and <b>guaranine</b>.

Here’s the Coffee section. You can

</p>
see the heading for it along with
the start of the paragraph below.

<h3><a id=”Coffee”> Coffee</a></h3>

<p>

<i> All fluid ounces are U.S. fluid ounces. </i>

</p>

Ahhh, and here is the
destination anchor. It has
the name “Coffee”.

Reworking the link in “index.html”

Now all you need to do is revisit the link to Caffeine Buzz and add on the destination anchor name, like this:

Add # along with the

This is a snippet from the
destination anchor id to

Starbuzz “index.html” file.

your href.

Read the <a href=”http://buzz.headfirstlabs.com#Coffee”

title=”Read all about caffeine on the Buzz”> Caffeine Buzz</a> Make this change to your Starbuzz

“index.html” file. Reload and click on
the “Caf eine Buzz” link. You should be

Exercise
taken directly to the Cof ee section of

Caffeine Buzz’s front page.

154

Chapter 4
getting connected
there are no

Dumb Questions

Q: When I have two attributes in

Q: If a Web page doesn’t provide a
an element, is the order important? For

A: Think of it this way: you have to destination anchor and I stil need to link example, should the title attribute always
link from something to something else. The to a specific part of the page, how can I?

come after the href?

<a> element with an href provides a way

A:

to describe the from something. And the

A:

to something has always been just the top

You can’t. If there is no destination

The order of at ributes is not
of the other Web page – in other words,
anchor then you can’t direct the browser to
important in any element (if it were we’d all
you got the to something for free. With the go to a specific location in a Web page. You
have headaches 24/7). So, use any ordering destination anchor you can also define the might try to contact the page author and
you like.

to something yourself. So, while confusing,
ask them to add one (even bet er, tel them

Q:

there is some sanity to the naming.

how!).

Normal y when I use an <a>
element the browser underlines the text,

Q:

Q:

I noticed in the anchor id names,

Can I have a destination anchor id
but when I used the id attribute instead of you used “chai” with al lowercase letters like “Jedi Mindtrick” or does an id have href, it doesn’t.

and Caffeine Buzz used “Coffee” with a
to be only one word?

A:

upper case “C”. Does it matter?

Right. When you use the id attribute

A: To work consistently with the most
it has no effect on the look of the text the

A: You can use any combination
browsers, always start your id with a letter

<a> element surrounds. Remember, the
of upper- and lowercase characters in

(A-Z or a-z) and fol ow it with any let er,
point of the destination anchor (<a> with the
your id at ributes. Just make sure you
digit, hyphen, underscore, colon, or period.

id at ribute) is just to mark the location within are consistent and always use the same So, since you can’t use a space, you can’t
the page, not to create a link, so there isn’t
upper- and lowercase let ers in your hrefs
have a name like “Jedi Mindtrick”; but that
any need to display it visually.

and destination anchor id (which is why
isn’t much of a restriction because you

Q:

it is often easier to make these names
can always have “Jedi-Mindtrick”, “Jedi_

Mindtrick”, “JediMindtrick”, and so on.

Why is it called an anchor?

entirely lowercase every time). If you aren’t

What’s anchor-like about it?

consistent, don’t expect your links to work
correctly on every browser.

Q: How can I tel others what

A:

destination anchors they can link to?

On this one we’re just going to say

Q: Can I put a link to a destination
it like it is: ”anchor” was a bad choice of
anchor from within the same document?

names and has confused tens of thousands

A: There is no established way of doing
before you, if not mil ions. We’re not even
this, and in fact, “View Source” remains the
going to try to give you a cute metaphor

A: Sure. In fact, it is common to
oldest and best technique for discovering the
to understand how it could possibly be an
define a destination anchor “top” at the top
destination anchors you can link to.

anchor. Basical y we’re al stuck with the
of a page and have a link at the bot om
name, but now you do know what it does,
of the page saying “Back to top”. It is also
and before long you won’t even give the
common in long documents to have a
name a second thought.

table of contents for the entire page. For

Q:

instance, to link to the “top” destination

Well even with the bad name,
anchor in the same page, you would write
why use the same element to do such

<a href=”#top”>Back to top</a>.

different things? Why not have separate
linking and destination elements?

you are here �

155

case solved, its all about relative and absolute

The Case of Relatives and Absolutes

So, how did RadWebDesign flub up the demo? Wel , because
they used URLs for their hrefs instead of relative links, they had to edit and change every single link from
http://www.planetrobots.com to http://www.robotsrus.com. Can you say error-prone? At 3:00 a.m., someone yawned

Oops...

and accidently typed ht p:/ www.robutsru.com (and
someone
as fate has it, that was the same link that the CEO

Five-Minute
forgot an “s”

clicked on at the demo).

on the end

CorrectWebDesign, on the other hand, used relative

Mystery
of the name.

paths for all internal links. For example, the link from
the company’s mission statement to the products page,

<a href=”../products.html”> , works whether the site is Solved
called PlanetRobots or RobotsRUs. So, all CorrectWebDesign
had to do was update the company name on a few pages.

So RadWebDesign left the demo sleep-deprived and with a little egg on their face, while CorrectWebDesign left the meeting
with even more business. But, the story doesn’t end there. It turns out that RadWebDesign dropped by a little coffeehouse/
bookstore after the demo and, determined not to be outdone, picked up a certain book on HTML & CSS. What happened?

Join us in a few chapters for “The Case of Brute Force versus Style.”

156

Chapter 4

getting connected

Awesome job linking
to the Buzz site... I know I keep
asking for changes, but really, this
is the last one. Can you make the Buzz site
come up in a separate window when I click
on the link? I don’t want the Starbuzz
page to go away.

Linking to a new window

We have another new requirement from the

Starbuzz CEO (there are always new requirements
for Web sites). What he wants is this: when you
click on the “Caffeine Buzz” link in the Starbuzz

Coffee page, the Starbuzz Coffee page shouldn’t go
away. Instead a whole new window should open
up with the Caffeine Buzz page in it, like this:

Here’s the main

When the Caffeine Buzz

Starbuzz Coffee page
window pops open, it will open
over the top of the Starbuzz
page, but the Starbuzz page
will still be there.

What the CEO wants is
a whole new window to
open when you click on
the Caffeine Buzz link
you are here �

157

targeting windows

Opening a new window using target

To open a page in a new window, you need to tell the browser the name of the window in which to open it. If you don’t tell the browser a specific window to use, the browser just opens the page in the same window. You can tell the browser to use a different window by adding a target attribute to the <a> element. The value of the target attribute tells the browser the “target window” for the page. If you use “_blank” for the target, the browser will always open a new window to display the page. Let’s take a closer look:

<a target=”_blank” href=”http://buzz.headfirstlabs.com”

title=”Read all about caffeine on the Buzz”>Caffeine Buzz</a> The target attribute tells the browser where
to open the Web page that is at the link in
the href attribute. If there is no target,
then the browser opens the link in the same
window. If the target is “_blank” then the
browser opens the link in a new window.

there are no

Exercise

Dumb Questions

Open your Starbuzz “index.html”

Q: What if I have more than one <a> element
file. Add the target attribute
with a target? If there’s already a “_blank” new
to the <a> tag that links to the
window open, wil it open in the window that’s

Caffeine Buzz page. Now give it a
already open? Or will it open in a new “_blank”

try – did you get a new window?

window?

A: If you give the name “_blank” to the targets
in al your <a> elements, then each link wil open in a new blank window. However, this is a good question
brain
because it brings up an important point: you don’t
actual y have to name your target “_blank”. If you
power

?

give it another name, say, “cof ee”, then al links
with the target name “cof ee” wil open in the same

Can you think of some advantages
window. The reason is that when you give your target
and some disadvantages to using
a specific name, like “cof ee”, you are real y naming
the target attribute to open a page
the new window that wil be used to display the page
in a new window?

at the link. “_blank” is a special case that tel s the
browser to always use a new window.

158

Chapter 4

getting connected

The Target Attribute Exposed

This week’s interview:

Using target considered bad?

Head First: Hello target, we’re so glad you
they’re reading, it can be very confusing for
could join us.

them. It’s hard to tell what’s going on when

Target Attribute: I’m glad to be here. It’s
you’re not looking at the whole screen at once.

nice to know you’re still interested in hearing

Target: Yeah I suppose it would be. It’s
about me.

probably difficult for using screen readers, too.

Head First: Why do you say that?

Head First: Yup. Some screen readers play

Target: Well, to be honest, I’m not as popular
a sound when a new window opens, but others
as I used to be.

just ignore the new window completely, or else
they jump right to the new window immediately.

Head First: Why do you think that is?

Either way, it’s gotta be confusing for someone

Target: I think it’s because users want to be
who can’t see what’s going on. And of course,
in control of when a window opens. They
since the page is in a whole new window, there’s
don’t always like new windows popping open at
no way to use the back button to get back to the
unexpected times.

original window.

Head First: Well, it can be very confusing

Target: [Sigh] I’m starting to see why I’m not

– we’ve had complaints from people who end
as popular as I used to be.

up with so many windows on their screens, they

Head First: Don’t get too depressed; there are
can’t find the original page.

times when it’s nice to have a new window open,

Target: But it’s not like it’s difficult to get rid of right?

the windows... just click on the little close button. Target: Yes, I always thought having those little What’s so hard about that?!

informational windows for “extra information”

Head First: True, but if users don’t know
was handy, and I’m especially proud when
a new window has opened then they can
people use me to open large versions of images.

get confused. Sometimes the new window

That way, the user can view the large image and
completely covers the old window and it’s hard
then go right back to the main page.

to tell what’s happening. That can be confusing

Head First: Okay, see, you do come in handy
for anyone, but especially for someone with a
at times. We’ve just got to remember to use you
visual impairment.

when it’s appropriate, but to keep in mind those

Target: Oh, I never thought of that.

people who might be visually impaired and not
overuse you.

Head First: Well, think about it: if someone’s
got their browser window magnified, and a

Target: Right!

whole new window opens on top of the one
you are here �

159

a little brain crossover

HTMLcross

Here are some mind benders for your left brain.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

Across

Down

2. Wrong way to pronounce URL.

1. People scan these rather than reading text.

4. Attribute used to anchor an <a> element to a

3. Path from the root.

page.

5. What are you supposed to send back from

7. Earl sold these.

Webville?

8. Web address to a resource.

6. Informative caffeine site.

9. Protocol we've been using up until this chapter.

7. Keep your link labels ______.

11. Unique name on the Web.

10. Controls domain names.

12. Always use these kinds of links when linking to

11. _______ file you get when you ask for a
pages on the same server.

directory.

13. Request/response protocol.

12. Top directory of your Web site.

14. Most popular Mac FTP application.

160

Chapter 4

getting connected

BULLET POINTS

n

Typically the best way to get on the Web is

n

The file protocol is used by the browser to
to find a hosting company to host your Web
read pages from your computer.

pages.

n

An absolute path is the path from the root

n

A domain name is a unique name, like
folder to a file.

amazon.com or starbuzzcoffee.com, that is
used to identify a site.

n

“index.html” and “default.htm” are examples
of default pages. If you specify a directory

n

A hosting company can create one or more
without a filename, the Web server will look for

Web servers in your domain. Servers are
a default page to return to the browser.

often named “www”.

n

You can use relative paths or URLs in your

n

The File Transfer Protocol (FTP) is a common

<a> element’s href attribute to link to other
means of transferring your Web pages and

Web pages. For other pages in your site, it’s
content to a server.

best to use relative paths, and use URLs for
external links.

n

FTP applications, like Fetch for Mac or

WS_FTP for Windows, can make using FTP

n

Use the id attribute to create a destination
easier by providing a graphical user interface.

anchor in a page. Use ‘#’ followed by a
destination anchor id to link to that location in

n

A URL is a Uniform Resource Locator, or Web
address, that can be used to identify any
a page.

resource on the Web.

n

To help accessibility, use the title attribute
to provide a description of the link in <a>

n

A typical URL consists of a protocol, a Web
site name, and an absolute path to the
elements.

resource.

n

Use the target attribute to open a link in
another browser window. Don’t forget that

n

HTTP is a request and response protocol
used to transfer Web pages between a Web
the target attribute can be problematic for
server and your browser.

users on a variety of devices and alternative
browsers.

Wait, wait! Before you go, we need
our logo on the Web page! Hello?

Oh, I guess they’ve already gone on to

Chapter 5...

you are here �

161

exercise solutions

Sharpen your pencil

Solution
http

:// www.starbuzzcoffee.com /index.html
protocol

Web site name
absolute path

Your Web site name here.

1 L

2

3

4

E A R

L

I D

B

N

5

S

P

K

6

7

B

O

O

C A R S

8

9

10

U R

L

S

O

F

I

L

E

Z

U

T

N

C

11

Z

T

C

C

D O M A

I N

12

R

E

L A T

I

V

E

N

O

R

S

F

N

O

D

E

A

13

H T T

P

U

L

14

F

E

T C H

Across

Down

2. Wrong way to pronounce URL. [earl]

1. People scan these rather than reading text.

162

4. Attribute used to anchor an <a> element to a

[links]

Chapter 4 page. [id]

3. Path from the root. [absolute]

7. Earl sold these. [cars]

5. What are you supposed to send back from

8. Web address to a resource. [url]

Webville? [postcard]

9. Protocol we've been using up until this chapter.

6. Informative caffeine site. [buzz]

[file]

7. Keep your link labels ______. [concise]

11. Unique name on the Web. [domain]

10. Controls domain names. [ICANN]

12. Always use these kinds of links when linking to

11. _______ file you get when you ask for a
pages on the same server. [relative]

directory. [default]

13. Request/response protocol. [http]

12. Top directory of your Web site. [root]

getting connected

Earl needs a little help with his URLs

Solution

A
http://www.earlsautos.com/

B
http://www.earlsautos.com/directions.html

C
http://www.earlsautos.com/cars/new/

D
http://www.earlsautos.com/cars/used/inventory.html

E
http://www.earlsautos.com/cars/new/images/minicooper.gif
you are here �

163

exercise solutions

Add a title to the link to “mission.html” with the text “Read more about Starbuzz Cof ee’s important mission”. Notice that we didn’t make the mission Exercise
link’s label as concise as it should be. Shorten the link label to “our Mission”.

Solutions

Here’s the solution; did you test your changes?

<html>

<head>

<title>Starbuzz Coffee</title>

<style type=”text/css”>

body {

background-color: #d2b48c;

margin-left: 20%;

margin-right: 20%;

border: 1px dotted gray;

padding: 10px 10px 10px 10px;

font-family: sans-serif;

}

</style>

</head>

<body>

<h1>Starbuzz Coffee Beverages</h1>

<h2>House Blend, $1.49</h2>

<p>A smooth, mild blend of coffees from Mexico,

Bolivia and Guatemala.</p>

<h2>Mocha Cafe Latte, $2.35</h2>

<p>Espresso, steamed milk and chocolate syrup.</p>

<h2>Cappuccino, $1.89</h2>

<p>A mixture of espresso, steamed milk and foam.</p>

<h2>Chai Tea, $1.85</h2>

Add a title

<p>A spicy drink made with black tea, spices,
attribute milk and honey.

to the

Move the “Read about” outside the <a> element.

</p>
mission link.

<p>

Read about <a href=”mission.html”

title=”Read more about Starbuzz Coffee’s important mission“>our Mission</a>

<br>

Read the <a href=”http://buzz.headfirstlabs.com”

title=”Read all about caffeine on the Buzz”>Caffeine Buzz</a>

</p>

</body>

</html>

164

Chapter 4

5 adding images to your pages

Meeting the Media

Smile and say “cheese.” Actually, smile and say “gif”, “jpg”, or “png”

– these are going to be your choices when “developing pictures” for the Web. In this chapter you’re going to learn all about adding your first media type to your pages: images. Got some digital photos you need to get online? No problem. Got a logo you need to get on your page? Got it covered. But before we get into all that, don’t you still need to be formally introduced to the <img> element? So sorry, we weren’t being rude, we just never saw the “right opening.” To make up for it, here’s an entire chapter devoted to <img>. By the end of the chapter you’re going to know all the ins and outs of how to use the <img> element and its attributes. You’re also going to see exactly how this little element causes the browser to do extra work to retrieve and display your images.

this is a new chapter

165

images in your html

How the browser works with images

Browsers handle <img> elements a little differently than other elements. Take an element like an <h1> or a <p> . When the browser sees these tags in a page, all it needs to do is display them. Pretty simple. But, when a browser sees an <img> element something very different happens: the browser has to retrieve the image before it can be displayed in a page.

The best way to understand this is to look at an example. Let’s take a quick look back at the elixirs page from the Head First Lounge, which has four <img> elements:

<html>

<head>

<title> Head First Lounge Elixirs</title>

</head>

<body>

<h1> Our Elixirs</h1>

<h2> Green Tea Cooler</h2>

<p>

<img src=”../images/green.jpg”>

Chock full of vitamins and minerals, this elixir
combines the healthful benefits of green tea with
a twist of chamomile blossoms and ginger root.

</p>

<h2> Raspberry Ice Concentration</h2>

<p>

<img src=”../images/lightblue.jpg”> Combining raspberry juice with lemon grass,
citrus peel and rosehips, this icy drink

We’ve got four images
will make your mind feel clear and crisp.

in this HTML.

</p>

<h2> Blueberry Bliss Elixir</h2>

<p>

<img src=”../images/blue.jpg”>

Blueberries and cherry essence mixed into a base
of elderflower herb tea will put you in a relaxed
state of bliss in no time.

</p>

<h2> Cranberry Antioxidant Blast</h2>

<p>

<img src=”../images/red.jpg”>

Wake up to the flavors of cranberry and hibiscus
in this vitamin C rich elixir.

</p>

<p>

<a href=”../lounge.html”> Back to the Lounge</a>

</p>

</body>

</html>

166

Chapter 5

adding images to your web pages

Now let’s take a look behind the scenes and step through how the browser retrieves and displays this page when it is requested from http://lounge.headfirstlabs.com:

Behind
the Scenes

1

First the browser retrieves the file “elixir.html” from the server.

Empty browser window, nothing retrieved yet.

<html>

<head>

<title> Another

<html>

Page</title>

<head>

</head>

<title> Head

<body>

First Lounge Elix-

<h1> Another
irs</title>

Page</h1>

</head>

...

<body>

“I need the HTML f le ‘elixir.html’”

</html>

<h1> Our Elix-
irs</h1>

...

</html>

“ Found it,

Web Server
here ya go”

Browser

Next the browser reads the “elixir.html” file, displays it, and sees it 2
has four images to retrieve. So, it needs to get each one from the Web server, starting with “green.jpg”.

The HTML page is retrieved, but the browser
still needs to get the images.

<html>

<head>

<title> Another

<html>

Page</title>

<head>

</head>

<title> Head

<body>

First Lounge Elix-

<h1> Another

“Oh, it looks like I need green.jpg, too
irs</title>

Page</h1>

”

</head>

...

<body>

</html>

<h1> Our Elix-
irs</h1>

...

</html>

“ Found it,

Web Server
here ya go”

Browser
you are here �

167

how browsers load images

3

Having just retrieved “green.jpg”, the browser displays it and then moves on to the next image: “lightblue.jpg”.

“green.jpg”

<html>

<head>
displayed.

<title>

My Playlist

<html>

</title>

<head>

<head>

<title> Head

<body>

<h1>Kick’n Tunes

First Lounge Elix-
h, it looks like I need lightblue.jpg, to

</h1>
irs</title>

<p>BT - Satellite:

o
nice downbeat tune.

</head>

</p>

<body>

<p>

”

<h1> Our Elix-

...

“O
irs</h1>

...

</html>

“ Found it,

Web Server
here ya go”

Browser

4

Now the browser has retrieved “lightblue.jpg”, so it displays that image and then moves on to the next image, “blue.jpg”. This process continues for each image in the page.

<html>

<head>

<title>

My Playlist

<html>

</title>

<head>

<head>

<title> Head

<body>

<h1>Kick’n Tunes

First Lounge Elix-

</h1>
irs</title>

<p>BT - Satellite:

nice downbeat tune.

</head>

</p>

<body>

<p>

<h1> Our Elix-

...

irs</h1>

“Oh, it looks like I need blue.jpg, too”

...

</html>

“lightblue.jpg”

displayed.

“ Found it,

Web Server
here ya go”

Browser

168

Chapter 5

adding images to your web pages

How images work

Images are just images, right? Well, actually there are a zillion formats for images out there in the world, all with their own strengths and weaknesses. But luckily, only two of those formats are commonly used on the Web: JPEG and GIF. The only tricky part is deciding which to use when.

What’s the difference bet ween JPEG and GIF?

Use JPEG for photos and

Use GIF for images with solid
complex graphics
colors, logos, and geometric shapes.

Works best for continuous tone images,

Works best for images with a few
like photographs.

solid colors, and images with lines,
like logos, clip art, and small text in
images.

Can represent images with up to 16

Can represent images with up to 256
million different colors.

different colors.

Is a “lossy” format because to

GIF also compresses the file to
reduce the file size, it throws away
reduce its size, but doesn’t throw
some information about the image.

anything way. So, it is a “lossless”

format.

Does not support transparency.

Allows one background color to be
set to “transparent” so that anything
underneath the image will show
through.

you are here �

169

differences between gif and jpeg

Tonight’s talk: JPEG and GIF compare
their images.

JPEG

GIF

Hello again, GIF. Didn’t I just see you on a

Web page?

Yeah... wouldn’t it be nice if everyone just stuck
to GIF? Then I wouldn’t have to run into you
so often.

Hah. As soon as you get good at representing
complex images, like photos, I’m sure people
wil be happy to stick with you, but you still
don’t know how to represent anything that
needs more than a puny 256 colors.

Hey, representing photos is easy if you’re willing
to lose quality. But I’m all about quality. If I can’t represent an image fully, I won’t do it. Just
take a look at some of the logos you’ve tried to
represent ... Yuck.

You wanna talk to me about quality? I let my
users choose exactly how much quality they
want.

Yeah, but at what cost? Face it, to get a photo
down to a size that is reasonable to transmit
over the Web, you have to lose a little quality in
the image.

That’s true, but most people are more than
happy with that. Not everyone needs super high-
resolution images on their pages. With me, users
can usual y choose a quality setting of low or
medium and they are just fine with the quality
of the images. And, if they used you instead,
they’d have huge files for the same image.

Sure, sure, but have you ever looked at lines,
logos, small text, solid colors? They don’t look so
great with JPEG.

170

Chapter 5
adding images to your web pages

JPEG

GIF

Yeah, sure, GIF works great for those, but only
as long as there are a smal number of those
colors. You’re just like a lesser version of me. I
can do anything you can.

{GIF disappears, literally}

Say what? GIF? We’re doing a show here.

Where’d you go?

{GIF reappears}

Don’t panic. I’m just proving a point. If JPEG
is so great, how come you can’t make parts
of your images transparent like I can? With
transparency, what is underneath the image
shows through. If my users want a logo on
a Web page, and the page has a colored
background, they’ll use me because they know

I’ll let the background show through the parts
of the logo without any color.

I think you make way too much of this
transparency thing – I say, just build that
background color into the image.

Sure, and then someone changes the Web page
color. No way. Transparency is the way to go,
and to get it, you gotta use me.

Well, I’m not too worried about it; there aren’t
many photos without backgrounds.

Oh yeah? How about if you want to cut out a
picture of a person, or even a tree, and use it
on a Web page without a background?

When would that ever happen?

You’d be surprised how often I get to represent
photos just because my users want that
transparent background.

Yeah, right. Stick to your logos and simple text
images, and I’ll stick to photos and complex
images. Everyone knows I’m better for
handling complexity.

Hey, someone is asking me to do transparency...

gotta run.

you are here �

171

when to use gif or jpeg
n
d
d
d

WHICH

?

Image Format?

Congratulations: you’ve been elected “Grand Image Format Chooser” of the day.

For each image below, choose the format that would best represent it for the Web.

JPEG or GIF

® ®

® ®

® ®

® ®

® ®

172

Chapter 5

adding images to your web pages

Uh, I don’t mean to be
rude, but we’re on the ninth

<img> page of the IMAGES chapter and
you STILL haven’t introduced me!

JPEG, GIF, blah, blah, blah... could
you get on with it?

And now for the formal introduction: meet the

<img> element.

We’ve held off on the introductions long enough. As you can see, there’s more to dealing with images than just the HTML markup.

Anyway, enough of that for now... it’s time to meet the <img> element.

Let’s start by taking a closer look at the element (although you’ve probably already picked up on most of how <img> works by now):

The <img> element is an inline
element. It doesn’t cause linebreaks
to be inserted before or after it.

Here’s the <img> element.

<img src=”images/drinks.gif”>

The src attribute specifies the location You already know
of an image file to be included in the

<img> is an empty
display of the Web page.

element.

So, is that it? Not quite. There are a couple of attributes you’ll want to know about. And of course you’ll also want to know how to use the <img> element to reference images on the Web that aren’t on your own site. But really, you already know the basics of using the <img> element.

Let’s work through a few of the finer points of using the <img> element, and then put all this knowledge to work.

you are here �

173

using urls with images

<img>: it’s not just relative links anymore

The src attribute can be used for more than just relative links; you can also put a URL
in your src attribute. Images are stored on Web servers right alongside HTML pages, so every image on the Web has its own URL, just like Web pages do.

You’ll generally want to use a URL for an image if you’re pointing to an image at a different Web site (remember, for links and images on the same site, it’s better to use relative paths).

Here’s how you link to an image using a URL:

<img src=”http://www.starbuzzcoffee.com/images/corporate/ceo.jpg”> To include an image using its URL,

The URL is the path to the image,
just put the whole URL of the
so the filename at the end is always
image in the src attribute.

the filename of an image. There’s
no such thing as a default image
like there is for Web pages.

Sharpen your pencil

Here’s a “Sharpen your pencil” that is actually about pencils (oh, and images too). This exercise involves a bit of trivia: Given a typical, brand-new pencil, if you drew one continuous line with it, using the entire pencil up, how long would the line be?

What’s that got to do with images? To find the answer you’re going to have to write some HTML. The answer to this trivia is contained in the image that is at the URL: http://www.headfirstlabs.com/trivia/pencil.gif. Your job is to add an image to this HTML and retrieve the answer:

<html>

<head>

<title>Sharpen your pencil trivia</title>

</head>

<body>

<p>How long a line can you draw with the typical pencil?</p>

<p>

</p>

Put your image element here.

</body>

</html>

174

Chapter 5
adding images to your web pages
there are no

Dumb Questions

Q: So the <img> element is quite Q: Back in the example of a Web simple – it just provides a way to specify
page loading with images. . when I load a

Q:

the location of the image that needs to be

What makes a JPEG photo better

Web page, I don’t see the images loading
displayed in the page?

than a GIF photo, or a GIF logo better
one after the other. Why?

than a JPEG logo?

A: Yes, that about sums it up. We’l talk A: Browsers often retrieve the images A: about a couple of at ributes you can add to

“Bet er” is usual y defined as some
concurrently. That is, the browser makes
the element. Later, you’l see a number of
combination of image quality and file size.

requests for multiple images at the same
ways to use CSS to change the visual style

A JPEG photo wil usual y be much smal er
time. Given the speed of computers and
of an image.

than an equivalent quality GIF, while a GIF
networks, this al happens fast enough that
logo will usually look better, and have a

But there’s a lot to know about the images
you usual y see a page display along with
smaller file size than in JPEG format.

themselves. What are the different image
its images.

formats for? When should I use one over the

Q:

other? How big should they be? How do I

Q:

I’ve heard about the PNG image
prepare images for use in a Web page?

If I see an image on a Web page,
format too. Why didn’t you mention that?

how do I determine its URL so that I can

Q:

link to it?

We’ve learned that empty

A: PNG is the latest newcomer in
elements are elements without content.

A:

graphic formats, and an interesting one as

We’ve also learned that the <img>

Most browsers al ow you to
it can support both JPEG and GIF styles
element is empty. But, doesn’t it have

“right-click” on an image, which brings up
of images. It also has more advanced
content (the image)?

a contextual menu with some choices. In
transparency features than GIF. Right now,
these choices you should see “Copy Image

PNG is a lit le on the cut ing edge because

A:

Address” or “Copy Image Link”, which will
not al browsers support it. But its popularity

Wel , to be more precise, an empty
place the URL in your clipboard. Another
is growing quickly. You should feel free to
element is an element that doesn’t have any
way to find the URL is to right-click and
use PNG, but just be aware that it won’t
content in the HTML page to put the open
choose “Open Image in New Window”, which work on every browser.

and closing tags around. True, an image
will open the image in a browser window.

is content, but the <img> element refers to

Then you can get the URL of the image from
the image. The image isn’t part of the HTML
the browser’s address bar. A last option is
page itself. Instead, the image replaces the
to use your browser’s “View Source” menu

<img> element when the browser displays
option and look through the HTML. Keep in
the page. And remember, HTML pages
mind, though, you might find a relative link to
are purely text, so the image could never
the image, so you’l have to “reconstruct” the
be directly part of the page. It’s always a

URL using the Web site domain name and
separate thing.

the path of the image.

you are here �

175

use the alt attribute for accessibility

Always provide an alternative

One thing you can be sure of on the Web is that you never know exactly which browsers and devices will be used to view your pages. Visitors are likely to show up with mobile devices, screen readers for the visually impaired, browsers that are running over very slow Internet connections (and may retrieve only the text, not the images, of a site), cell phones, Internet-enabled toasters... Who knows?

But in the middle of all this uncertainty you can be prepared. Even if a browser can’t display the images on your page, there is an alternative. You can give the visitor some indication of what information is in the image using the <img> element’s alt attribute. Here’s how it works:

<img src=”http://www.headfirstlabs.com/trivia/pencil.gif”

alt=”Pencil line 35 miles long”>

If the image can’t be displayed, then

The alt attribute just requires a short bit
this text is used in its place.

of text that describes the image.

In this exercise you’re going to see how your browser handles the alt attribute when you have a broken image. The theory goes that if an image can’t be found, the alt Exercise
attribute is displayed instead. But not all browsers implement this, so your results may vary. Here’s what you need to do:

1

Take your HTML from the previous exercise.

Update the image element to include the alt attribute

2

“Pencil line 35 miles long”.

3

Change the image name of “pencil.gif” to “broken.gif”. This image doesn’t actually exist, so you’ll get a broken image.

4

Reload the page in your browser.

5

Finally, download a couple of other browsers and give this
a try. Did you get different results?

For instance, you could try Firefox

(http://www.mozilla.org/) or Opera

(http://www.opera.com/).

Look at the end of the chapter to see our results...

176

Chapter 5
adding images to your web pages

Sizing up your images

There’s one last attribute of the <img> element you should know about –
actually, they’re a pair of attributes: width and height. You can use these attributes to tell the browser, up front, the size of an image in your page.

Here’s how you use width and height:

<img src=”images/drinks.gif” width=”48” height=”100”> The width attribute tells the

The height attribute
browser how wide the image
tells the browser how
should appear in the page.

tall the image should
appear in the page.

Both width and height are specified using the number of pixels. If you’re not familiar with pixels, we’ll go into what they are in a little more detail later in this chapter. You can add width and height attributes to any image; if you don’t, the browser will automatically determine the size of the image before displaying it in the page.

there are no

Dumb Questions

Q:

Why would I ever use these
to fit those dimensions. Many people do

Q: We’ve said many times that we
attributes if the browser just figures it
this when they need to display an existing
are supposed to use HTML for structure,
out anyway?

image at a size that is larger or smal er than
its original dimensions. As you’l see later,
and not for presentation. These feel like
presentation attributes. Am I wrong?

A:

however, there are many reasons not to use

On many browsers, if you supply
width and height for this purpose.

the width and height in your HTML, then

A: It depends on how you are using
the browser can get a head start laying

Q: Do I have to use these attributes these atributes. If you’re seting the image out the page before displaying it. If you
in pairs? Can I just specify a width or a
width and height to the correct dimensions,
don’t, the browser often has to readjust the
height?

then it is real y just informational. However,
page layout after it knows the size of an
if you are using the width and height to
image. Remember, the browser downloads
resize the image in the browser, then you
images after it downloads the HTML file and A: You can, but if you’re going to go to are using these at ributes for presentation.

begins to display the page. The browser
the trouble to tel the browser one dimension, In that case, it’s probably bet er to consider can’t know the size of the images before it
supplying the second dimension is about the using CSS to achieve the same result.

downloads them unless you tell it.

same amount of work (and there isn’t a lot

You can also supply width and height values
to be gained by supplying just a width or a
that are larger or smal er than the size of the height unless you’re scaling the image to a image and the browser wil scale the image
particular width or height).

you are here �

177

a fan site for ipods

Creating the ultimate
fan site: myPod
iPod owners love their iPods, and they take them
everywhere. Imagine creating a new site called “myPod”

to display pictures of your friends and their iPods from
their favorite locations, all around the world.

What do you need to get started? Just some knowledge
of HTML, some images, and a love for your iPod.

We’ve already written some of the HTML for this site,
but we haven’t added the images yet – that’s where
you come in. But before you get to the images, let’s
get things set up; look for the “chapter5” folder in the
sample source for the book. There you’ll find a folder
named “mypod”. Open the “mypod” folder and here’s
what you’ll see inside:

My iPod in Seattle! You can see rain clouds
and the Space Needle. You can’t see the 628
coffee shops.

You’ll find this in the
chapter5 folder.

We’ve already written some
of the HTML for the
myPod site. You’ll find it
in the “index.html” file.

<html>
mypod

.

.

.

</html>
index.html

Here’s the first iPod
image:an image of Seattle.

photos
seat le.jpg

We’re going to use the
photos folder to hold

Note: you’ll find a couple of other folders
the images for the site.

in “mypod” too, but ignore those for now.

178

Chapter 5

adding images to your web pages

Check out myPod’s “index.html” file

Open up the file “index.html” and you’ll see work has already begun on myPod. Here’s the HTML so far:

<html>

We threw in some Ready Bake CSS here. Just

<head>
type this in for now - all it does is give

<title> myPod</title>
the page a light green background. We’ll be

<style type=”text/css”>
getting to CSS in a few chapters - promise!

body { background-color: #eaf3da;}

</style>

</head>

<body>

This HTML should look familiar, as we’re using
the basic building blocks: <h1>, <h2>, and <p>.

<h1> Welcome to myPod</h1>

<p>

Welcome to the place to show off your iPod, wherever you might be.

Wanna join the fun? All you need is any iPod from the early classic iPod to the latest iPod Nano, the smallest iPod Shuffle to the largest iPod Photo, and a digital camera. Just take a snapshot of your iPod in your favorite location and we’ll be glad to post it on myPod. So, what are you waiting for?

</p>

<h2> Seattle, Washington</h2>

<p>

Me and my iPod in Seattle! You can see rain clouds and the Space Needle. You can’t see the 628 coffee shops.

</p>

</body>

</html>

And here’s how it looks in
the browser. Not bad, but
we need images.

you are here �

179

inserting an image

Sharpen your pencil

As you can see, a lot of the HTML is already written to
get myPod up and running. All you need to do is add
an <img> element for each photo you want to include.

There’s one photo so far, “seattle.jpg”, so go ahead and
add an element to place that image in the page below.

When you’ve finished, load the page in your browser and
check out the view of Seattle.

We need an
image, right here.

<html>

<head>

<title> myPod</title>

<style type=”text/css”>
body { background-color: #eaf3da;}

</style>

This is where you need to

</head>

<body>
place the first photo.

<h1> Welcome to myPod</h1>

<p>

Welcome to the place to show off your iPod, wherever you might be.

Wanna join the fun? All you need is any iPod from, the early classic iPod to the latest iPod Nano, the smallest iPod Shuffle to the largest iPod Photo, and a digital camera. Just take a snapshot of your iPod in your favorite location and we’ll be glad to post it on myPod. So, what are you waiting for?

</p>

<h2> Seattle, Washington</h2>

<p>

Me and my iPod in Seattle! You can see rain clouds and the Space Needle. You can’t see the 628 coffee shops.

</p>

<p>

Your <img> element is
going to go right here.

</p>

</body>

</html>

180

Chapter 5

adding images to your web pages

Whoa! The image is way too large

Well, the image is right there where it should be, but that is one large image. Then again, most of the images that come from digital If the image fits
cameras these days are that large (or larger). Should we just leave nicely in your
browser window
the image like it is and let visitors use the scroll bar? You’re going to

,
then your browse
see there are a couple of reasons why that’s a bad idea.

r

Watch it! may have an “auto

Let’s take a look at the image and the browser and see just how bad image resize” option
this situation is...

turned on. More on

Here’s our browser. It’s about the
this in just a sec...

size of the typical browser window.

And here’s the “seattle.jpg” image you
added to “index.html.”

Here’s the full size of the image,
which is bigger than the size of the
browser window... much bigger.

We could use the scroll
bars to see the rest of
the image, but wouldn’t
it be better if we could
fit this image into the
browser window?

The browser
window is about

800 pixels wide.

The image is 1200 pixels wide.

you are here �

181

all about image sizes
there are no

Dumb Questions

Q: What’s wrong with having the user just use the scroll bar to see the image?

And, while screen sizes and resolutions tend to vary (some people have smal monitors, some large), 800 pixels is the typical width that A:

most people set their browsers to. So, 800 pixels is a good rule of In general, Web pages with large images are hard to use.

thumb for the maximum width of your images (and your Web pages Not only can your visitors not see the entire image at once, but using too, but we’ll get to that in a later chapter).

scroll bars is cumbersome. Large images also require more data to be transferred between the server and your browser, which takes Q:

a lot of time and may result in your page being very slow to display, How do the number of pixels relate to the size of the
particularly for users on dialup or other slow connections.

image on the screen?

Q:

A:

Why can’t I just use the width and height attribute to

A good rule of thumb is 72 pixels to every inch, although
resize the images on the page?

depending on your monitor, you can have up to 120 pixels in an inch.

Assuming your monitor has 72 pixels per inch, if you want an image A:

to be approximately 3” wide and high, you’d make it 72 (pixels) times Because the browser stil has to retrieve the entire large

3 (inches) = 246 pixels, or, rounding up, 250 by 250 pixels.

image before it scales it down to fit your page.

Q:

Q: Well, how large should I make my images then?

You said the browser window is 800 pixels wide; what
exactly does that mean?

A: In general, you want to keep the width of your image to

A:

less than 800 pixels. Of course, you may want your images to be Your computer’s display is made up of millions of dots called significantly smal er depending on what you’re using the image for.

pixels. If you look very closely at your display you’ll see them: What if the image is a logo for your page? You probably want that smal , but stil readable. After al , you don’t need a logo the width Here’s a lot

Here’s one pixel.

of the entire Web page. Logos tend to run between 100 and 200
of pixels that
pixels wide. So, ultimately, the answer to your question depends on together make up
the design of your page. For photos – which you usual y do want to the upper part of
view as large as possible – you may want to have a page of small the right wing of
thumbnail images that load quickly, and then al ow the user to click the butterfly.

on each thumbnail to see a larger version of the image. We’l get to all that shortly.

Q: I think my browser automaticaly resized the image of

Seattle, because it fits perfectly in the window. Why did my browser do this?

A: Some browsers have a feature that resizes any image that doesn’t fit within the width of your browser. But many browsers don’t do this, so you don’t want to rely on it. Even if every browser did have this feature, you’d stil be transferring a lot more data than This image is made up
necessary between the server and browser, which would make your of thousands of pixels
page slow to load and less usable.

when it’s displayed on a
computer screen.

182

Chapter 5

adding images to your web pages

Resize the image to fit in the browser

Let’s fix up this image so it fits the browser page better. Right now this image is 1200 pixels wide by 800 pixels tall (you’ll see how to determine that in a sec).

Because we want the width of the image to be less than 800 pixels, we need to decide on a width that would fit our myPod Web page nicely. The whole point of myPod is viewing photos of iPods in their surroundings, so we probably want to have reasonably large images. If we reduce this image size by one half to 600 pixels wide by 400 pixels high, that will still take up most of the browser width, while still allowing for a little space on the sides. Sound good?

Let’s get this image resized...

1200 pixels

We need to resize the
image so that it’s still
reasonably large, but
is less than 800 pixels
wide. 600 seems like a

600 pixels
nice width that happens

800
to be one half the
pixels
current size.

400
pixels

Here’s what you’re going to do:

1 Open the image using a photo editing application.

2

Reduce the image size by one half (to 600 pixels by 400 pixels).

3 Save the image as “seattle_med.jpg”.

you are here �

183

choosing a photo editor

Before we get
started, which photo editing
application are we going to
use to resize the image? I
have Photoshop Elements. Will
that work?

Good question – there are lots of photo editing
applications on the market (some freely available),
which are all quite similar. We’re going to use

Adobe’s Photoshop Elements to resize the images,
because it is one of the most popular photo
editing applications, and is available on both

Windows and the Macintosh. If you own another
photo editing application, you should have no
problem following along and translating each
editing task to your own application.

If you don’t yet have a photo editing application,
you might first check to see if there was one
included with your operating system. If you have
a Mac, you can use iPhoto to edit your photos. If
you’re a Windows user, you might find Microsoft’s

Digital Image Suite on your computer already.

If you still don’t have an editing application
available to you, follow along and and for each
step you can use the HTML and images included
in the example folders.

If you don’t have Adobe Phot
you’d like t
oshop Elements, but
o follow along f
chapter wi
or the r
th i
est of the
t, you can download i
out free for 30 days. T
t and try it
he URL t
http://www.adobe.com/produc
o download it is:

ts/tryadobe/main.jsp

184

Chapter 5

adding images to your web pages

Open the image

First, start your photo editing application and open the “seattle.jpg”

image. In Photoshop Elements, you’ll want to choose the “Browse Folders...” menu option under the “File” menu, which will open Or, if you’re using Windows, use
the “File Browser” dialog box. You’re going to use this to navigate the File > Open menu to open
to the image “seattle.jpg” in the “chapter5/mypod/photos” folder.

the “seattle.jpg” image directly.

Here’s the File Browser

As you navigate through folders, you’ll see a
dialog box. Use this
preview of the images in those folders here.

dialog to navigate to the

“seattle.jpg” image.

When you’ve located the “seattle.jpg”

image, double-click it to open.

Single clicking the preview
image shows you a larger
preview of the image.

you are here �

185

resizing an image

Resizing the image

Now that “seattle.jpg” is open, we’re going to use the “Save for Web” dialog to both resize the image and save it. To get to that dialog box, just choose the

“Save for Web” menu option from the “File” menu.

To resize the image, choose “Save
for Web” from the File menu.

Here’s the “seattle.jpg” image
in Photoshop Elements.

186

Chapter 5

adding images to your web pages

Resizing the image, continued...

After you’ve selected the “Save for Web” menu option, you should see the dialog box below; let’s get acquainted with it before we use it.

This dialog lets you do all kinds of interesting things. For now, we’re going to focus on how to use it to resize and save images in JPEG format for Web pages.

Here’s where you choose the format to
save your file. Currently it’s set to save
as GIF; we’re going to change this to

JPEG in a couple of pages...

Here’s the
current size
of the image:

1200 pixels by

800 pixels.

This split window shows you your original image on the left, and the image in the format you’re saving it for the Web on the right. Currently this is showing “GIF” format; we’ll be changing this to JPEG in an upcoming step.

you are here �

187

using save for web

As you can see, there’s a lot of functionality built into this dialog. Let’s put it to good use. To resize the image, you
need to change the width to 600 pixels and the height
to 400 pixels. Then you need to save the image in JPEG

(1) Change the image size here
format. Let’s start with the resize...

to a width of 600 and a height
of 400. If you have “Constrain

Proportions” checked, then all you
have to do is type the new width,

600, and Elements will change the
height to 400 for you.

(2) Once the width and
height are set correctly,
click “Apply” to let

Elements know this is
the size you want.

This will not affect the original image,
just the file you’re going to save.

You must click Apply to reduce the image size; otherwise,
the image will be saved at its original width and height.

188

Chapter 5

adding images to your web pages

You’ve resized - now save

Now you just need to save the image in the correct format

(JPEG). To do that, you need to choose JPEG format and set
the quality to “Medium”. We’ll talk more about quality in a sec.

(1) Now that the image size is set, you just
need to choose the format for the image.

Currently it’s set to save as GIF; change this
to JPEG like we’ve done here.

(2) Set the quality to “Medium”.

(3) That’s it;
click “OK” and
go to the next
page.

Notice that when you clicked “Apply”

in the previous step, the image was
resized and redisplayed.

you are here �

189

image saving and quality

Save the image

After you click OK, you’ll get a Save dialog. Save the image as

“seattle_med.jpg” so you don’t overwrite the original photo.

Change the filename to seattle_med.jpg.

Make sure you’re
saving the image in the

“mypod/photos” folder.

Click “Save” to save

Notice that you’re changing the filename from “seattle.jpg”

the image.

to “seattle_med.jpg”. Why? People usually like to save their original, high-quality, big photos for printing, and put smaller versions on the Web. If you saved this as “seattle.jpg”, you’d be losing the original photo!

there are no

Dumb Questions

Q: Can you say more about the The best way to get a feel for quality Q: Couldn’t I just use the <img>
quality setting in “Save for Web”?

settings and the various image formats is to
element’s width and height attributes to
experiment with them on your own images.

resize my image instead?

A:

You’l soon figure out what quality levels

The JPEG format al ows you to
are needed for your image and the type of
specify the level of image quality you need.

Web page you’re developing. You’l also get A: You could use the width and height The lower the quality, the smal er the file
to know when to use JPEG versus other
attributes to resize an image, but that’s
size. If you look at the preview pane in the
formats.

not a good idea. Why? Because if you do

“Save for Web” dialog you can see both the
that, you’re still downloading the full-size
quality and file size change as you change

Q:

image, and making the browser do the
the quality settings.

What is the number 30 next to the
work to resize the image (just like when you

Quality label in the JPEG Options dialog
have the auto resize option on in browsers

Image format.

box?

that support that feature). The width and

Image size (1K equals

1024 bytes in size). A:

height at ributes are real y there to help
the browser figure out how much space to

30 is a number that Photoshop
reserve for the image; if you use them, they

Elements considers “Medium” quality. JPEG should match the actual width and height of Photoshop Elements even
actual y uses a scale of 1-100%, and Low,
the image.

tells you how long it would

Medium, High, etc. are just preset values
take to transfer over a
that many photo editing applications use.

dialup modem to a browser.

190

Chapter 5

adding images to your web pages

Fixing up the myPod HTML

Once you’ve saved the image, you can quit out of Photoshop Elements. Now all you need to do is change the myPod “index.html” page to include the new version of the photo, “seattle_med.jpg”.

Here’s a snippet of the “index.html” file, showing only the parts you need to change.

<html>

<head>

<title> myPod</title>

<style type=”text/css”>
body { background-color: #eaf3da;}

</style>

The rest of the HTML goes here. You’ve

</head>

<body>
already got it in your “index.html” file.

.

All you need to do is change the

.

filename in the <img> element to

.

the name of the image you just

<h2> Seattle, Washington</h2>
made: “seattle_med.jpg”.

<p>

Me and my iPod in Seattle! You can see rain clouds and the Space Needle. You can’t see the 628 coffee shops.

</p>

<p>

<img src=”photos/seattle_med.jpg” alt=”My iPod in Seattle, WA”>

</p>

</body>

</html>

And now for the test drive...

Go ahead and make the changes, save them, and
reload “index.html” in your browser. Things
should look much better. Now the image is sized
just right to give your visitors a good view – without
overwhelming them with a large photo.

Now the image fits nicely in the browser window.

you are here �

191

comparing image settings
d
n
d
d

2

WHICH

Your task this time: open the file “c

?

Image Format?

hapter5/testimage/eye.jpg” in Photoshop Elements. Open the “Save for Web” dialog and fill in the blanks below by choosing each quality setting for JPEG (low, medium, high, etc.).

You’ll find this information in the preview pane below the image. Once you’ve finished, determine which setting makes the most sense for this image.

Format.

Size of image.

Time to transfer over
dialup modem.

Format Quality Size Time Winner

JPEG

Maximum

®

JPEG

Very High

®

JPEG

High

®

JPEG

Medium

®

JPEG

Low

®

GIF

N/A

®

192

Chapter 5
adding images to your web pages

More photos for myPod

A new batch of photos has arrived for myPod: two more from Seattle and a few from a friend in Britain. The photos have already been resized to less than 800 pixels wide. Add the <img> elements for them (you’ll find the images already in the photos folder):

<html>

<head>

Feel free to add some of your

<title> myPod</title>
own photos her

<style type=”text/css”>
e as well. Just
remember to resize them first.

body { background-color: #eaf3da;}

</style>

</head>

<body>

<h1>Welcome to myPod</h1>

<p>

Welcome to the place to show off your iPod, wherever you might be.

Wanna join the fun? All you need is any iPod, from the early classic iPod to the latest iPod Nano, the smallest iPod Shuffle to the largest iPod Photo, and a digital camera. Just take a snapshot of your iPod in your favorite location and we’ll be glad to post it on myPod. So, what are you waiting for?

</p>

<h2> Seattle, Washington</h2>

<p>

Let’s keep all the

Me and my iPod in Seattle! You can see rain clouds and the Seattle photos together.

Space Needle. You can’t see the 628 coffee shops.

</p>

<p>

<img src=”photos/seattle_med.jpg” alt=”My iPod in Seattle, WA”>

<img src=”photos/seattle_shuffle.jpg” alt=”An iPod Shuffle in Seattle, WA”>

<img src=”photos/seattle_downtown.jpg” alt=”An iPod in downtown Seattle, WA”>

</p>

Same with the

<h2> Birmingham, England</h2>

Birmingham photos...

<p>

Here are some iPod photos around Birmingham. We’ve obviously got some passionate folks over here who love their iPods. Check out the classic red British telephone box!

</p>

<p>

<img src=”photos/britain.jpg” alt=”An iPod in Birmingham at a telephone box”>

<img src=”photos/applestore.jpg” alt=”An iPod at the Birmingham Apple store”>

</p>

</body>

</html>
you are here �

193

viewing mypod with resized images

Taking myPod for another test drive

At this point we don’t need to tell you to reload the page
in your browser; we’re sure you’re way ahead of us. Wow,
what a difference a few images make, don’t you think?

This page is starting to look downright interesting.

But that doesn’t mean you’re there yet. While you’ve got
a great set of images on the page, and even though you’ve
already resized them, the images are still quite large. Not only is the page going to load more and more slowly as
you add more images, but the user has to do a lot of
scrolling to see them all. Wouldn’t it be better if users

Here’s what
could see a small “thumbnail” image for each photo, and
the whole page
then click on the thumbnail to see the larger image?

looks like now,
with all the

And, here’s what the page
images.

looks like now, close up.

194

Chapter 5

adding images to your web pages

Reworking the site to use thumbnails

You’re now going to make this page more usable by substituting a smaller image (which we’ll call a thumbnail) for each photo, and then you’ll create a link from that thumbnail to each of the larger photos.

Here’s how you’re going to do this, one step at a time:

1 Create a new directory for the thumbnails.

2 Resize each photo to 150 by 100 pixels and save it in a

“thumbnail” folder.

3 Set the src of each <img> element in “index.html”

to the thumbnail version of the photo.

4 Add a link from each thumbnail to a new page
containing the larger photo.

Create a new directory for thumbnails

To keep things organized, create a separate folder for the thumbnail images. Otherwise, you’ll end up with a folder of larger images and small thumbnails all lumped together, which could get quite cluttered after you’ve added a significant number of photos.

Create a folder called “thumbnails” under the “mypod” folder. If you’re working from the book example files, you’ll find this folder already in there.

<html>
mypod

.

.

.

</html>
index.html
photos
thumbnails

Create a new folder
called “thumbnails” in
the “mypod” folder.

you are here �

195

using thumbnail images

Create the thumbnails

You’ve got a place to put your thumbnails, so let’s create them. Start by opening “seattle_med.jpg” with your photo editing application. You’re going to resize it to 150x100 pixels using the same method you used to create the 600x400 version:

Then change the width

In Photoshop Elements,
to 150 and the height to Don’t forget to change the
choose the “Save for Web”

100 and click “Apply”.

format to JPEG, Medium quality.

Finally,
menu option.

click OK.

With the image resized, choose “OK” and save it as the same name If you’re working with the example
but in the thumbnail folder. Be careful: if you save it to the “photos”

files, you’ll find the thumbnails
folder you’ll be replacing the larger image.

already in the “thumbnails” folder

Now, repeat this for each photo in your “photos” folder.

so you don’t have to do every one

(after all, you’re learning HTML,
not batch photo processing).

What about
the photos from

Birmingham – they are
tal er than they are wide.

Does 150x100 make sense?

Good catch. Because these images are taller
than they are wide, we have two choices: we can
switch the dimensions and make them 100x150
or we can crop each image and make a 150x100
pixel thumbnail from it. We’re going to make
ours 100x150; feel free to crop them and create

150x100 pixel images if you’d like to explore how
to do that in your photo editing application.

196

Chapter 5
adding images to your web pages

Rework the HTML to use the thumbnails

Now you just need to change the HTML so that the <img> elements get their images from the “thumbnails” folder rather than the “photos” folder. And, because you’re currently using relative paths like “photos/seattle_med.jpg”, that’s going to be simple: for each

<img> element, all you need to do is change the folder from “photos” to “thumbnails”.

<html>

<head>

<title> myPod</title>

<style type=”text/css”>
body { background-color: #eaf3da;}

</style>

</head>

<body>

<h1>Welcome to myPod</h1>

<p>

Welcome to the place to show off your iPod, wherever you might be.

Wanna join the fun? All you need is any iPod, from the early classic iPod to the latest iPod Nano, the smallest iPod Shuffle to the largest iPod Photo, and a digital camera. Just take a snapshot of your iPod in your favorite location and we’ll be glad to post it on myPod. So, what are you waiting for?

</p>

All you need to do is change the
folder from “photos” to “thumbnails”.

<h2> Seattle, Washington</h2>

<p>

Me and my iPod in Seattle! You can see rain clouds and the Space Needle. You can’t see the 628 coffee shops.

</p>

<p>

<img src=”thumbnails/seattle_med.jpg” alt=”My iPod in Seattle, WA”>

<img src=”thumbnails/seattle_shuffle.jpg” alt=”A iPod Shuffle in Seattle, WA”>

<img src=”thumbnails/seattle_downtown.jpg” alt=”An iPod in downtown Seattle, WA”>

</p>

<h2> Birmingham, England</h2>

<p>

Here are some iPod photos around Birmingham. We’ve obviously got some passionate folks over here who love their iPods. Check out the classic red British telephone box!

</p>

<p>

<img src=”thumbnails/britain.jpg” alt=”An iPod in Birmingham at a telephone box”>

<img src=”thumbnails/applestore.jpg” alt=”An iPod at the Birmingham Apple store”>

</p>

</body>

</html>
you are here �

197

images and layout

Take myPod for another test drive

Ahhh... much better. Visitors can see all the
available pictures at a glance. They can also tell
which photos go with each city more easily. Now we
need to find a way to link from each thumbnail to
the corresponding large image.

Wait a sec, don’t
you think you’re
pul ing a fast one? The
images used to be on top
of each other; now
they’re side by side.

Right; but remember the <img> element
is an inline element.

In other words, we didn’t “pull anything.” Because <img> is an inline element, it doesn’t cause linebreaks to be
inserted before and after the element is displayed. So, if
there are several images together in your HTML, the
browser will fit them side by side if the browser window is wide enough.

The reason the larger photos weren’t side by side is
because the browser didn’t have room to display them
next to each other. Instead, it displayed them on top
of each other. A browser always displays vertical space
before and after a block element, and if you look back at
the screenshots, you’ll see the images are right on top of
each other with no space in between. That’s another sign

<img> is an inline element.

198

Chapter 5

adding images to your web pages

Turning the thumbnails into links

You’re almost there. Now you just need to create a link from each thumbnail image to its larger version. Here’s how this is going to work: A visitor sees a thumbnail they like,
say the downtown iPod thumbnail...

...the visitor clicks
on the thumbnail...

...the browser retrieves
a new page with the
large image...

Click

...and displays it.

The visitor can click
the back button
to get back to the
myPod page.

To do this you need two things:

1

A page to display each photo along with a
heading that describes its content.

2

A link from each thumbnail in “index.html”

to its corresponding photo page.

Let’s create the pages first, and then we’ll come back and
finish off the links.

you are here �

199

adding individual image pages

Create individual pages for the photos

First, create a new folder called “html” to hold these individual pages, just below the “mypod” folder:

<html>
mypod

.

.

.

</html>
index.html
photos
thumbnails
html

As you’ve probably
guessed, we’ve already
created this folder for
you in the book examples.

Now we’re going to create one HTML file for each photo. If the photo is called

“seattle_med.jpg”, then let’s call the HTML file “seattle_med.html” just to be consistent. In each HTML file, we’ll have a heading that describes the photo, followed by the photo. Here’s the HTML for the first Seattle photo. All the other pages will follow this same format:

Title for the page. This

Here’s our ready bake CSS
should describe the photo.

again, just to keep the page

<html>
a consistent color.

<head>

<title> myPod: Seattle Ferry</title>

<style type=”text/css”> body { background-color: #eaf3da; } </style>

</head>

Here we give the page a descriptive heading.

<body>

<h1> Seattle Ferry</h1>

<p>

<img src=”../photos/seattle_med.jpg” alt=”An iPod on the Seattle ferry”>

</p>

</body>

Here’s the <img> element that points to the large

</html>

“seattle_med.jpg” photo. Let’s also give the image
a descriptive alt attribute.

Notice that we need to use “..” in the relative path
because the “html” folder is a sibling of the “photos”

folder, so we have to go up one folder and then down
into “photos” when using relative links.

200

Chapter 5

adding images to your web pages

Exercise

If you look in the “html” folder in the chapter example files, you’l find al of the single photo pages already there, except one – the page for

“seat le_downtown.jpg”. Create a page cal ed “seat le_downtown.html” in the “html” folder, and test it out. Get this working before you move on.

You’l find the answer in the back of the chapter if you have any problems.

So, how do I make links out of images?

You’ve got your large photos, your smaller thumbnails, and even a set of HTML pages for displaying individual photos. Now you need to put it all together and get those thumbnails in “index.html” linked to the pages in the

“html” folder. But how?

To link an image, you put the <img> element inside an <a> element, like this: The href is linked to the new

And here’s an <a>

HTML page for the photo,
opening tag just before

“seattle_downtown.html”, which
the <img> element.

is in the “html” directory.

Here’s the <img> element for

the “seattle_downtown.jpg”

<a href=”html/seattle_downtown.html”>
thumbnail, just as it is in the

<img src=”thumbnails/seattle_downtown.jpg”

“index.html” file.

alt=”An iPod in downtown Seattle, WA”>

</a>

Here’s the

The <img> element is nested
closing <a> tag.

directly inside the <a> element.

Once you’ve placed the <img> element into an <a> element, the browser treats the image as a clickable link. When you click the image, the browser will retrieve the page in the href.

you are here �

201
adding links to images

Add the image links to “index.html”

This is the last step. You just need to wrap <a> elements around each thumbnail’s <img> element in your “index.html” file. Remember, the href of each <a> element should link to the page containing the large version of the image in the “html” folder. Make sure that your links, thumbnails, and pages all match up correctly.

Here’s the complete “index.html” file. All you need to do is add the HTML marked in gray.

<html>

<head>

<title> myPod</title>

<style type=”text/css”>
body { background-color: #eaf3da;}

</style>

</head>

<body>

<h1>Welcome to myPod</h1>

<p>

Welcome to the place to show off your iPod, wherever you might be.

Wanna join the fun? All you need is any iPod, from the early classic iPod to the latest iPod Nano, the smallest iPod Shuffle to the largest iPod Photo, and a digital camera. Just take a snapshot of your iPod in your favorite location and we’ll be glad to post it on myPod. So, what are you waiting for?

</p>

<h2> Seattle, Washington</h2>

<p>

Me and my iPod in Seattle! You can see rain clouds and the Space Needle. You can’t see the 628 coffee shops.

</p>

<p>

<a href=”html/seattle_med.html”>

<img src=”thumbnails/seattle_med.jpg” alt=”My iPod in Seattle, WA”>

</a>

<a href=”html/seattle_shuffle.html”>

<img src=”thumbnails/seattle_shuffle.jpg” alt=”A iPod Shuffle in Seattle, WA”>

</a>

<a href=”html/seattle_downtown.html”>

<img src=”thumbnails/seattle_downtown.jpg” alt=”An iPod in downtown Seattle, WA”>

</a>

</p>

<h2> Birmingham, England</h2>

<p>

Here are some iPod photos around Birmingham. We’ve obviously got some 202

Chapter 5
adding images to your web pages
passionate folks over here who love their iPods. Check out the classic red British telephone box!

</p>

<p>

<a href=”html/britain.html”>

<img src=”thumbnails/britain.jpg” alt=”An iPod in Birmingham at a telephone box”>

</a>

<a href=”html/applestore.html”>

<img src=”thumbnails/applestore.jpg” alt=”An iPod at the Birmingham Apple store”>

</a>

</p>

</body>

</html>

For each thumbnail image, wrap an <a> element around it.

Just be careful to get the right href in each link!

Add these <a> elements to your “index.html” file.

Save, load into your browser and check out myPod!

there are no

Dumb Questions

Q: When we put an <a> element around text we get Q: Can’t we just link to the JPEG image directly without an underline. Why don’t we get something equivalent with all those HTML pages? I thought the browser was smart
images?

enough to display images by themselves.

A: Actualy, most browsers DO put a border around an image A: You’re right, you could link directly to the image, like this: to show it is linked. (Our browser, Safari, is one of the few that

<a href=“photos/seat le_downtown.jpg”> . . </a>. If you did that don’t.) If your browser puts a border around your linked images, and clicked on the link, the browser would display the image and you don’t like it, hold on a few more chapters and you’ll by itself on a blank page. In general though, linking directly to learn how to take that border off with CSS. Also notice that when an image is considered bad form, because you usual y want to you pass your mouse over an image, your cursor will change to provide some context for the images you are displaying.

indicate you can click on the linked image. In most cases your users wil know an image is linked by context and by the mouse cursor, even if there’s no border.

you are here �

203

adding a logo

The myPod Web page is
looking awesome! I think
you should add a logo to the
page - that would add a
great finishing touch.

Great idea. In fact, we’ve got a myPod
logo all ready to go.

Take another look in the folder

“chapter5/mypod”, and you’ll find a
folder called “logo”. In that folder
you’ll find a file called “mypod.psd”.

The “.psd” means that the file has
been saved in the Photoshop format, a
common format for digital images. But

Photoshop format files are meant for
processing digital images, not for Web
pages, so we’ll have to do some work to
get a “Web ready” image from it.

Many photo editing applications
understand .psd files, so even
if you don’t have Photoshop

Elements, follow along for
the next few pages. If your
application can’t open the “.psd”

file, you’ll find the images from
each step in the “logo” folder.

204

Chapter 5

adding images to your web pages

Open the myPod logo

Let’s check out the myPod logo: open up the file “mypod.psd”

in the “chapter5/mypod/logo” folder in Photoshop Elements:

If your photo editing
application won’t open
the file, follow along
anyway - the same
principles apply for
other formats as well.

You’ll find the “logo” folder in
the “chapter5/mypod” folder.

A closer look...

Nice logo; it’s got some typography combined with two circles, one gray and one white (obviously inspired by the click-wheel controls on the iPod).

But what is that checkered pattern in the background? That’s the way most photo editing applications show you areas that are transparent. Keep all that in mind as we choose a graphic format for the logo...

Whenever you see this
checkered pattern,
that indicates a
transparent area in
the image.

you are here �

205

choosing between gif and jpeg

What format should we use?

You already know that we have a couple of options in deciding how to save this image: we could use JPEG or GIF. This logo uses only three colors, text, and some geometric shapes. From what you’ve learned about the two formats, you’re probably leaning towards GIF (good choice!).

So, go ahead and choose GIF in the format drop down, and you’ll see we have a few more options. Let’s take a look...

Remember, use this
pulldown menu to set the
format. We’re going to
set the format to GIF to

Here’s where Photoshop
save the logo.

Elements shows you the
number of colors being
used to save the GIF.

It’s already set to the
maximum, 256. We’ll
leave it there.

When you set the
format to GIF, this

Transparency checkbox
appears. By default,
it’s checked. Do we
want a transparent
background?

Also note the

Matte option.

This is related to
transparency, as
you’ll see in a sec.

Try unchecking the Transparency checkbox:

you’ll see the GIF preview at the bottom
change to a white background.

206

Chapter 5

adding images to your web pages

To be transparent, or not to be transparent?

That is the question...

The myPod logo is going to be placed on a light green
background, so you might think that transparency is going
to be a good thing, right? Well, let’s compare how the logo looks using a few options in the “Save for Web” dialog:

Here’s the logo saved in three different ways and
displayed on a Web page with a green background.

Without transparency things look
pretty bad. Clearly, a white
o work
background isn’t going t
on a green Web page. (It might,
however, work just fine on a
white Web page).

Here’s what we get if we check

Transparency and save. Better...

but what’s that white “halo”

around the letters in the logo?

The halos happen because the
photo editing application creates
a “matte” to soften the text’s
edges against the background
color. When it did that for this
logo, however, it assumed it was
softening the edges against a
white background.

Ah, now we’re talking; this looks great. For this
version we told Photoshop Elements to create the
matte around the text using a green background.

How? We’ll show you next.

you are here �

207

creating a transparent gif

Save the transparent GIF

You know you want a transparent GIF version of the logo,
and you also know we’ll need to use a matte to prevent the
halos around the text. Let’s check out the GIF panel of the

“Save for Web” dialog.

You know to
choose GIF
already.

And check

Now we need to take a look at

Transparency.

the Matte option.

The Matte option allows you to select the color for the matte around the text. And we want that to be the color of the Web page background.

The Matte option
supplies the color for
softening the edges
of the text. Since the

Web page is a light
green, we want to use
the same color for the
matte.

Choose “Other...” since
our color isn’t listed.

208

Chapter 5

adding images to your web pages

Wait, what is the color of the Web page background?

Remember that Ready Bake CSS in the myPod “index.html” file?

That CSS is what sets the background color of the page to light green. And that’s where we can get the color:

<style type=”text/css”>

Here’s the background
body { background-color: #eaf3da;}

color right here.

</style>

What? You can’t tell that’s light
green? For now take our word for
it; we’ll come back to this in a few
chapters and explain all about colors.

Set the matte color

When you click on the Matte pulldown menu and choose the “Other...” menu option, Photoshop Elements will bring up the Color Picker dialog.

The Color Picker gives you a lot
of different ways to choose the
matte color. We just want to set
it to the background of the Web
page, and we already know that
is eaf3da...

... which is going to go right here.

you are here �

209

setting a matte color

Set the matte color, continued

Go ahead and enter the color, “eaf3da”, into the “Color Picker” dialog box.

You’ll see the color change to the background color of the myPod page.

Type these letters in right here.

This box is designed specifically for
colors written in the Web format.

You can type the letters in upper-
or lowercase, it doesn’t matter.

Once you’ve typed the color
into the Color Picker, click

“OK” and it will apply the
change to the logo.

Check out the logo with a matte

Now take a close look at the logo again in the preview pane. You’ll see Photoshop Elements has added a light green matte around the hard edges, which will give the myPod logo text a softer, more polished look when the logo is in the Web page.

Now, when you look close up at the
logo, you’ll see the matte matches the
green color in the background of the

“mypod.html” Web page.

210

Chapter 5

adding images to your web pages

Save the logo

Okay you’ve made all the adjustments you need to in the “Save for Web”

dialog, so go ahead and click “OK” to save the image as “mypod.gif ”.

Elements will automatically
change the extension of your
filename to “.gif”. Save the
image as “mypod.gif” in the

“logo” folder.

Add the logo to the myPod Web page

Now all you need to do is add the logo to the myPod Web page.

We’ll add it to the top so it appears above the Web site description and iPod images. That way, it’s the first thing your visitors see when they come to your myPod page.

<html>

<head>

<title> myPod</title>

Add the logo image at the top of the

<style type=”text/css”>
myPod Web page. Remember to use
body { background-color: #eaf3da;}

the correct relative path for the logo,

</style>
in the “logo” folder, and add an alt

</head>
attribute that describes the image.

<body>

<p>

<img src=”logo/mypod.gif” alt=”myPod Logo”>

</p>

<h1>Welcome to myPod</h1>

.

.

Rest of “index.html” HTML here...

.

</body>

</html>
you are here �

211

testing the transparent gif

And now for the final test drive

Let’s test this puppy! Reload the Web page in the browser and see how your myPod transparent GIF logo works.

And it works - all that
hard work paid off. You
have a great looking logo
on your myPod Web page.

Excellent work. The
logo looks great. You’ve
got a kick-ass myPod

Web site here!

212

Chapter 5

adding images to your web pages
there are no

Dumb Questions

Q: Do I realy need to know al this stuff about Q: So where does the “Matte” come in?

image formats to write good Web pages?

A:

A: The process of anti-aliasing softens the edges

No. You can build great Web pages without any
relative to the background color. If you put the bot om
images. However, images are a big part of the Web, so
version of the logo (from the previous Q&A) against a
some knowledge of how images work can real y help.

colored background, you’d see it has white edges in it. The Sometimes just an image or two makes the dif erence

Mat e option in Photoshop Elements al ows you to specify
between a good page and a great one. There’s a lot to
the color of the background that the text wil be placed on, know about images, but it’s easy to learn as you go.

so when the text is softened it is done so against that color.

Q: Why does the text need its edges softened? Q: Does this technique just work for text?

A: Check out the two versions of the myPod logo

A: No, it works for any lines in your graphics that might
below:

result in “jaggies”. Check out the circle in the myPod logo; it was matted too.

Q: Why can’t I just make the logo background
color solid and match the color to the Web page?

A: You could do that too, but there is one disadvantage:

if there are other things in your Web page that are showing through the transparency, then they won’t be seen with the

You’l see the top version has very hard, jagged edges
solid color version. You haven’t seen any examples of this
and is less readable. This is the way text is displayed by
yet, but when we get into CSS, you will.

default on a computer screen. The second version has had
its edges softened using a technique cal ed anti-aliasing.

Q: What if I change my background color after I

Words that are anti-aliased on a computer screen are more
make the matted version?

readable and more pleasant to the eye.

A: A slight variation in your background color probably
wouldn’t be noticeable; however, if you change the color
dramatical y, you’l have to recreate the GIF with a new
matte color.

you are here �

213

review using images with html

BULLET POINTS

n

Use the <img> element to place images in
n

Images that are too large for the browser
your Web page.

make Web pages difficult to use and slow to
download and display.

n

Browsers treat <img> elements a little
differently than other HTML elements; after
n

A pixel is the smallest dot that can be
reading the HTML page, the browser retrieves
represented on the screen. Each image is
each image from the Web server and displays
composed of thousands of pixels. Depending
it.

on your monitor, there can be anywhere from

72 pixels in an inch to 120 pixels in an inch.

n

If you have more than a couple of large
images on a Web page, you can make
n

JPEG and GIF are the two formats for images
your Web page more usable and faster to
that are widely supported by Web browsers.

download by creating thumbnails – small
images that the user can click on to see the
n

The JPEG format is best for photographs and
large version of the image.

other complex images.

n

The GIF format is best for logos and other

n

The <img> element is an inline element,
which means that the browser doesn’t put a
simple graphics with solid colors, lines, or text.

linebreak before or after an image.

n

JPEG images can be compressed at a variety
of different qualities, so you can choose the

n

The src attribute is how you specify the
location of the image file. You can include
best balance of quality and file size for your
images from your own site using a relative
needs.

path in the src attribute, or images from other
n

The GIF image format allows you to make an
sites using a URL.

image with a transparent background. If you
put an image with a transparent background

n

The alt attribute of an <img> element is a
meaningful description of the image. It is
in a Web page, what’s behind the image, such
displayed in some browsers if the image can’t
as the background color of the page, will show
be located, and is used by screen readers to
through the transparent parts of the image.

describe the image for the visually impaired.

n

In Photoshop Elements, use the Matte color
menu in the “Save for Web” dialog to choose

n

A width of less than 800 pixels is a good
rule of thumb for the size of photo images
the right color for softening the edges of your
in a Web page. Most photo images that are
transparent GIF image.

created by digital cameras are too large for
n

Images can be used as links to other Web

Web pages, so you’ll need to resize them.

pages. To create a link from an image, use
the <img> element as the content of an <a>

n

Photoshop Elements is one of many photo
editing applications you can use to resize your
element, and put the link in the href attribute
images.

of the <a> element.

214

Chapter 5

adding images to your web pages

HTMLcross

It’s time to give your right brain a break and put that left brain to work.

All these words are HTML-related and from this chapter.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

Across

Down

3. Smallest element on a screen.

1. Lovable MP3 player.

5. Web server makes a request for each one of

2. With JPEG you can control this.

these.

4. The larger the image, the _____ it takes to

7. Better for solid colors, lines, and small text.

transfer it.

9. Newcomer image format.

6. GIF has it, JPEG doesn't.

10. Most Web browsers retrieve images this way.

8. Technique for softening edges of text.

11. Miles you can draw with a pencil.

12. Better for photos with continuous tones.

13. Small images on a page.

14. You used Photoshop Elements to do this to
images.

15. The alt attribute improves this.

you are here �

215

exercise solutions

Exercise

Solutions
n
d
d
d

WHICH

?

Image Format?

Congratulations: you’ve been elected “Grand Image Format Chooser” of the day.

For each image below, choose the format that would best represent it on the Web.

JPEG or GIF

A photo with lots of continuous

® ®
shades of gray.

Only a couple of colors with some
text; definitely a GIF.

® ®

A photo with lots of colors;
definitely a JPEG.

® ®

Just a simple black and
white icon; a GIF.

® ®

This image is borderline. It has
lots of continuous colors (JPEG),
but is also slightly geometric

(GIF) and you may want to

® ®
use this in a way that requires
transparency (GIF).

216

Chapter 5

adding images to your web pages

Sharpen your pencil

Solution

Here’s a “Sharpen your pencil” that is actually about pencils (oh, and images of course). This exercise involves a bit of trivia: Given a typical, brand-new pencil, if you drew one continuous line with it, using the entire pencil up, how long would the line be?

What’s that got to do with images? To find the answer you’re going to have to write some HTML. The answer is contained in the image that is at the URL: http://www.headfirstlabs.com/
trivia/pencil.gif. Your job is to add an image to this HTML and retrieve the answer:

<html>

<head>

<title>Sharpen your pencil trivia</title>

</head>

<body>

<p>How long a line can you draw with the typical pencil?</p>

<p>

<img src=”http://www.headfirstlabs.com/trivia/pencil.gif”>

</p>

</body>

</html>

Source: http://www.papermate.com
you are here �

217

exercise solutions

Here are the results of having a broken image in a few different browsers. In most cases, the browser is able to use the extra alt attribute information to improve what is displayed. Why do we care? After all, this is an error in a Web page; we should just Exercise
fix it, right? Wel , in the real world things are often not ideal; sometimes things break, Internet connections go bad in the middle of a page load, or visually impaired users Solutions
need to hear what is in the image, because they can’t see it.

PC

The Firefox browser just displays the alt
attribute, as if it were text, if the image

Internet
can’t be retrieved.

Explorer

Mac
displays a
broken image
icon and the
alt attribute
text next
to it.

Safari on the Mac
doesn’t make good use
of the alt attribute
from broken images.

On the Mac, Internet

Explorer also displays
a broken image icon
and the alt attribute
text next to it.

218

Chapter 5

adding images to your web pages

Exercise
n
d

Solutions
d
d

2

WHICH

?

Image Format?

Format Quality Size Time Winner

Note that your numbers may differ depending on
the version of software you are using.

JPEG

Maximum

232K

83 Seconds ®

Did you notice how

JPEG

Very High

112K

41 Seconds ®
the image quality
degrades?

JPEG

High

64K

24 Seconds ®

30K

JPEG

Medium

12 Seconds ®

JPEG

18K

Low

7 Seconds

®

GIF

221K

N/A

80 Seconds ®

Is the winner really Medium? Not necessarily. It all depends on what your needs are. If you want a really high quality image, then you might want Very High. If you want the fastest possible site, then try Low.

We’ve chosen Medium because it is a nice trade off in size versus the quality of the image. You may think Low is good enough, or that it’s worth bumping the quality up to High. So, it’s all very subjective. One thing is for sure however, GIF doesn’t work very well for this image (which should not be a surprise).

you are here �

219

exercise solutions

If you look in the “html” folder with the chapter examples, you’l find al of the single Exercise
photo pages already there, except one: the page for “seat le_downtown.jpg”. Create a page cal ed “seat le_downtown.html” in the “html” folder, and test it out. Get this Solutions
working before you move on.

Here’s the answer:

Here’s the HTML; this file should
be called “seattle_downtown.html”.

<html>

<head>

<title>myPod: Seattle Downtown</title>

<style type=”text/css”> body { background-color: #eaf3da; } </style>

</head>

<body>

<h1>Downtown Seattle</h1>

<p>

<img src=”../photos/seattle_downtown.jpg” alt=”An iPod in downtown Seattle, WA”>

</p>

</body>

</html>

This file should go in the

“html” folder under “mypod”.

Here’s the test drive.

mypod
photos
thumbnails
html

220

Chapter 5

adding images to your web pages

1

2

I

Q

Exercise

3

4

P

I X E

L

U

Solutions

5

6

O

O

I M A G E

T

D

N

L

R

7G I F

I

A

8

9

E

A

T

P

N G

10

C O N C U R

R

E N T

L

Y

S

T

P

11

12

T H

I

R

T Y

F

I

V

E

J

A

A

P

R

13

14

T H U M B N A

I

L S

R

E S

I Z

E

I

G

N

A

C

15

A C

C

E S S

I

B

I

L

I

T Y

Across

Down

3. Smallest element on a screen. [pixel]

1. Lovable MP3 player. [ipod]

5. Web server makes a request for each one of

2. With JPEG you can control this. [quality]

these. [image]

4. The larger the image, the _____ it takes to

7. Better for solid colors, lines, and small text.

transfer it. [longer]

[GIF]

6. GIF has it, JPEG doesn't. [transparency]

9. Newcomer image format. [png]

8. Technique for softening edges of text.

10. Most Web servers retrieve images this way.

[antialias]

[concurrently]

12. Better for photos with continuous tones.

Sharpen your pencil

11. Miles you can draw with a pencil. [thirtyfive]

[JPEG]

13. Small images on a page. [thumbnails]

Here’s how you add the image “seattle.jpg” to the file “index.html”.

<h2> Seattle, Washington</h2>

<p>

Me and my iPod in Seattle! You can see rain clouds and the Space Needle. You can’t see the 628 coffee shops.

</p>

<p>

<img src=”photos/seattle.jpg” alt=”My iPod in Seattle, WA”>

</p>
you are here �

221

6 standards, compliance, and all that jazz

Serious HTML

What else is there to know about HTML? You’re well on your way to mastering HTML. In fact, isn’t it about time we move on to CSS and learn how to make all this bland markup look fabulous? Before we do, we need to make sure your HTML is really tight (you know... buttoned up, ship shape, nailed down) and we’re going to do that by getting serious about the way we write our HTML. Don’t get us wrong, you’ve been writing first-class HTML all along, but there’s a few things you can do to help the browser faithfully display your pages and to make sure that little mistakes don’t creep into your markup. What’s in it for you? Pages that display more uniformly across browsers (and even display well on mobile devices and screen readers for the visually impaired), pages that load faster, and pages that are guaranteed to play well with CSS. Get ready, this is the chapter where you move from Web tinkerer to Web professional.

this is a new chapter

223

writing standard html

Hey guys, the
boss just sent an email.

Before we move Head First

Lounge to CSS, he wants us to
button up our HTML.

Jim: Button up?

Frank: You know, make sure it meets the HTML

“standards.”

Jim: Our HTML is just fine... here, look at it in the browser. It looks beautiful. We’re a careful bunch. We
know how to correctly form our elements.

Joe: Yeah, that’s what I think... they’re just trying to give us another thing to worry about. Standards, schmandards.

We know what we’re doing.

Joe

Frank: Actually guys, I hate to admit it but I think the Jim

Frank
boss is right on this one.

Jim, Joe: Huh?!

Joe: Come on, this is just going to mean even more work.

We’ve already got enough to do.

Frank: Guys, what I’m saying is that I think this will help us do less work in the future.

Joe: Ha! This should be good...

Frank: Okay, here goes: the browser reads our HTML
and then does its best to display it, right? In fact, browsers are pretty forgiving... you can have a few mistakes here
and there, or use HTML incorrectly – like putting a block
element accidentally inside an inline element – and the
browser tries to do the right thing.

Jim: Yeah, and?

224

Chapter 6
standards, compliance, and all that jazz

Frank: But different browsers (say Internet Explorer versus Firefox versus Safari) have different ways of handling imperfect HTML. In other words, if you have mistakes in your HTML, then all bets are off in terms of how your pages will look in different browsers. It’s only when you don’t have mistakes that most browsers display things consistently. And when we start adding presentation to our HTML with CSS, the differences will get even more dramatic if our HTML
isn’t up to snuff.

So, by making sure we’re, as they say, “compliant” with the “standards,” we’ll have a lot fewer problems with our pages displaying incorrectly for our customers.

Jim: If that reduces the number of 3 a.m. calls I get, then that sounds like a good idea to me. After all, our customers use every browser under the sun.

Joe: Wait a sec, I still don’t get it. Aren’t we compliant now? What’s wrong with our HTML?

Frank: Maybe nothing, but there are a few things we can to do to make sure.

Joe: Like what?

Frank: Well, we can start by helping the browser a bit by telling it exactly which version of HTML we’re using.

Joe: I’m not even sure I know which version we’re using.

Frank: Ah ha! So there is some room for improvement here. Okay, let’s begin by figuring out which version of HTML we’re using and how we can tell the browser about it. There are a few other things we need to do too, but don’t worry, this isn’t a big deal. And, when we’re done, life will be much easier when we start using CSS.

brain
power

?

Browsers all do a pretty good job of consistently displaying your pages when you write correct HTML, but when you make mistakes or do nonstandard things in your HTML, pages are often displayed differently from one browser to another. Why do you think that is the case?

you are here �

225

html timeline

A Brief History of HTML

HTML 1.0-2.0

HTML 3

HTML 4

These were the early days;

The long, cold days of the

Ahhh... the end of the
you could fit everything

“Browser Wars.” Netscape

Browser Wars and, to
there was to know about
and Microsoft were duking
our rescue, the World

HTML into the back of
it out for control of the

Wide Web Consortium
your car. Pages weren’t
world. After all, he who

(nickname: W3C). Their
pretty, but at least they
controls the browser
plan: to bring order to the
were hypertext enabled.

controls the Universe,

Universe by creating the

No one cared much about
right?

ONE HTML “standard” to
presentation, and just
rule them all.

At the center of the fallout
about everyone on the
was the Web developer.

The key to their plan?

Web had their very own

During the wars, an

Separate HTML’s structure

“home page.” Even a count
arms race emerged as
and presentation into two
of the number of pencils,
each browser company
languages – a language for
paperclips, and Post-it
kept adding their own
structure (HTML 4.0) and a
notes on your desk was
proprietary extensions in
language for presentation
considered “Web content”

order to stay ahead. Who

(CSS) – and convince the
back then (you think we’re

could keep up? And not
browser makers it was in
kidding).

only that, back in those
their best interest to adopt
days, you had to often write
these standards.

two separate Web pages:

But did their plan work?

one for the Netscape
browser and one for

Uh, almost... with a few

Internet Explorer. Not good.

changes (see HTML 4.01).

1989 1991

1995

1998

226

Chapter 6

standards, compliance, and all that jazz

Our goal in this chapter is to
get ourselves up to HTML 4.01.

Starting in Chapter 7,
our goal is to be faithful
to XHTML 1.0. As
always, the world keeps
moving, so we’ll also talk
later in the book about
where things are going.

HTML 4.01

XHTML 1.0

Ah, the good life. HTML 4.01

But, of course, just as we
entered the scene in 1999,
were all getting comfortable,
and is the most current
new technologies were

????

version of HTML. While
created and things changed.

everyone hoped 4.0 would be

And what will happen

HTML and another markup
the ONE, it’s always the case
in the future? Will we
language known as XML
that a few fixes are needed
all be going to work
got together, and sooner
here and there. No biggies
than you can say “arranged
in flying cars and
and nothing to worry about.

swallowing nutrition
marriage,” XHTML 1.0 was
pills for dinner? Keep
born. XHTML inherited traits

Compared to the early days
from both parents: popularity
reading to find out.

of HTML (when we all had
and browser-friendliness from
to walk barefoot in 6 feet of

HTML, and extensibility and
snow, uphill both ways), we
strictness from XML. What
were all cruising along writing
does that mean? You’ll find

HTML 4.01 and sleeping well
out soon enough, because
at night knowing that almost
we’re going to have you
all browsers (at least the ones
creating XHTML Web
anyone would care about) are
pages before you can say
going to display your content
just fine.

“Extensible Hypertext Markup

Language.” Well, at least in
the next chapter.

1999

2000
you are here �

227

browsers and quirks mode

The Browser Exposed

This week’s interview:

Why do you care which version
of HTML you’re displaying?

Head First: We’re glad to have you here, Browser.

there are so many weird things that can happen on

As you know, “HTML versions” have become a
those pages.

popular issue. What’s the deal with that? You’re a

Head First: That sounds like a pretty good

Web browser after all. I give you HTML and you
solution to me...

display it the best you can.

Browser: Well, it can get you into trouble, though.

Browser: Being a browser is tough these days...

If you’re writing new HTML, but you don’t tell me
there are a lot of Web pages out there and many are
you’re writing new HTML, then I have to assume
written with old versions of HTML or with mistakes
you’re writing old HTML, and go into quirks mode
in their markup. Like you said, my job is to try to
just in case. And you don’t want that.

display every single one of those pages, no matter
what.

Head First: What do you mean?

Head First: So what’s the big deal? What does it

Browser: Not all browsers agree on how to display
really matter which version of HTML I use?

the older stuff, but we all do a pretty consistent job
with standard HTML. So if you’re using standard

Browser: Remember the browser wars? All kinds

HTML, tell me and you’ll get more consistent results
of elements were added to HTML that we aren’t
in all browsers.

supposed to use anymore. But some people expect us
browsers to be able to display them anyway, and we

Head First: Oh, so you can end up using the
don’t always agree on how that should be done.

quirks mode rules on the pages written using new

HTML?

Head First: Why aren’t we supposed to use those
elements any more?

Browser: Exactly. If I don’t know you’re writing
new HTML, I go into my quirks mode and do the

Browser: Well, before CSS was invented, HTML
best I can. But, you don’t want that because all those
had elements that were there for presentation, not

“quirks” mean that your pages might end up looking
structure. Now, with CSS, we don’t need those
a bit off, when they could have looked beautiful if I’d
anymore, but there are still plenty of Web pages out
only known you were using new HTML.

there that use them.

Head First: Ahh. So, what’s the solution to this

Head First: I think I’m starting to see the problem. mess? We definitely want our Web pages to look So how do you manage to display all these pages in
good.

all these different versions of HTML? That’s quite a
tall order.

Browser: Easy. Tell me up front which version of

HTML you’re using. That way I know which rules

Browser: Yeah, like I said, it’s tough being a
to use to display your page.

browser. What we end up doing is having two sets of
rules for displaying Web pages: one for old HTML

Head First: Got it. Thank you, Browser!

and one for the newer, standard HTML. When I use
the old rules, I call that my “quirks mode” because

228

Chapter 6
standards, compliance, and all that jazz

We can’t have your pages putting
the browser into Quirks Mode!

We’ll all be better off for telling the browser up front: “Hey, we’re an HTML page that gets it. We’re standards compliant. This is HTML 4.01, baby!”

When you do that, the browser knows exactly how to handle your page and (at least on any browser you’d care about) the page is going to display as you’d expect.

So, how do you tell the browser? Easy, you just add one line to the top of your HTML files. Here’s what the line looks like:

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”> Okay, we know that is one butt ugly line, but keep in mind, it is written for your browser, not you. This line is called a document type definition because it tells the browser the type of the document, and in this case, the document is your HTML page. Let’s just take a quick peek at this line to get a feel for it. But again, this is browser speak, not something you need to know well or memorize. Just throw it in You can type this all on
the top of your HTML and you’re ready to go.

one line, or if you want,
you can add a return

This means

This just means

This part says we’re using where we did. Just
that <html>
the HTML

HTML version 4.01 and
make sure you only press
is the root

4.01 standard
that HTML markup is
return in between the

Tells the browser this is (first) element is publicly
written in English.

parts in the quotes.

specifying a document
in your page.

type for this page.

available.

<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”

“http://www.w3.org/TR/html4/loose.dtd”>

We’ll talk
more about

Notice that this is NOT an HTML
the word
element. It has a “!” after the “<”

This points to a file that identifies
transitional
at the beginning, which tells you this
this particular standard.

in a bit....

is something different.

This is all tricky to type in with all the slashes, quotes, and so on. So instead of typing it in, you can copy and paste this text from the file

“doctype.txt”. You’ll find this file in the “chapter6” folder when you download the files for the book from the headfirstlabs.com Web site.

you are here �

229
html, standards, and document types
there are no

Dumb Questions

Q:

XHTML, so no mat er which standard you choose, it wil be easy for What exactly do you mean when you say we’re
you to write Web pages based on what you’ve learned so far.

“compliant,” or that we’re writing “standard HTML?”

Q:

A:

Let me get this straight: if I throw the document type
definition in the top of my HTML file, then the browser sees it

“Standard HTML” just means the version of HTML that
and can make certain assumptions about my HTML, which is a everyone has agreed is “the standard,” and right now that is HTML
good thing?

4.01.

Being compliant is just another way of saying your pages meet the standard.

A: That’s right. The document type definition tels your browser, Q:

“I’m using HTML 4.01.” When the browser sees that, it assumes you know what you’re talking about and that you really are writing And why should I care about standard HTML, or about

HTML 4.01. That’s good because the browser wil use the layout making my pages compliant? They look fine to me.

and display rules for HTML 4.01, and not use quirks mode.

A:

Q:

Do you real y want to go to al the trouble of writing Web

What if I tel the browser I’m using HTML 4.01, and I’m
pages and then styling them with CSS, only to have them display not?

inconsistently (which is another way of saying “display badly”) in some browsers? By making them compliant, you’re assuring that your pages are going to display as consistently as possible in a A: The browser will figure out that you’re not really writing variety of browsers.

HTML 4.01 and go back to quirks mode. And then you’re back to the Q:

problem of having the various browsers handle your page in dif erent ways. The only way you can get predictable results is to tell the How do I make sure my pages are compliant, then?

browser you’re using “HTML 4.01” and to actually do so.

A:

Q:

You need to do a couple of things, which we’re going to go

I really don’t have to worry about what’s in the document through, but we’re also going to make use of a freely available tool type line? Just throw it on my page?

on the Web that checks your pages to make sure they’re compliant.

Q:

A: Yup, that’s prety much the case. Although there is one

So, we’re calling HTML 4.01 the standard?

gotcha: there are a few dif erent document types you might want to know about and we’re going to talk about another one of those in A:

just a sec. But, in terms of using the document type, just throw it in Yes, HTML 4.01 is the HTML standard most widely supported the top of your file. Once you’ve got the DOCTYPE in there, no one by browsers. The Web keeps moving ahead, though, so we’ll talk in worries on a daily basis about what it has in it.

the very next chapter about what’s new in the standards world.

Q:

Q: The word “transitional” in that document type worries What happens when there is an HTML 5?

me a bit. I thought this was a standard, but it sounds less than standard if it is “transitional.”

A: Good question. It’s likely that there won’t be an HTML 5
because the new standard for writing Web pages is XHTML. You’re A: Good catch, and you’ve got good instincts. If you’l hold on a going to learn al about XHTML in the next chapter. The good news few pages we’ll get to the bottom of that question.

is that you’re already in great shape to use either HTML 4.01 or 230

Chapter 6

standards, compliance, and all that jazz

Okay, I think we’ve got
it now. Let’s get that

DOCTYPE in the lounge files.

Adding the document type definition

Enough talk, let’s get that DOCTYPE in the HTML. You can attempt to type it in yourself (we hope you have really good eyes), or you can copy and paste it from the file “doctype.txt” in the “chapter6” folder.

Here’s the

DOCTYPE line. Just

<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”

add it as the very

“http://www.w3.org/TR/html4/loose.dtd”>
first thing in the

<html>

“lounge.html” file.

<head>

Remember, you can type it all on one line, or

<title> Head First Lounge</title> you can hit return between the quoted parts

</head>
like we’ve done her

<body>
e.

<h1> Welcome to the New and Improved Head First Lounge</h1>

<img src=”drinks.gif”>

<p>

Join us any evening for refreshing

<a href=”elixir.html”> elixirs</a> , conversation and maybe a game or two
of <em>Dance Dance Revolution</em>.

Wireless access is always provided;

BYOWS (Bring Your Own Web Server).

</p>

<h2>Directions</h2>

<p>

You’ll find us right in the center of downtown Webville. If you need help finding us, check out our

<a href=”directions.html”> detailed directions</a> .

Come join us!

</p>

</body>

</html>
you are here �

231

testing with a document type

The DOCTYPE test drive

Make the changes to your “lounge.html” file in the

“chapter6/lounge” folder and then load the page in your browser.

Wow, no difference. Well, we didn’t
really expect any because all the

DOCTYPE does is let the browser
know for sure you’re using HTML 4.01.

Add a DOCTYPE to the “directions.html” and “elixir.html” file as wel . Go ahead and give them a good test. Just like “lounge.html”, you won’t see Exercise
any fireworks (but you might sleep a bit better tonight).

232

Chapter 6

standards, compliance, and all that jazz

See, piece of cake.

The DOCTYPE is in our
pages and working fine.

Jim: Yeah, really easy. But here’s what I still don’t get: we put this DOCTYPE at the top of our file to tell the browser our page is HTML 4.01
but that doesn’t ensure that the file really is HTML 4.01. We could have made a mistake. So what’s the point?

Frank: You’re right, because your promise to the browser is only good if you actually have written perfect HTML 4.01. That’s what I was going to get to next. What we can do is make use of a free online service that can look at a page and tell us if it’s compliant.

Jim: Really? How does that work?

Frank: Well, this service first looks at the document type and then checks all your HTML and makes sure it’s actually correct... like checking to make sure you’re spelling your tag names right, your elements are nested properly, that your inline elements are inside block elements and so on. It’s called a validator.

Jim: Wow, and this is free? Who provides this service?

Frank: The guys who came up with the standards. They’re called the World Wide Web Consortium, or W3C for short.

Jim: This sounds like the answer to writing compliant HTML. But how do I know all those things you just mentioned, like what elements go inside what elements?

Frank: Let’s check out the validator first and then we’ll come back to that...

you are here �

233

validating your html

Meet the W3C validator

Let’s give the validator a spin and have it check out the
lounge files. To follow along, just point your browser to
http://validator.w3.org.

The W3C validator is located at http://validator.w3.org.

There are three ways you
can check your HTML:

(1) If your page is on the Web, then
you can type in the URL here,
click the “Check” button, and the
service will retrieve your HTML
and check it.

(2) You can click “Choose file” (or

“Browse” if you’re using Windows)

and choose a file on your computer.

When you’ve selected the file, click

“Check”, and the browser will upload
the page for the service to check.

(3) Or, copy and paste your

HTML into this form. Then
click “Check” and the service
will check your HTML.

234

Chapter 6

standards, compliance, and all that jazz

Validating the Head First Lounge

We’re going to use option (3) to validate the “lounge.html”

file. That means we need to copy and paste the HTML from

“lounge.html” into the form at the bottom of the W3C validator Web page; keep following along and give it a try...

We’re using method (2) here. We clicked on the “Choose File” button and browsed to the file “lounge.html”, which now has the DOCTYPE for Transitional HTML 4.01 at the top. We’re ready for the big moment... will the Web page validate? Bets anyone?

Click “Check” (and turn the page) to find out...

Feel free to use method (1) or

(3) if it’s more convenient.

you are here �

235

the alt attribute is required

Houston, we have a problem...

That red on the page can’t be good. It doesn’t look
like the page validated. We’d better take a look...

We failed the
validation. It
looks like there
is one error.

This must be
the error.

The W3C is constantly
revising the validator.

Watch it!

Because the W3C frequently revises the

This doesn’t look bad. It looks like in
validator, you may not see exactly the

HTML 4.01 we have to put an alt
same error messages. No worries, just
attribute in the <img> element.

keep fol owing along because al the stuff
in the next few pages is important, even if
you don’t see the error above.

236

Chapter 6
standards, compliance, and all that jazz

Fixing that error

Okay, this looks pretty simple to fix. You just need to add an alt attribute to your <img> elements in HTML 4.01. Go ahead and open “lounge.html”, make the change, save, and
then let’s try to validate again.

<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”

“http://www.w3.org/TR/html4/loose.dtd”>

<html>

<head>

<title> Head First Lounge</title>

</head>

<body>

<h1> Welcome to the New and Improved Head First Lounge</h1>

<img src=”drinks.gif” alt=”Drinks”>

<p>

Join us any evening for refreshing

<a href=”elixir.html”> elixirs</a> , You know the alt attribute;
conversation and maybe a game or two
add it into the <img> element.

of <em>Dance Dance Revolution</em>.

Wireless access is always provided;

BYOWS (Bring Your Own Web Server).

</p>

<h2>Directions</h2>

<p>

You’ll find us right in the center of downtown Webville. If you need help finding us, check out our

<a href=”directions.html”> detailed directions</a> .

Come join us!

</p>

</body>

</html>
brain
power

?

Why do you think the alt attribute is required in HTML 4.01?

you are here �

237

tentatively valid html

We’re not there yet...

Hmm; it looks like we’re now “tentatively valid HTML 4.01 Transitional.” That sounds like “close, but no cigar.” Let’s take a look:

There’s definitely some
issue with the lounge Web
page, but what the heck
does this mean??

It looks like
if we fix the
problem above
we’ll have valid

HTML.

So, we’ve got a perfectly valid HTML file in terms of how we’ve written the HTML, but it looks like we have to tell it something about our “Character Encoding”. To solve that we’re going to have to find out what the heck it means...

238

Chapter 6

standards, compliance, and all that jazz

See, we’re getting this
error message that
the validator can’t find a
character encoding.

Frank: The character encoding tells the browser what kind of characters are being used in the page. For instance, pages can be written using encodings for English, Chinese, Arabic, and lots of other types of characters.

Jim: What’s so hard about figuring out how to display a character?

If there’s an “a” in the file, then the browser should display an “a”.

Right?

Frank: Well, what if you’re using Chinese in your pages? It’s an entirely different “alphabet” and it has a heck of a lot more than 26

A-Z characters.

Jim: Oh. Good point.... But shouldn’t the browser be able to tell the difference? Those other languages look nothing like English.

Frank: No; the browser is just reading data. It could assume it was getting English-language characters, but what if it’s not? The character encoding takes the guesswork out of it.

Jim: We’ve had the site up for a long time; why is this an issue now?

Frank: Because the validator is saying “Hey, if I’m going to validate your page, you’d better tell me up front what characters you’re going to use!” And think about it, we’d want to do that for the browsers out there anyway. Don’t stress, we just need to add one more line to our HTML, called a <meta> tag. I should have thought of this sooner.

Jim: Got any other surprises for us? I really thought our Web page would validate after we put the document type definition in our file...

Frank: I sure hope there are no more surprises! Let’s get the <meta> tag in there and find out.

you are here �

239
using <meta> to specify a content type

Adding a <meta> tag to specify the content type

Most of you reading this book are probably using English or Western-European languages (the so-called “Latin” languages), so you’ll need a <meta> tag in your HTML that looks like this:

<meta http-equiv=”Content-Type” content=”text/html; charset=ISO-8859-1”> You’re going to throw this line in as the first thing inside the <head> element of your HTML. This tag tells any browser the content type of your file, and what kinds of characters are used to encode it. Let’s look at the <meta> tag in a little more detail...

e’re

And we’re going to The content attribute

“meta” means w
tell it something

Here’s the new part; this tells
going to tell the
more about the
is where we specify
the browser that we’re using
browser something
content type of
the content type
the ISO-8859-1 character
about the page...

the page.

information.

encoding.

<meta http-equiv=”Content-Type” content=”text/html; charset=ISO-8859-1”> Just like other HTML tags, the

Notice that this whole

<meta> tag has attributes.

First we tell it that this is an HTML
file. This is a bit redundant, because the
string is the value of the
browser already knows that (remember we
content attribute.

told it that in the DOCTYPE as well).

there are no

Dumb Questions

Q: DOCTYPES, <meta> tags.. ugh, do I need to realy Q: ISO-8859-1?

remember all this to write Web pages?

A:

A: Work with us here. It’s like WD-40; you don’t worry about Specifying a DOCTYPE and a <meta> content tag why it’s called that, you just use it.

are kind of like taxes: you got a do them to be compliant. Look ISO-8859-1 is the character encoding for “Latin-1” characters, at it this way: you already understand them more than 99% of which can represent almost all the European languages. If
the Web page writing population, which is great. But at the end you’re writing in another language, check out the information on of the day, everyone just puts the DOCTYPE and <meta> tag in character encoding at
their HTML and moves on with life. So make sure you’ve got the http://www.w3.org/International/O-charset.html.

right DOCTYPE and <meta> tag and then go do something much more fun.

240

Chapter 6
standards, compliance, and all that jazz

Making the validator (and more
than a few browsers) happy with a

<meta> content tag...

Okay, you know the plan. You just need to type the <meta> content type line right into your HTML. Let’s first add it to the “lounge.html” file: Here’s the <meta> tag.

We’ve added it to the

<head> element above the

<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”

<title> element.

“http://www.w3.org/TR/html4/loose.dtd”>

<html>

<head>

<meta http-equiv=”Content-Type” content=”text/html; charset=ISO-8859-1”>

<title> Head First Lounge</title>

</head>

<body>

<h1> Welcome to the New and Improved Head First Lounge</h1>

<img src=”drinks.gif” alt=”Drinks”>

Always add this line

<p>
above any other

Join us any evening for refreshing
elements in the

<a href=”elixir.html”> elixirs</a> ,

<head> element.

conversation and maybe a game or two
of <em> Dance Dance Revolution</em> .

Wireless access is always provided;

BYOWS (Bring Your Own Web Server).

</p>

<h2>Directions</h2>

<p>

You’ll find us right in the center of downtown Webville. If you need help finding us, check out our

<a href=”directions.html”> detailed directions</a> .

Come join us!

</p>

</body>

</html>

Want to place another bet? Is this going to validate? First, make the changes to your “lounge.html” file, save it and reload it into your browser. Once again, you won’t notice any change, but the browser will.

Now let’s see if it validates...

you are here �

241

testing the meta tag

Third time’s the charm?

Just like before, upload your “lounge.html” HTML file to the W3C validator Web page at http://validator.w3.org. Or, you can validate by copying and pasting your HTML into the form, or even transfer the files to your Web site and give the validator your URL, whichever you prefer. Once you’ve done that, click the “Check” button...

“Passed validation”,
you’re golden!

Red was bad, green’s
got to be good.

Like it says, you told the browser

(and the validation service) that you
are using HTML 4.01 Transitional,
and the service w

See! That was nothing
as able to validate
and now we’re writing valid
your page successfully.

HTML 4.01. I think we’re going to
be talking BONUS when the boss
sees how fast we’re moving.

242

Chapter 6

standards, compliance, and all that jazz

Okay, it’s been more than
a “few pages” since you said
you were going to talk about what

“transitional” means. What’s with this
transitional stuff? If we’re writing

“standard” HTML 4.01, why is it
transitional?

There are actually two DOCTYPEs, one
for those transitioning to HTML 4.01,
and a more strict DOCTYPE for those
who are already there.

Imagine you’ve got a Web site with hundreds of Web
pages, all written in nonstandard HTML. You’d like to
improve the site and get all that HTML up to the 4.01
standard, but you’re using lots of old legacy stuff from
back in the 2.0 and 3.2 days of HTML.

What do you do? Use the HTML 4.01 Transitional

DOCTYPE, which allows you to validate your pages but
still permits some of the legacy HTML. That way, you
can be sure you don’t have any outright mistakes in your
markup (like typos, mismatched tags, and so on) but you
won’t have to rework all your HTML to get it to validate.

Then, after you’ve removed all the legacy HTML, you’re
all ready for the strict document type, which ensures you
have a fully compliant, standardized Web site.

you are here �

243

questions about strictness

Okay, so it gives us
a transition point between
old style HTML and standard

HTML 4.01. But why are we
using it? Why didn’t we just
start with strict?

We certainly could have.

That would have been a perfectly valid
approach. But, while we’ve been writing pretty
decent HTML in this book, we’re just now
learning how to write it in a way that is correct
and standardized. Right? And, as you can see,
it took us a few steps to get there, what with
all the DOCTYPEs and <meta> tags and the
alt attribute.

But now that we’re there, and we’ve got
validated transitional 4.01 HTML, we’re in a
good position to start using the strict form of

HTML. Let’s give strict a try and then we can
talk a little more about transitional versus strict.

244

Chapter 6

standards, compliance, and all that jazz

I think we’ve been pretty
darn strict in our HTML.

Let’s throw the strict

DOCTYPE in and see what
happens.

To move from transitional HTML 4.01 to strict, we
change the DOCTYPE to the strict version. Once we’ve
done that, the validator (and browsers) will assume we’re
playing by stricter rules that don’t allow some of the
legacy HTML. We’ll talk about those rules in a sec, but
for now let’s give the strict DOCTYPE a try. To do that,
we’ll start by taking a quick look at the DOCTYPE:

This stuff is the same as
the transitional DOCTYPE.

The word “Transitional” is gone.

Here’s the strict version of

<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01//EN”

the HTML 4.01 DOCTYPE.

“http://www.w3.org/TR/html4/strict.dtd”>

Overall this all looks
remarkably similar.

Remember this URL defines what
belongs in strict HTML.

No big differences here. The “transitional” word is
gone and we have a different URL that defines the strict
version of HTML 4.01. Let’s replace the transitional

DOCTYPE with the strict and try to validate.

you are here �

245
making your html strict

Changing the DOCTYPE to strict

Open your “lounge.html” file again. To change from transitional to strict, you just need to do two things to the DOCTYPE: delete the word

“Transitional” and, in the URL, change “loose.dtd” to “strict.dtd”. Or if you like, you can delete the old line and type the new one in.

First, remove the word

“Transitional”.

<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01//EN”

“http://www.w3.org/TR/html4/strict.dtd”>

<html>

And then replace “loose.dtd” with “strict.dtd”.

<head>

<meta http-equiv=”Content-Type” content=”text/html; charset=ISO-8859-1”>

<title> Head First Lounge</title>

</head>

<body>

<h1> Welcome to the New and Improved Head First Lounge</h1>

<img src=”drinks.gif” alt=”Drinks”>

<p>

Join us any evening for refreshing

<a href=”elixir.html”> elixirs</a> , conversation and maybe a game or two
of <em> Dance Dance Revolution</em> .

Wireless access is always provided;

BYOWS (Bring Your Own Web Server).

</p>

<h2>Directions</h2>

<p>

You’ll find us right in the center of downtown Webville. If you need help finding us, check out our

<a href=”directions.html”> detailed directions</a> .

Come join us!

</p>

</body>

</html>

That’s it. Just make sure your DOCTYPE looks exactly as it does above.

Now all that remains is to ask the validator if our HTML is compliant with the strict version of HTML 4.01. Use the validator again to check the page, after making sure your page has the changes above.

246

Chapter 6

standards, compliance, and all that jazz

Do we have validation?

Uh oh, red again. That can’t be good.

It looks like we’re not valid under
the strict rules, but why?

Let’s look at the error message: it
looks like strict HTML doesn’t like
where we put the <img> element.

But transitional was okay with it...

sounds like maybe the nesting rules
changed in strict HTML?

“I think we’ve been
pretty darn strict...”

How’s this for strict?

you are here �

247

diagnosing why the html isn’t strict

Come on guys, no fighting. I
see your problem. You’re not
using the right nesting for strict

HTML 4.01. But it’s easy to fix.

Joe: We’re not?

Judy: No. Look here, you’ve got an <img> element that’s nested in the

<body> element. That was okay in older versions of HTML, and 4.01
transitional lets it slide, but in the current standard, inline elements belong inside block elements.

Joe: Oh right, <img> is an inline element.

Judy: Yup. It’s easy to fix though; all you have to do is stick your image in a block element like <p> and you’ll be good to go.

Joe: I guess that’s clear if you look at that error message... the elements I recognize are all block elements. Like <h1> , <p> , etc.

Judy: Exactly.

Judy

Joe: But I don’t see all the block elements we’ve used... for instance,

<blockquote> seems to be missing from the list. That’s a block element, right?

Judy: Good point. You can’t stick the <img> element into just any block element in HTML 4.01 strict. <blockquote> is an example of a block element that you can’t nest inline elements directly inside.

Joe: Well, how are we supposed to know if we’re nesting things properly before we try to validate – is there a list of “nesting rules” somewhere?

Judy: There is, but you can remember most of them using common sense once you’ve looked at the rules.

Frank: Judy, are there any other places where we didn’t nest things properly?

Judy: I don’t see any... the rest of this looks pretty good to me. But that’s why we have validators. They never miss a thing. Humans do.

Frank: Okay, well let’s fix it and get this page validated. I’m ready to see the green bar of success here, guys.

Judy: Good luck and good work. It looks like you’ve almost got it.

248

Chapter 6

standards, compliance, and all that jazz

Fixing the nesting problem

So it looks like strict HTML 4.01 prefers that images, which are inline elements, be nested inside a block element, like a paragraph or a heading. That’s a simple change to make. Open your “lounge.html”

file and add a <p> element around the <img> element.

<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01//EN”

“http://www.w3.org/TR/html4/strict.dtd”>

<html>

<head>

<meta http-equiv=”Content-Type” content=”text/html; charset=ISO-8859-1”>

<title> Head First Lounge</title>

</head>

<body>

<h1> Welcome to the New and Improved Head First Lounge</h1>

<p>

<img src=”drinks.gif” alt=”Drinks”>

Now, the image “drinks.gif” is safely

</p>
nested inside a <p> element.

<p>

Join us any evening for refreshing

<a href=”elixir.html”> elixirs</a> , conversation and maybe a game or two

All our other inline elements,
of <em> Dance Dance Revolution</em> .

like <a> and <em>, are already

Wireless access is always provided;
inside block elements - these

BYOWS (Bring Your Own Web Server).

</p>
paragraphs.

<h2>Directions</h2>

<p>

You’ll find us right in the center of downtown Webville. If you need help finding us, check out our

<a href=”directions.html”> detailed directions</a> .

Come join us!

</p>

</body>

</html>

Once you’ve done that, save and reload the page in your
browser. You’ll see it doesn’t really affect the look of the page.

Why? Because the heading above the image and the paragraph below are already block elements with linebreaks below and
above them, respectively. So the <p> element around the image doesn’t actually add any new linebreaks or spacing.

you are here �

249

a successful strict test

One more chance to be strict...

You know the game. Ask the validator to give your “lounge.html”

file another try. Let’s see if we’re worthy...

It works! The big green
badge of success.

And we’re HTML

4.01 Strict.

Can you say “HTML

Superstar?” Oh yeah,
bring on that strict 4.01.

We’re ready.

Is that “bring it on
as long as we have Judy
around to bail us out?” Come
on guys, we’ve gotta figure
out what we can and can’t
do in HTML 4.01.

250

Chapter 6

standards, compliance, and all that jazz
there are no

Dumb Questions

Q:

a block element. The first thing it does
hopefully you’ll spot your mistake.

Okay, I think I get al this, and
is say, “Hey, I expected a block element

After reading these error messages for a
it was kind of fun having the validator
here.” It keeps reading, and then gets to
while you’l start to get the hang of them
check my HTML, but SO WHAT? Again,
the end of the <img> element (which,
and often know what they are referring
what is all this “compliance” really
since <img> is an empty element,
to, even if the validator doesn’t tel you
getting me?

happens as soon as it sees the “>” at the
specifical y.

end of the <img> tag) and says, “Hey

A:

you can’t be ending an <img> element

Q:

How does happier customers
here because there shouldn’t be an

Why are al the element
sound? If you know your HTML is valid,

<img> element here to start with.”

names listed in that error message in
then it’s more likely that your Web pages

Also, you might find that you see multiple
uppercase? I thought element names
wil work consistently in a wide variety of
error messages from one mistake. Just
were written in lowercase.

browsers, which is going to give your Web take it one error message at a time, fix page users a bet er experience. There
your mistake, and you’l often find you

A:

are a few other benefits: Web pages with
eliminate more than one error message in

Good question. HTML actually
compliant HTML load faster and work
the process.

allows element names to be uppercase
bet er on other devices that are now
or lowercase, or even mixed case. You
being used to surf the Web (like TVs and

Q:

could write <IMG> or even <ImG> if you
phones). They’re also more accessible to

Are all the validator’s error
wanted. However, the W3C is changing
the visual y impaired who are using aural
messages so difficult to understand?

the rules, so in the future element names
screen readers.

wil al be lowercase. So, while technical y
the validator for Strict HTML 4.01 still

Q:

A: Generaly, yes, the error
allows (and displays) uppercase tags,

So can you explain the error in
messages can be a lit le difficult to
we’re only using lowercase so you’ll get
detail? I want to understand exactly
decipher. This is a piece of software
into the habit of using only lowercase.

what it means.

tel ing you what is wrong, not a human

This means you won’t have to update your
or a Head First book. Remember, the
tag names down the road (and that means

A:

validator doesn’t know what you meant to
less work for you). And when we say

The error was caused by the
do and can only at empt to decipher and

“down the road,” we actually mean in the

<img> element not being nested inside
indicate errors in what you actually did.

next chapter.

a block element. Imagine the browser is

Most of the time, it wil point you to the
reading through your HTML, and sees
right line in your HTML where your error
an <img> element where it expected
is occurring, which is half the battle. Then

Your turn. Add the strict DOCTYPE and the <meta> tag to

“directions.html” and “elixir.html”. Try validating them – do Exercise
they validate? If not, fix them so that they do.

you are here �

251

understanding how to be strict

Strict HTML 4.01, grab the handbook

You’ve been in Webville for a few chapters now. Don’t you think it’s about time you learn the local rules of the road? Luckily, Webville has prepared a handy guide to using strict HTML 4.01. This guide is meant for you – someone who is new to Webville. It isn’t an exhaustive reference, but rather focuses on the more important common sense rules of the road. And you’ll definitely be adding to the knowledge in this guide as you get to know your way around Webville in coming chapters. But for now, take one – they’re FREE.

252

Chapter 6

standards, compliance, and all that jazz

Webville Guide to Strict HTML 4.01

Traveling on the information super-highway can be dangerous if you don’t know the rules. In this handy guide, we’ve boiled strict HTML 4.01 down into a common sense set of rules, starting with the major rules first: The <html> element: don’t leave home without it.

Always start each page with a DOCTYPE, but fol owing
that, the <html> element must always be the top, or root, element of your Web page. So, after the DOCTYPE,
the <html> tag will start your page and the </html> tag should end it, with everything else in your page nested
inside.

Remember to use both your <head> and your

<body> for better HTML.

Only the <head> and <body> elements can go directly inside your <html> element. This means that every other element must go either inside the <head> or the

<body> element. No exceptions!

What’s a <head> without a <title>?

Always give your <head> element a <title> element.

It’s the law. Failure to do so wil result in HTML that isn’t compliant. The <head> element is the only place you should put your <title> , <meta> , and <style> elements.

Feed your <body> only wholesome block elements.

You can put only block elements (<h1>, <h2>, ..., <h6>,

<p>, <blockquote> , and so on) directly inside your

<body> element. Al inline elements and text need to be inside another block element before they can go in the

<body> element.

Keep block elements out of your inline elements.

The only things you can put in an inline element are text
and other inline elements. Block elements are not allowed
under any circumstances.

you are here �

253

strict html fine points

Webville Guide to Strict HTML 4.01 Continued

Now that you’ve got the major rules down, let’s look at some of the finer points of the law.

Keep block elements out of your <p> element.

Paragraphs are for text, so keep block elements out
of your paragraphs. Of course it is perfectly fine to use
all the inline elements you want in them (<em> , <a> ,

<strong> , <img> , <q> , and so on).

Lists are for list items.

Only the <li> element is allowed in the <ul> and <ol> elements. Why would you want to put anything other
than a list item in an unordered or ordered list anyway?

Go ahead, put whatever you want in a list item.

Webville has very liberal laws when it comes to the <li> element: you can put text, inline elements, or block
elements inside your list items.

Oops! We weren’t
up to the 4.01
standard when

Who knew? The <blockquote> only likes
we did Tony’s
block elements.

<blockquote> in

The <blockquote> element requires one or more Chapter 3. That
block elements inside it. While it’s common to see text text should have directly inside a block quote, that isn’t up to code here been put inside a in Webvil e. Please always put your text and inline

<p> first.

elements inside block elements before adding them to
a <blockquote> .

Be careful about nesting an inline element
inside another inline element.

While you can nest just about any inline element in
another, there are a couple of cases that don’t make
sense. Never nest an <a> element inside another <a> element because that would be too confusing for our
visitors. Also, empty elements like <img> provide no way to nest other inline elements within them.

254

Chapter 6

standards, compliance, and all that jazz
there are no

Q: Dumb Questions
quotes someone else. So, in general you can nest

That wasn’t too bad; I was expecting pages
any of the inline elements inside other inline elements.

of rules I had to remember. Can I really write strict

Some of these make more sense than others, but the

HTML 4.01 just following these rules?

<a> element is the only one that you can’t nest inside itself. Remember too, that the <img> element is A:

empty, so you can’t nest anything inside it.

These rules will get you a long way, but
remember, you haven’t learned everything about HTML Q: So why can’t I put text directly in a yet, so there are going to be a few new things that

<blockquote>? A list item can have text or a block you’l need to keep in mind too. That said, there is no
element. That seems inconsistent.

reason to memorize all these rules. Your common
sense and this guide is a good start, and from there
you can also consult an HTML reference or just ask the A: ’Cause the standard says so. Just kidding.

validator if your HTML is valid (you should anyway!)

You’re right, it does seem inconsistent, but it’s all
when you get into some tricky areas.

based on the intent of the element. Take the <p>

Q:

element, for instance. It’s for one text paragraph, so

So whenever possible, always go with
of course no other block elements are al owed in it.

strict?

<blockquote>? It’s for quoting large portions of text from another source, which might include headings,

A:

paragraphs, whatever. So the point is to “quote

It depends. Just throwing up a page that three
blocks.” List items? They’re like the contortionists of
people in the world wil see? Hey, as long as it looks
the element world – they have to be able to hold simple
good in al your browsers, who cares. But if you’re
text, large bits of text like paragraphs or even other
doing something a fair number of people wil visit,
lists, so they can handle everything.

you’l be bet er of keeping your HTML up to standards

Webvil e’s a friendly
and validating it. Should that be the transitional or

Q: I noticed the validator said place. Forget a rule? Just strict standard? Wel , the world is moving in the
the standard requires the “alt”

run it by me, the Validator.

strict direction, so you can pay now or pay later, but
attribute on <img> elements. Are

I’ll get you pointed in the
eventual y, it wil be in your best interest to go strict.

there any other attributes that are
right direction.

When you’re starting fresh, strict is just as easy. And
required?

if you use strict, moving to XHTML wil be a lot easier,
and we’re going to do that in the very next chapter and
use XHTML in the rest of the book.

A: Wow, good catch. Yes, the alt atribute

Q:

is required on images for accessibility, so that, for

So I get that putting an <a> inside an <a>
instance, the visual y impaired can know what the
is confusing and wouldn’t work anyway. But I can
image is, even if they can’t see it. The other required
real y put an <em> inside an <em>? What’s the attribute is the src at ribute on an image – what good point of that?

is an <img> element if it doesn’t point to an image?

There are also some at ributes that were okay with

A:

HTML 3.2 that you can’t use anymore with strict HTML

In principle, someone might want to put

4.01. Why? Because most of them affected the way
emphasis on emphasis. That seems sil y, but since it

Web pages looked, and you’re supposed to be using
doesn’t cause problems, like nested

CSS for that kind of styling (more on this topic in just a

<a> elements
do, the standard just says, if you want to do it, you
couple of chapters).

can. What about a <q> within a <q> , would that ever Validator
make sense? Sure, you might quote someone who
you are here �

255

pondering strict versus transitional

Tonight’s talk: Transitional and Strict try to
recruit followers.

Transitional

Strict

Hey there, Strict. You here to talk about how
much you love frustrating Web page writers?

What’s that supposed to mean?

Oh, you know, al those Web page writers out
there who are struggling to get their Web pages
to validate with your strict DOCTYPE. You’re
pretty tough, you know.

It’s tough love, man.

Tough love?

Yeah. Sooner or later any page of importance
really needs to move to strict. You may think

I’m tough now, but you’ll love me later.

Oh, please. Not everyone wants to be strict all
the time.

Huh? You encourage people to stay behind
the times with all those old tags and attributes.

You’re just a crutch.

Not everyone can, or wants to, transition their
entire Web site to the strict standard overnight,
you know. Sheesh, I’m playing an important

The way I see it, people get to say they’re
role here.

“standard HTML” when in reality, they’re still
relying on old habits. I say, strict is the way to
go. That’s the only way to future-proof a Web
site.

How is it future-proofing anything?

Hey man, some of your tags have been

“deprecated.” Do you know what that means? It
means they’re going away. By going strict now,
it’ll be a lot easier to update to the next version
of HTML.

256

Chapter 6
standards, compliance, and all that jazz

Transitional

Strict

So, you’re just going to leave behind al those
mil ions of Web pages out there that stil use older
versions of HTML? Ignore them completely? I
bet you use some nonstrict Web pages yourself.

Oh no, you’re not coming near my browser

How ’bout I come over and check your history list?

history; keep your grubby paws off it. You’re
right, there are a lot of useful pages out there
that need to be updated, and maybe they never
will be, but we’re trying to build a better Web.

So stop encouraging people to stay behind the
times.

Not everyone wants to be on the cutting edge,
you know. Some people like using those old tags.

Other people want to take things a bit slower,
make sure they understand exactly what the new
standard is before jumping in and wil y-nil y

Willy-nilly? There’s nothing willy-nilly about
changing their pages.

4.01. It’s actually cleaner and simpler to
understand than the older HTML versions.

And, if people write their Web pages correctly,
they’ll be well prepared to have their pages
work well in browsers for a long time.

You know, you real y should be nice to me; I’ve
helped a lot of pages move to strict.

Okay, it is helpful for people to be able to mark
their pages as transitional until they learn the
new stuff. All I’m saying here is transitional
shouldn’t be used as a crutch. And anyone
reading this book who is new to HTML and

True, they can just start strict and won’t need me.

CSS has no need to be transitional.

Anyway, I’m going back to my kinder and gentler
method of moving pages to strict. You can go back
to cracking your whip.

Hey! Watch it. Pages will be thanking me down
the road for keeping them strict.

Yeah, yeah. Did you bother tel ing the readers that
by the end of the chapter, you’ll be obsolete too?

Uhhhh....

you are here �

257

html and deprecated markup

One more question
about this transitional
stuff. What is all this old
markup that isn’t al owed in
strict? Have we seen any
examples?

No, we’ve been writing mostly
strict HTML all along.

Even though we haven’t been including a

DOCTYPE or a <meta> tag, and we’ve
been a little lazy on the image nesting rules,
throughout this book you’ve been writing

That’s a good thing, because

HTML that is very close to the standard. So,
sometimes unlearning a bad
you haven’t had much opportunity to see the
habit is the hardest part of
phased out elements and attributes.

a new standard.

Want to see some? Just visit a few Web pages
with your browser and choose “View Source”

from the “View” menu (your browser’s menus
may differ). Any tag or attribute that looks
like it is used to alter the display of the page is
most likely deprecated in HTML 4.01 (because
that is now CSS’s job). It doesn’t hurt to know
a little about these legacy elements, because
you are quite likely to run into some of them
now and then. Let’s take a quick look...

258

Chapter 6

standards, compliance, and all that jazz

HTML

Archeology

We did some digging and found an HTML 3.2 page
that contains some elements and attributes that are no
longer part of the standard, as well as a couple of common mistakes that are no longer allowed in strict HTML 4.01.

<html>

<head>

<title> Webville Forecast</title>

Here are some attributes that

</head>
controlled presentation. bgcolor sets
the background color of the page, and

<body bgcolor=”tan” text=”black”>
text sets the color of the body text.

<p>

The weather report says lots of rain and wind in store for

<font face=”arial”> Webville</font> today, so be sure to stay inside if you can.

</p>

Font changes were made with the

<font> element and its face attribute.

<ul>

<li> Tuesday: Rain and 60 degrees.

<li> Wednesday: Rain and 62 degrees.

You could get away without some

</ul>
closing tags, like </li> and </p>.

<p align=right>

Or even without double quotes around

Bring your umbrella!

attribute values.

<center><font size=”small”> This page brought to you buy Lou’s Diner, a Webville institution for over 50 years.

</font></center>

</body>

Text size was controlled with

</html>
the <font> element, using

Here are two ways to align text. the size attribute.

Right align a paragraph, or
center a piece of text.

you are here �

259

test your knowledge of strict

BE the Validator

Below, you’ll find an HTML
file. Your job is to play like
you’re the validator and locate

ALL the errors. After you’ve
done the exercise, look at the
end of the chapter to see if you
caught them all.

Use the validator to check
your work once you’ve done

(or if you need hints).

<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01//EN”

“http://www.w3.org/TR/html4/strict.dtd”>

<html>

<head>

<meta http-equiv=”Content-Type” content=”text/html; charset=ISO-8859-1”>

</head>

<body>

<img src=”chamberofcommerce.gif”>

<h1>Tips for Enjoying Your Visit in Webville</h1>

<p>

Here are a few tips to help you better enjoy your stay in Webville.

<ul>

<li>Always dress in layers and keep an html around your head and body.</li>

<li>Get plenty of rest while you’re here, sleep helps all those rules sink in.</li>

<li>Don’t miss the work of our local artists right downtown in the CSS gallery.</li>

</ul>

</p>

<p>

Having problems? You can always find answers at

<a href=”http://www.headfirstlabs.com”><em>Head First Labs</em></a>.

Still got problems? Relax, Webville’s a friendly place, just ask someone for help. And, as a local used to say:

</p>

<blockquote>

Don’t worry. As long as you hit that wire with the connecting hook at precisely 88mph the instant the lightning strikes the tower...

everything will be fine.

</blockquote>

</body>

</html>

260

Chapter 6

standards, compliance, and all that jazz

Doh! We got it
wrong – the boss wants
us to go to strict XHTML, not

HTML. Help! That’s a whole
different language isn’t it?

BULLET POINTS

n

HTML 4.01 is the HTML standard that is most

n

The <meta> tag in the <head> element tells
widely supported by browsers.

the browser additional information about a

Web page, such as the content type and

n

The World Wide Web Consortium (W3C) is
the standards organization that defines what
character encoding.

“standard HTML” is.

n

A character encoding tells the browser the
character set that is used in the Web page.

n

Many browsers have two modes for displaying

HTML: “quirks” mode for old HTML and

n

Most Western-European languages used on
standards mode for HTML 4.01.

computers today can be represented with the

ISO-8859-1 character encoding.

n

If you don’t tell the browser which version of

HTML you are using, many browsers will use

n

The W3C validator is a free online service that
quirks mode, which may cause inconsistent
checks pages for compliance with standards.

page display in various browsers.

n

Use the validator to ensure that your HTML

n

The document type definition (DOCTYPE) is
is well formed and that your elements and
used to tell the browser which version of HTML
attributes meet the standards.

your Web page is written in.

n

By adhering to standards, your pages will

n

The strict DOCTYPE is used if you are writing
display more quickly and with fewer display
fully compliant HTML 4.01.

differences between browsers.

n

Use the transitional DOCTYPE if you are
transitioning HTML that still includes display-
oriented elements and attributes.

you are here �

261

are you awake?

HTMLcross

It’s been a heck of a chapter. Go ahead and grab a cup of your favorite beverage, sit back, and strengthen those neural connections by doing this crossword. All the answers come from the chapter.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

Across

Down

3. True or false: element names should be

1. This service will check your HTML for
lowercase.

compliance with the standards.

4. Required in the <head> element.

2. In the old days of HTML, this was mixed with

6. Standards organization that supplies the

HTML structure.

validator.

5. Reason alt attribute is required.

7. When your HTML meets the standards, it is

6. Victim of the browser wars.

this.

7. The ________ encoding tells the browser which

8. Microsoft versus Netscape.

set of characters you're using.

9. The boss wanted to standardize before adding

10. DOCTYPE that expects your HTML to be fully
this to the HTML.

compliant with 4.01.

11. <img> attribute required in standard HTML.

12. If the browser can't tell what version of HTML

14. DOCTYPE that allows older HTML tags.

a page is, it uses this mode.

15. Definition that tells the browser and validator

13. Tag that tells the browser about the page.

what kind of HTML you're using.

262

Chapter 6

standards, compliance, and all that jazz

BE the Validator

Below, you’ll find an HTML

Exercise
file. Your job is to play like
you’re the validator and

Solutions
locate ALL the errors. Here’s
the solution.

<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01//EN”

“http://www.w3.org/TR/html4/strict.dtd”>

<title> should be

<html>
in the <head>.

<head>

<meta http-equiv=”Content-Type” content=”text/html; charset=ISO-8859-1”>

</head>

Inline element at top level of <body>.

<body>

<img src=”chamberofcommerce.gif”>

No alt attribute.

<h1>Tips for Enjoying Your Visit in Webville</h1>

<p>

Here are a few tips to help you better enjoy your stay in Webville.

<ul>

Block element inside a <p>.

<li>Always dress in layers and keep an html around your head and body.</li>

<li>Get plenty of rest while you’re here, sleep helps all those rules sink in.</li>

<li>Don’t miss the work of our local artists right downtown in the CSS gallery.</li>

</ul>

</p>

<p>

Having problems? You can always find answers at

<a href=”http://www.headfirstlabs.com”><em>Head First Labs</em></a>.

Still got problems? Relax, Webville’s a friendly place, just ask someone for help. And, as a local used to say:

</p>

<blockquote>

Don’t worry. As long as you hit that wire with the connecting hook at precisely 88mph the instant the lightning strikes the tower...

everything will be fine.

</blockquote>

<blockquote> only accepts block

</body>
elements directly in it.

</html>
you are here �

263

exercise solutions

Solution

1

2

V

S

3

A

T R U E

L

Y

4

5

T

I

T

L

E

A

6

D

E

W 3

C

C

A

E

C

7

T

B

C O M P

L

I A N T

E

O

D

H

S

8B R O W S E R W A R S

S

9

10

V

R

C S S

I

11

12

E

A

L

T

T

Q

B

13

M

L

C

R

U

I

14

E

O

T R A N S

I

T

I O N A

L

15

D O C

T Y

P

E

E

C

R

I

A

E

R

T

K

T

R

S

Y

Across

Down

3. True or false: element names should be

1. This service will check your HTML for
lowercase. [true]

compliance with the standards. [validator]

4. Required in the <head> element. [title]

2. In the old days of HTML, this was mixed with

6. Standards organization that supplies the

HTML structure. [style]

validator. [w3c]

5. Reason alt attribute is required. [accessibility]

7. When your HTML meets the standards, it is

6. Victim of the browser wars. [webdeveloper]

Your turn. Add the strict DOCTYPE and the <meta> tag to this. [compliant]

7. The ________ encoding tells the browser which

8. Microsoft versus Netscape. [browserwars]

set of characters you're using. [character]

“directions.html” and “elixir.html”. Try validating them – do Exercise 9. The boss wanted to standardize before adding 10. DOCTYPE that expects your HTML to be fully they validate? If not, fix them so that they do.

this to the HTML. [css]

compliant with 4.01. [strict]

11. <img> attribute required in standard HTML. [alt]

12. If the browser can't tell what version of HTML

Solution 14. DOCTYPE that allows older HTML tags.

Solution: To validate “elixir.html”,a page is, it uses this mode. [quirks]

you’l have to add the

[transitional]

13. Tag that tells the browser about the page.

alt attribute to each of your <img> elements.

15. Definition that tells the browser and validator

[meta]

what kind of HTML you're using. [doctype]

264

Chapter 6

7 moving to XHTML

Putting an ‘X’ into HTML

You mean, there’s still

MORE HTML? Doesn’t
this EVER end? When do
we get to CSS?

We’ve been keeping a dirty secret from you. We know you thought you bought an HTML book, but this is really an XHTML book in disguise. In fact, we’ve been teaching you mostly XHTML all along. You’re probably wondering, just what the heck is XHTML? Well, meet eXtensible HTML – otherwise known as XHTML – the next evolution of HTML. It’s leaner, meaner, and even more tuned for compatibility with browsers on a wide range of devices. In this short little chapter we’re going to get you from HTML to XHTML in three simple steps. So, turn the page, you’re almost there... (and then we’re on to CSS).

this is a new chapter

265

xml and html, and xhtml

This is like déjà vu.

Weren’t we standing in exactly
the same place in the last chapter,
but moving to HTML 4.01? Now we
have to move to XHTML, and I
don’t even know what that is!

Joe: I can’t believe our manager knows what it is.

Frank: Hey guys, XHTML is the new standard for

HTML. There’s not going to be an HTML 5; the new
standard is XHTML 1.0.

Jim: That’s great, but do we need to be so cutting edge?

Frank: Actually, XHTML 1.0 has been around since

2000, so it’s not as cutting edge as it sounds.

Jim: What’s the “X” for? Because it sounds cool...

X-Men, X-Games, X-Files, gen-X, and now X-HTML?

Joe

Frank: Good one, Jim, but no. The X in XHTML is for

Frank

Jim

“eXtensible,” which is another way of saying it’s based on something called XML.

Joe: Don’t the software guys use that to store some of our data?

Frank: Yup, they sure do. XML stands for eXtensible Markup Language.

Joe: Uh oh, I see some comparison to Hypertext Markup Language coming.

Frank: Yes, exactly, Joe. XML is a markup language like HTML, but you can use it to do all kinds of things beyond

“marking up” Web pages. Here, let me show you...

266

Chapter 7
moving to xhtml

What is XML?

Okay, we’re going to take a big step back, for a page or two, and look at XML (not to be confused with XHTML). This is going to be a fast ride, so hang on...

Let’s use HTML for comparison. With HTML you’re basically told what elements you can and can’t use, right? So, if you want to just make up an element, like <cool> , to wrap around content, you can’t do it, can you? Ah, but with XML, you can. If fact, you can invent totally new markup languages using XML. Let’s look at an example: Here’s the root element. It’s not called <html>, it’s called <recipe>, since this is the XML for a recipe. Notice it has some extra attributes in it, which you’ve never seen on an <html> element in HTML.

<recipe xmlns=”http://www.foodnetwerk.com/recipe” lang=”en” xml:lang=”en”>

<name> Head First Lounge Iced Tea</name> Wow, look at these tags. The

<description>

<h1>s and <p>s are all gone, and

A brisk iced tea with a bit of a kick. We
instead we’ve got <recipe>, <name>,
serve this all day long.

<description>, <ingredient>s,

</description>

<preparation>, and so on.

<ingredients>

<ingredient measurement=”6 cups”> water</ingredient>

<ingredient measurement=”2 bags”> black tea</ingredient> Just by looking at the

<ingredient measurement=”2 bags”>
element names y
earl grey tea</ingredient>
ou can

<ingredient measurement=”6 cups”>
tell this is a recipe.

ice</ingredient>

</ingredients>

This empty element looks

<preparation>
a little strange. We’ll come

<time duration=”10 minutes” />
back to that in a bit.

<step> Boil one cup of water in a pan, remove pan, and add tea. Let steep for five minutes. </step>

<step> Add ice to a pitcher, then add tea, then 5 cups cold water. </step>

<step> Mix well and serve. Give tea a
quick shake in a shaker for an
extra touch. </step>

</preparation>
brain

</recipe>

Other than the element names, the way the
power

?

elements look and are used is just like HTML

(opening tags, closing tags, and so on).

Think about how you would
create a Web page using HTML
to represent the recipe. How
would that be different from
using XML?

you are here �

267
how html relates to xhtml

What does this have to do with HTML?

If XML is a language that can be used to invent new markup languages, and HTML
is a markup language, can we use XML to recreate HTML? We sure can. Let’s see how this might look before we talk about why in the heck you’d actually want to: And here’s a DOCTYPE. You’ve seen these
before, but notice that we’re now using

XHTML 1.0, instead of HTML 4.01.

The <html> element now
has an xmlns attribute,

and lang and xml:lang

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”

attributes, like the
recipe did.

“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” lang=”en” xml:lang=”en”>

<head>

<meta http-equiv=”Content-Type” content=”text/html; charset=UTF-8” />

<title> Head First Lounge</title>

</head>

Everything here looks normal, except

<body>
the empty elements have that weird

<h1> Welcome to the New and Improved Head First Lounge</h1>

“/>” on the end again.

<p><img src=”drinks.gif” alt=”The drinks” /></p>

<p>

Join us any evening for refreshing

<a href=”elixir.html”> elixirs</a> , conversation and maybe a game or two
of <em> Dance Dance Revolution</em> .

Wireless access is always provided;

BYOWS (Bring Your Own Web Server).

</p>

But the rest of the HTML

<h2> Directions</h2>
is EXACTLY like HTML

<p>

4.01 Strict. Wow, XHTML

You’ll find us right in the center of downtown looks a lot like HTML.

Webville. If you need help finding us, check out our

<a href=”directions.html”> detailed directions</a> .

Come join us!

</p>

</body>

</html>

268

Chapter 7

moving to xhtml

I don’t get it. We changed
the DOCTYPE and added a couple
of new attributes, but the rest of
this example is totally like HTML

4.01. So, what’s the big deal?

This is going to sound very anticlimatic, but

XHTML is XML while HTML is, well, just

HTML. The big distinction may be difficult for
you to see at first glance, but the reason XML
is a good thing (and the reason the W3C and
others have gone to all the trouble of creating

XHTML, when they already had HTML) is that
once your pages are written in XHTML, all sorts
of things become possible that aren’t possible
with HTML. (You’ll get a feel for some of those
things in just a sec).

There’s another way to look at this: the
differences between HTML and XHTML can
all be seen on the previous page. You’ve got a
new DOCTYPE, and some minor changes to
attributes and the way you write empty elements.

These small changes are all that is required to
turn your HTML into XHTML.

Now that you know that moving to XHTML is
so easy, it’s time for you to get a better idea of
what it gets you.

you are here �

269

reasons to consider xhtml

So why would you want to use XHTML?

By using XHTML

I’m future-proofing my Web
pages to take advantage of all

By using HTML 4.01 Strict, you’re already reaping some of the the latest and greatest browser
benefits of XHTML. However, because XHTML is XML, it has advances to come. My pages are also
some interesting advantages beyond HTML 4.01. Let’s take a look more likely to work on mobile devices
at everything XHTML gets you, including some of the benefits and a variety of browsers.

you’re already getting out of using HTML 4.01 Strict, through the eyes of a few people already using XHTML.

XHTML’s strict
syntax allows aural
screen readers and other
browsers for the visually
impaired to more easily
consume Web content.

Hobbyist, runs a
popular gaming

Web site.

Visually impaired

Web user.

Unlike HTML, XHTML can
be extended to include new
markup. For instance, there

I like keeping up with
are already extensions that add
trends and technologies.

elements for vector graphics

XHTML is the future, and since
and mathematical formulas.

it’s almost exactly like HTML,
why not go with the better
technology?

Mathematics researcher,
large university.

Maintains her
own blog.

270

Chapter 7

moving to xhtml

XHTML is becoming the

There’s already a lot
language of choice for browsers
of data and information
on mobile devices and cell phones. In
written in XML, and it’s more
the future, XHTML is going to let
easily transformed into XHTML
us pick and choose the parts of the
than to HTML. So, we’ll be able to
language we want to support in each
get all that information on the
mobile device, as well.

Web more easily with

XHTML.

Database engineer,
media company.

Business development,
mobile phone
company.

XHTML can be read

XHTML gives us the benefits of
by our existing software

XML (which is great for storing large,
applications that already
structured document collections) along
understand how to read XML.

with the benefits of HTML, such as CSS
for creating presentation.

Librarian at major

Junior software
metropolitan library.

developer.

you are here �

271

a checklist for xhtml strict

You’re much closer to using XHTML than
you might think

Even though HTML and XHTML are almost the same, there are a few small differences, as you’ve seen. Here’s a handy checklist for moving from HTML 4.01

Strict to XHTML 1.0 Strict:

The XHTML 1.0 checklist

Here’s the list of things you must do to convert from HTML to XHTML.

❏ Change your DOCTYPE to Strict XHTML. Or, you can

We’ve checked off the
use Transitional XHTML if you’re still using Transitional
requirements that you’re

HTML.

already on top of. So,

❏
that doesn’t leave you with

Add the xmlns, lang, and xml:lang attributes to your much to do to move to

<html> opening tag.

XHTML 1.0.

❏ The <html> tag must be the first tag after the DOCTYPE
and the </html> closing tag must be the last tag in the document.

We’re going to talk

❏ All element names must be written with lowercase letters.

about what this means.

❏ All opening tags must have closing tags. Or, if an element is empty, the tag must end with a space and then /> .

❏ All attributes must have values, and those values must be surrounded by double quotes.

❏ Don’t use & in the content of your HTML. & is for starting entities, so use &amp; instead. Also convert any other special characters to entities.

If you started from scratch reading this book and you’ve been diligent in using strict HTML 4.01, then moving to XHTML 1.0 is going to be fast for you.

You really only have a few things you need to take care of, and we’ll talk about those next.

On the other hand, if you have a lot of legacy HTML you need to convert, then you may have a big job on your hands. But, even in that case, there are some tools that can help get you there. We’ll talk about those too.

272

Chapter 7

moving to xhtml

If my HTML is
transitional 4.01, and I want
to switch to XHTML strict,
then I have a little more work
to do, right?

Right. The checklist assumes
you’re already writing strict HTML.

HTML 4.01 Strict and XHTML 1.0 Strict are
basically the same. So, going from transitional

HTML 4.01 to HTML Strict or XHTML Strict is
about the same amount of work. To change your
transitional HTML to either, you’ll first need to do
all the things we mentioned in Chapter 6 to remove
presentation tags and clean up your HTML.

There is also a transitional XHTML 1.0 version,
which is essentially the same as transitional HTML

4.01. They both al ow deprecated presentational
elements, and inline elements directly in the body
of your page. So, if you want to use that instead,
remember to use the transitional XHTML 1.0

DOCTYPE instead of the strict DOCTYPE.

you are here �

273
going from html to xhtml

Going from strict HTML to XHTML 1.0 in three steps

1

Change your DOCTYPE to XHTML 1.0 Strict.

You already know all about DOCTYPEs and you’re used to seeing the HTML 4.01 Strict document type. Well, there’s also a document type for XHTML 1.0 Strict, and you need to change your DOCTYPE to use it instead. Here’s what it looks like:

Just like the HTML DOCTYPE,
this is a public document type.

It’s for the XHTML 1.0

Strict version of XHTML.

<!DOCTYPE html

PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”

“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”> And it has a URL pointing to the
definition of XHTML 1.0 Strict.

2

Add the xmlns, lang and xml:lang attributes to your <html> element.

Remember that XML can be used to define many markup languages other than XHTML. To keep all those languages straight, XML needs to know which language you’re talking about when you use the element <html> (after all, someone could come along and make up their own language with XML
and call it the “Hippo Tipping Markup Language,” which would cause mass confusion). So, to keep things straight, the xmlns attribute specifies which language the <html> element belongs to. And what about all the rest of the elements inside the <html> element? By default, they inherit the xmlns attribute of their parent.

The <html> element also needs lang and xml:lang attributes, which specify the language being used in the XML document. Here’s what your

<html> opening tag should look like in XHTML:

<html xmlns=”http://www.w3.org/1999/xhtml” lang=”en” xml:lang=”en”> The xmlns attribute is used t

And we just need to specify
o
identify which XML l

XML uses a URL as a unique identifier for a
that we’re using English.

anguage

“html” belongs t
language. If someone has written a “Hippo Tipping
o.

Depending on the way your

Markup Language” they might have used “http://www. XHTML is interpreted by the hippotipping.com/html” as their identifier. It doesn’t
browser, you may need either
matter what is at the URL - the URL alone is
one of these, so it’s best
enough to make it unique.

practice to use both.

274

Chapter 7
moving to xhtml

3

All empty tags should end in “ />”, not “>”.

This is the final, and most bizarre step of the HTML to XHTML 1.0
transformation. But it’s not so mysterious if you know the background.

We’ve told you XHTML is stricter than HTML, and one area where it is stricter is with closing tags. In HTML, you can have an empty element without a closing tag. But in XHTML, if you aren’t going to have a closing tag, you have to tell the browser about it by putting a slash before the final

“>”. So, take the <br> element as an example. In HTML we just write

<br> . But in XHTML, we write <br/> . That little slash on the end tells the browser it shouldn’t expect a closing tag, because the <br/> is all there is.

Now you might have noticed we didn’t include a space before the “/>”.

That’s because XHTML doesn’t require it. However, some older browsers can’t recognize “/>” without a space before the slash, so, to be backwards compatible, just put a space before your slash in “ />”.

Let’s look at a couple of examples so you know how to transform HTML
empty elements into XHTML empty elements:

Old school HTML 4.01 Strict

<br>

<img src=”drinks.gif” alt=”Drinks”>

No closing tags? No
problem in HTML.

New and improved XHTML 1.0

<br />

<img src=”drinks.gif” alt=”Drinks” />

But with XHTML we gotta
declare our intentions. If y

And, give those older
our
element is empty, let the
browsers a break by
browser know by putting a “/”

inserting a space before
before the ending “>”.

the forward slash.

you are here �

275

root elements and namespaces

You’re going to take Tony’s journal (remember him from Chapter 3?) and convert it to XHTML. We already cleaned up his code and changed it to HTML 4.01 Strict for you – we nested his <img> elements inside <p> elements and added alt at ributes, Exercise put his Burma Shave slogan in a <p> element, and added a <meta> tag. You’l find this HTML 4.01 Strict version of “journal.html” in the “chapter7/journal” folder.

Here’s what you need to do:

1

Change your DOCTYPE from HTML 4.01 Strict to XHTML 1.0 Strict.

2

Add the xmlns, lang and xml:lang attributes to your <html> opening tag.

3

Change the ending “>” characters on your empty elements to “ />”.

4

Save, and reload the page in your browser.

Be sure to check your work at the end of the chapter.

there are no

Dumb Questions

Q: Can you explain the xmlns

Q: But wait, that’s a URL, not an Q: You mentioned some tools earlier attribute a bit more; I feel like I missed
identifier.

that could help convert my HTML to
something.

XHTML.

A:

A: Yeah, XML people are weird that

You’re not the only one. This is one
way. It may look like a URL to you, but just

A: Yes, there’s a great litle tool caled
of the most confusing parts of XML. Okay,
think of it as something that is supposed to

Tidy that can do much of the work to get
it works like this: lots of people can create
be unique. The idea is that you could visit
your HTML documents validating and ready

XML languages (personal y, we say get out
that URL and find out something about the
for XHTML. Tidy has a number of options
and see the world, but some people seem
language, although there is no requirement
and can take nonvalidating HTML and
to be into this sort of thing). Let’s say two
that anything actually exist at the URL.

perform many of the tasks needed to make
people cal their elements the same thing.

HTML validate. It can also remove a fair

Take the name <table>, for instance. For

Q:

amount of legacy presentational HTML and
some people this is an element in HTML;

If this is XHTML, how come the
replace it with CSS. You can find Tidy at
for others, it’s part of an XML language for
root element isn’t <xhtml> rather than
http://tidy.sourceforge.net.

furniture. So, if you use <table> in your XML, <html>?

how do we know which one you mean?

Q:

That’s where the xmlns at ribute comes in.

So if I have strict HTML, this is

The xmlns attribute holds a unique identifier

A: Because XHTML is meant to be really all I have to do to move to XHTML?

that determines which language you mean.

backwards compatible with HTML. If they

In the case of XHTML, that identifier is
changed the root element to <xhtml> then
http://www.w3.org/1999/xhtml
older browsers wouldn’t know how to display A: That’s right. In fact, let’s give your pages.

it a try...

276

Chapter 7

moving to xhtml

Validation: it’s not just for HTML

We’re totally up
on the new XHTML

After Chapter 6, you’re an expert at using the W3C validator, and you’ll standards and ready to
find the validator is up to date and ready to validate your XHTML. You enforce them.

do that in exactly the same way that you validated HTML.

Go to validator.w3.org and either paste
in your XHTML, upload it, or point the
validator to your URL.

The validator will check
your XHTML and report
that it’s valid, or report

Validator
any errors to you.

there are no

Q: Dumb Questions

How does the validator know whether

I’m validating HTML or XHTML? After al , this
is the same page I used for HTML.

A: The validator looks at your DOCTYPE
declaration, which states that the document is
either XHTML Transitional or XHTML Strict, and
that’s what it bases its validation on.

you are here �

277

validating xhtml

You didn’t think we’d let you of the hook
without validating your XHTML did you?

Exercise Validate the “lounge.html” file in the

“chapter7/lounge” folder, and the

“journal.html” file in the “chapter7/journal/”

folder (the one you turned into XHTML a
couple of pages ago) at the W3C. If you
see any errors, check your typing, get
them fixed, and try again.

Congratulations,
you’ve just written

your first XHTML!

You’ve done it: you’ve transitioned
your HTML over to XHTML. While
your markup doesn’t look much different,
there’s a whole new set of possibilities
coming down the road for XHTML
documents. And, even better, you’ve
adopted a whole technology that isn’t that
much different from what you already know. Now’s
the time you can go tell all your friends you’re already using XHTML (we won’t tell them there isn’t much of a difference between HTML and XHTML if you don’t).

Oh, and if we haven’t said so already, XHTML is just
as compatible with CSS for styling, and you’re just a few
pages from adding your first style to an XHTML page.

278

Chapter 7

moving to xhtml

XHTML sounds like a
good thing. Is it really
ready for prime time?

XHTML does seem like a good thing, and moving from HTML 4.01

Strict is almost trivial, so, why not just go for it? But, before you do, you should know that XHTML is still a little ahead of the curve in terms of browser support. So, while you can use XHTML today, there are a few issues you need to keep in mind.

Right now the biggest problem you’re going to encounter is that while you might be using XHTML, some browsers are still going to treat your pages as HTML. In most cases, this is fine, because XHTML is designed to be backwards compatible with HTML. However, in the worst case, a browser may display your XHTML in the dreaded quirks mode (look back at Chapter 6 if you’ve forgotten about quirks mode), so you could get some inconsistent display of your XHTML. What to do? Well, the best you can do right now is test your XHTML in a variety of browsers to make sure things are working as you expect.

If browsers are
just going to treat
my XHTML like HTML,
then why should I bother
writing XHTML? Seems
like a waste of time
to me.

It really comes down to whether or not the XML benefits
of XHTML are meaningful to you. If they are, you
can start using XHTML today – just be diligent about
validating so that in the future, when real, strict XHTML
browsers emerge, your pages will play well with them.

(Because XHTML browsers are strict, they won’t accept
invalid XHTML.)

HTML has a long life ahead of it, so if you don’t have
a good reason to switch, you can stick with HTML for a
while. And, if you use HTML 4.01 Strict and validate
your pages, you’ll be ready to switch to XHTML at a
moment’s notice.

you are here �

279

html versus xhtml

Tonight’s talk: HTML and XHTML
ask for your support.

HTML

XHTML

I’m certainly glad to have the opportunity to
persuade you to stick with me: HTML 4.01. I’m
going to be around a long time, have no worries
there.

HTML, face it, you’re yesterday’s news. The
standards guys have already moved on. I’m
the future. Anyone with their head on straight
should be moving to XHTML.

There’s really just not enough difference between
you and me for people to really care. I mean, 4.01
is exactly the same as XHTML 1.0.

How can you say we’re the same? You’re

HTML; I’m XML.

And right now, that and a quarter won’t
even get you a cup of coffee.

Ah, but just wait. The number of devices that
read XHTML is increasing every day. And
there are a lot of applications out there that
are gearing up to use XHTML.

That’s the problem: you think everyone wants to
have applications using XHTML, or that everyone
is creating Web sites for mobile devices. Some
people just wanna make good Web sites. Why are
you asking them to go through all this pain?

Well that’s just it – there really is no pain.

If you’re already using HTML 4.01, then

XHTML is just a hop, skip, and jump away.

All you have to do is change your DOCTYPE,
and add a couple of attributes to your <html>
element. So, what’s the big deal? Why not have
the latest and greatest with just a few minutes
work?

280

Chapter 7
moving to xhtml

HTML

XHTML

You’re forgetting a few of the downsides. A lot
of browsers don’t handle XHTML very well. In
fact, they just see it as HTML. So you do all that
work and then you’re just fooling yourself that your

XHTML is somehow different.

Hey, that’s a good thing. The designers of

XHTML knew that not all browsers would
support XHTML, so they made it backwards
compatible. In other words, you can move to

XHTML today, and still have it all work even
on older browsers.

But what’s the point? If your XHTML is just
considered HTML by a browser, then it’s just

HTML!

Ah, but that’s changing; more and more
support for XHTML is arriving every day. So,

I say, go ahead and change over. It’s easy, and
when the new browsers and devices get here,
you’ll be ready without even trying.

This is all great, but I keep saying people just don’t
care. I’m already good enough for them. Lots of
people have no need for XML.

You can’t envision all the ways XHTML is
going to be used in the future. XHTML is the
way, and by moving to XHTML now, you’ll be
ready.

Okay; let’s say you’re right, and XHTML is going
to be the way of the future. Fine. But as you also
said, XHTML is just a hop, skip, and a jump away.

So, my users can just wait until XHTML gets here,
and they can hop, skip, and jump then.

What’s that saying? “You can’t teach an old
dog a new trick?”

I think you mean “You can lead a horse to
water...”

you are here �

281

making a decision between html and xhtml

HTML or XHTML? The choice is yours...

Do any of the advantages of XHTML matter to you? Are you
translating existing XML into HTML for the Web? Are you working on pages that you need to display well on mobile devices? Are some of the newer XHTML technologies going to be important to you in the near future? Or, do you just want to be on the cutting edge? Well, we have good news: you can move to XHTML today. All it will cost you is a new DOCTYPE and some minor changes to a couple of tags.

Now, not every browser will give you credit for moving
to XHTML, but sooner or later they will have to, and,
until they do, your pages wil display just fine because
the browser wil treat them as HTML (although, don’t forget the caveat we already mentioned). So, bon voyage, and enjoy your journey to XHTML.

None of that is important to you? You’re mainly concerned with making great Web pages? We have good news for you, too: you can easily stick with HTML 4.01 Strict and reap all the rewards of using the browser’s current choice of languages. And, should you ever feel the need to upgrade to XHTML, then you can follow the three-step program outlined in this chapter to get you there.

So, no matter what your choice is, you’ve made an excellent one, and we wish you the best. That said, the differences between HTML
and XHTML are really minimal, so why not go ahead and move to XHTML? We have, and in the rest of this book we’ll be using XHTML

1.0. If, for some reason, you need to stick with HTML 4.01, that’s fine.

And in fact, since they really are basically the same, you’ll have no problems with the rest of the book. Just make sure you’re using the right DOCTYPE for whichever version you’re using.

282

Chapter 7

moving to xhtml

Micro XHTMLcross

It’s been a small chapter (aren’t you glad!). Here’s a Micro XHTMLcross for you.

1

2

3

4

5

6

7

8

9

Across

Down

1. Used to double check your XHTML.

2. XHTML requires additional ______ in the <html>

6. XHTML is this type of markup.

element.

8. Use these for special characters.

3. The X in XHTML is for _________.

9. We invented an XML language for these.

4. In XHTML you have to explicitly have _____
tags.

5. In XHTML all element names must be this.

7. These kinds of devices are adopting XHTML.

you are here �

283

exercise solutions

Micro XHTMLcross Solution

It’s been a small chapter (aren’t you glad!). Here’s a Micro XHTMLCross for you.

1

2

V A

L

I

D A

T O

R

T

3

T

E

4

R

C

X

5L

I

L

T

O

B

O

E

6

7

X M L

W

U

S

N

8

O

E N

T

I

T

I

E

S

B

R

E

N

I

I

C

S

G

B

L

A

L

9R E C I P E S

E

E

You’re going to take Tony’s journal (remember him from

Across

Down
chapter 3?) and convert it to XHTML. We’ve put the most

1. Used to double check your XHTML. [validator]

2. XHTML requires additional ______ in the <html>

6. XHTML is this type of markup. [xml]

Exercise recent version of the journalelement. [attributes]

in the “chapter7/journal” folder,

8. Use these for special characters. [entities]

3. The X in XHTML is for _________. [extensible]

where you’ll find an HTML 4.01 strict version of “journal.html”.

9. We invented an XML language for these.

4. In XHTML you have to explicitly have _____

Solutions

[recipes]

tags. [closing]

Here’s the solution:

5. In XHTML all element names must be this.

[lowercase]

7. These kinds of devices are adopting XHTML.

[mobile]

Change the DOCTYPE to

XHTML 1.0 Strict.

<!DOCTYPE html

Add the three

PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”

attributes to the

<html> opening tag.

“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” lang=”en” xml:lang=”en”>

<head>

<meta http-equiv=”Content-Type” content=”text/html; charset=ISO-8859-1” />

<title>My Trip Around the USA on a Segway</title> The <meta> tag needs

.

Don’t forget to put “ />” in
a “ />”, too.

.

your empty elements.

.

</body>

</html>

284

Chapter 7

8 getting started with CSS

Adding a Little Style

Don’t get me wrong, the
hair, the hat, it al looks great.

But don’t you think he’d like it
if you spent a little more time
adding some style to your

XHTML?

I was told there’d be CSS in this book. So far you’ve been concentrating on learning XHTML to create the structure of your Web pages. But as you can see, the browser’s idea of style leaves a lot to be desired. Sure, we could call the fashion police, but we don’t need to. With CSS, you’re going to completely control the presentation of your pages, often without even changing your XHTML.

Could it really be so easy? Well, you are going to have to learn a new language; after all, Webville is a bilingual town. After reading this chapter’s guide to learning the language of CSS, you’re going to be able to stand on either side of Main Street and hold a conversation.

this is a new chapter

285

Remember the Wizard of Oz? Well, this
is the part of the book where things go
from black & white to color.

You’re not in Kansas anymore

You’ve been a good sport learning about markup
and structure and validation and proper syntax and
nesting and compliance, but now you get to really
start having some fun by styling your pages. But no worries, all those XHTML pushups you’ve been
doing aren’t going to waste. In fact, you’re going to
see that a solid understanding of XHTML is crucial
to learning (and using) CSS. And, learning CSS is
just what we’re going to do over the next several
chapters.

Just to tease you a bit, on these two pages we’ve
sprinkled a few of the designs you’re going to work
with in the rest of the book. Quite a difference from
the pages you’ve been creating so far, isn’t it? So,
what do you need to do to create them? Learn the
language of CSS of course.

Let’s get started...

286

Chapter 8

getting started with css
you are here �

287

the css language

Overheard on Webville’s “Trading Spaces”

Not up on the latest reality TV? No problem, here’s a recap: take two neighbors, two homes, and $1,000. The two neighbors switch homes, and using the $1,000, totally redesign a room or two in 48 hours. Let’s listen in...

. .and this bathroom needs
some serious help!

Okay, let’s get some design in this place...

bathroom {
bedroom {
tile: 1in white;
drapes: blue;
drapes: pink;
carpet: wool shag;

}

}

Of course, in the Webville edition of the show, everyone talks about design in CSS. If you’re having trouble understanding them, here’s a little translation tip: each statement in CSS consists of a location (like bedroom), a property in that location (like drapes, or carpet), and a style to apply to that property (like the color blue, or 1 inch tiles).

288

Chapter 8
getting started with css

Using CSS with XHTML

We’re sure CSS has a bright future in the home design category, but let’s get back to XHTML. XHTML doesn’t have rooms, but it does have elements and those elements are going to be the locations that we’re styling. Want to paint the walls of your <p> elements red? No problem; only paragraphs don’t have walls, so you’re going to have to settle for the paragraph’s background-color property instead. Here’s how you do that: The first thing you do is select the

Then you specify the property you
element you want to style, in this case
want to style, in this case the <p>
the <p> element. Notice in CSS, you
element’s background color.

don’t put <> around the name.

And you’re going to set the
p {
background-color to red.

background-color: red;

}

At the end,
put a semicolon.

Place all the styles

There’s a colon in between the
for the <p> element in
property and its value.

between { } braces.

We call the whole

You could also write the rule like this:

thing a RULE.

p { background-color: red; }

Here, all we’ve done is remove the linebreaks. Like XHTML, you can format your CSS pretty much as you like. For longer rules you’ll usually want to add some linebreaks and indenting to make the CSS more readable (for you).

Wanna add more style?

You can add as many properties and values as you like in each CSS rule. Say you wanted to put a border around your paragraphs, too. Here’s how you do that: p {

All you have to do is add
background-color: red;
another property and value.

border: 1px solid gray;

}

The <p> element
will have a border...

...that is 1 pixel thick, solid, and gray.

you are here �

289
more about css and xhtml
there are no

Dumb Questions

Q: Does every <p> element have the same
style? Or can I, say, make two paragraphs
different colors?

A: The CSS rules we’ve used so far define
the style for all paragraphs, but CSS is very
expressive: it can be used to specify styles in lots
of dif erent ways, for lots of dif erent elements
brain

– even subsets of elements. You’l see how to
power
make paragraphs two dif erent colors later in this

?

chapter.

Say you have an <em> element
inside a paragraph. If you change the

Q: How do I know what properties I can set
background color of the paragraph, do
on an element?

you think you also have to change the
background of the <em> element so it
matches the background color of the

A: Well, there are lots of properties that can
paragraph?

be set on elements, certainly more than you’d
want to memorize, in any case. You’re going to get
quite familiar with the more common properties in
the next few chapters. You’ll probably also want
to find a good CSS reference. There are plenty
of references online, and O’Reilly’s CSS Pocket

Referenc e is a great little book.

Q: Remind me why I’m defining al this
style in a separate language, rather than in

XHTML. Since the elements are written in

XHTML, wouldn’t it be easier just to write style
in XHTML, too?

A: You’re going to start to see some big
advantages to using CSS in the next few chapters.

But, here’s a quick answer: CSS really is better
suited for specifying style information than XHTML.

Using just a smal bit of CSS, you can create fairly
large effects on the style of your XHTML. You’re
also going to see that CSS is a much bet er way
to handle styles for multiple pages. You’l see how
that works later in this chapter.

290

Chapter 8

getting started with css

Getting CSS into your XHTML

Okay, you know a little about CSS syntax now. You know how to select an element and then write a rule with properties and values inside it. But you still need to get this CSS into some XHTML. First, we need some XHTML to put it in. In the next few chapters, we’re going to revisit our old friends – Starbuzz, and Tony and his Segway journal – and make things a little more stylish. But, who do you think is dying to have their site styled first? Of course, the Head First Lounge guys. So, here’s the XHTML for the Head First Lounge main page. Remember, in the last chapter we fixed things up a little and made it But not necessarily the best
strict XHTML (would you have expected any less of us?). Now, we’re adding way. We’ll come back to this
some style tags, the easiest way to get style into your pages.

later in the chapter and see
another way.

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”

“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” lang=”en” xml:lang=”en” >

<head>

<meta http-equiv=“Content-Type” content=”text/html; charset=ISO-8859-1” />

<title> Head First Lounge</title> Here’s what we’re interested in: the <style> element.

<style type=”text/css”>

To add CSS style directly to your XHTML, add
opening and closing style tags in the <head> element.

And a style type of “text/css”.

</style>

And your CSS rules are

</head>
going to go right in here.

<body>

<h1> Welcome to the Head First Lounge</h1>

<p>

<img src=“images/drinks.gif” alt=“Drinks” />

</p>

<p>

Join us any evening for refreshing

<a href=“beverages/elixir.html”> elixirs</a> , conversation and maybe a game or two
of <em> Dance Dance Revolution</em> .

Wireless access is always provided;

BYOWS (Bring your own web server).

</p>

<h2> Directions</h2>

<p>

You’ll find us right in the center of downtown

Webville. If you need help finding us, check out our

<a href=“about/directions.html”> detailed directions</a> .

Come join us!

</p>

</body>

</html>
you are here �

291
adding a style to the lounge

Adding style to the lounge

Now that you’ve got the <style> element in your XHTML, you’re going to add some style to the Lounge to get a feel for writing CSS. This design probably won’t win you any “design awards,” but you gotta start somewhere.

The first thing we’re going to do is change the color (something to match those red lounge couches) of the text in the paragraphs. To do that, we’ll use the CSS
color property like this:

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”

“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” lang=”en” xml:lang=”en”>

<head>

<meta http-equiv=“Content-Type”

Here’s the rule content=”text/html; charset=ISO-8859-1” /> that is going to <title> Head First Lounge</title> specify the font <style type=”text/css”>

The property to change the font color is
color of the
named “color” (you might think it would be
paragraphs.

“font-color” or “text-color”, but it’s not).

p {
color: maroon;

We’re selecting just }

We’re setting the text to a lovely
the <p> element to
maroon color that happens to
apply this style to.

match the lounge couches.

</style>

</head>

<body>

<h1> Welcome to the Head First Lounge</h1> The p selector

<p>
selects all the

<img src=“images/drinks.gif” alt=“Drinks” /> paragraphs in the

</p>

XHTML.

<p>

Join us any evening for refreshing

<a href=“beverages/elixir.html”> elixirs</a> , conversation and maybe a game or two
of <em> Dance Dance Revolution</em> .

Wireless access is always provided;

BYOWS (Bring your own web server).

</p>

<h2> Directions</h2>

<p>

You’ll find us right in the center
of downtown Webville. If you need
help finding us, check out our

<a href=“about/directions.html”> detailed directions</a> .

Come join us!

</p>

</body>

</html>

292

Chapter 8

getting started with css

Cruising with style: the test drive

Go ahead and make all the changes from the last couple of
pages to your “lounge.html” file in the “chapter8/lounge” folder, save, and reload the page in your browser. You’ll see that the paragraph text color has changed to maroon:

Everything else is
as it should be: the
headings are still black,
because all we selected
to style were the <p>

Here’s our
elements.

new maroon
paragraph text.

Notice that the color of
the links didn’t change.

Keep that in the back of
your mind...

brain
power

?

Instead of setting the color, what if you set background-color of the <p> elements to maroon instead? How would it change the way the browser displays the page?

you are here �

293

styling headings

Style the heading

How about a different

Now let’s give those headings some style. How about changing the font for the Lounge
headings? Make them really
font a bit? Let’s change both the type of font, and also the color of stand out. I’m seeing big,
the heading fonts:

clean, gray...

h1 {

Here’s the rule to select <h1>
elements and change the
font-family: sans-serif;
color: gray;
font-family to sans-serif

}

and the font color to gray.

We’ll talk a lot more about
h2 {
fonts later.

font-family: sans-serif;
color: gray;

And here’s another rule t

}

o do
the exact same thing to the
p {

<h2> element.

color: maroon;

}

Actually, since these rules are exactly the same, we can combine them, like this:

To write a rule for more than one
element, just put commas between
h1, h2 {
font-family: sans-serif;
the selectors, like “h1, h2”.

color: gray;

}

p {
color: maroon;

}

Test drive...

Add this new CSS to your “lounge.html” file
and reload. You’ll see that with one rule, you’ve
selected both the <h1> and <h2> headings.

Both of the headings on
the page are now styled
with a sans-serif font
and colored gray.

294

Chapter 8

getting started with css

Let’s put a line under the welcome message too

Let’s touch up the welcome heading a bit more. How about a line under it?

That should set the main heading apart visually and add a nice touch. Here’s the property we’ll use to do that:

border-bottom: 1px solid black;

This property controls how the
border under an element looks.

We’re going to style the bottom
border so that it is a 1 pixel
thick, solid black line.

The trouble is, if we add this property and value to the combined “h1, h2”

rule in our CSS, we’ll end up with borders on both our headings: h1, h2 {

Here we’re adding a property to
font-family: sans-serif;
color: gray;
change the bottom border for
border-bottom: 1px solid black;
both the <h1> and <h2> elements.

}

p {
color: maroon;

}

If we do this...

... we get bottom borders on both
our headings. Not what we want.

So, how can we set the bottom border
on just the <h1> element, without
affecting the <h2> element? Do we
have to split up the rules again? Turn the
page to find out...

you are here �

295

getting more sophisticated with selectors

We have the technology: specifying a
second rule, just for the <h1>

We don’t have to split the “h1, h2” rule up, we just need to add another rule that is only for “h1” and add the border style to it.

h1, h2 {

The first rule stays the same. We’re
font-family: sans-serif;
still going to use a combined rule
color: gray;
for the font-family and color for

}

both <h1> and <h2>.

h1 {

But now w
border-bottom: 1px solid black;
e’re adding a second rule
that adds another prop

}

erty just to

<h1>: the border-bottom property.

p {
color: maroon;

}

Another test drive...

Change your CSS and reload the page. You’ll see that the new rule added a black border to the bottom of the main heading, which gives us a nice underline on the heading and really makes it stand out.

Here’s the bottom
border in black.

And no border
here, just what we
wanted.

296

Chapter 8
getting started with css
there are no

Dumb Questions

Q: So how does that work when you Q: What’s the advantage of that A: Good question. There is an
have more than one rule for an element?

approach? Isn’t it better to organize each
underline style for text and we could use
element separately, so you know exactly
that instead. However, the two styles have

A:

what styles it has?

slightly dif erent ef ects on the page: if you

You can have as many rules as
use border-bot om then the line wil extend
you want for an element. Each rule adds to
to the edge of the page. An underline is only
the style information of the rule before it.

A: Not at al. If you combine common shown under the text itself. The property to In general, you try to group together al the
styles together, then if they change, you
set text underline is called text-decoration
common styles between elements, like we
only have to change them in one rule. If you
and has a value of “underline” for underlined
did with <h1> and <h2>, and then any style
break them up, then there are many rules
text. Give it a try and check out the
that is specific to an element, you write in
you have to change, which is error-prone.

differences.

another rule, like we did with the border-
bottom style for the main heading.

Q: Why do we use a bottom border
to underline text? Isn’t there an underline
style for text?

So, how do selections really work?

You’ve seen how to select an element to style it, like this: We call this the selector.

h1 {

The style is applied to the elements

color: gray;
described by the selector - in this

}

case, <h1> elements.

Or, how to select more than one element, like this:

Another selector. The style is applied to <h1> and <h2> elements.

h1, h2 {

color: gray;

}

You’re going to see that CSS allows you to specify all kinds of selectors that determine which elements your styles are applied to. Knowing how to use these selectors is the first step in mastering CSS, and to do that you need to understand the organization of the XHTML that you’re styling. After all, how can you select elements for styling if you don’t have a good mental picture of what elements are in the XHTML, and how they relate to one another?

So, let’s get that picture of the Lounge XHTML in your head, and then we’ll dive back into selectors.

you are here �

297

drawing the lounge’s structure

Markup Magnets

Like this.

html

Remember drawing the diagram of HTML elements in Chapter 3?

You’re going to do that again for the Lounge’s main page. Below, head
body
you’ll find all the element magnets you need to complete the diagram. Using the Lounge’s XHTML (on the right), complete the title
p
tree below. We’ve done a couple for you already. You’ll find the answer in the back of the chapter.

q
html
title
img
h1
body
p
a
p
p
h2
meta
head
a
style
em

298

Chapter 8
getting started with css

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”

The Head First

“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”> Lounge XHTML.

<html xmlns=”http://www.w3.org/1999/xhtml” lang=”en” xml:lang=”en”>

<head>

<meta http-equiv=“Content-Type” content=”text/html; charset=ISO-8859-1” />

<title> Head First Lounge</title>

<style type=“text/css”>
h1, h2 {

font-family: sans-serif;

color: gray;

}

h1 {

border-bottom: 1px solid black;

}

p {

color: maroon;

}

</style>

</head>

<body>

<h1> Welcome to the Head First Lounge</h1>

<p>

<img src=“images/drinks.gif” alt=“Drinks” />

</p>

<p>

Join us any evening for refreshing

<a href=“beverages/elixir.html”> elixirs</a> , conversation and maybe a game or two
of <em> Dance Dance Revolution</em> .

Wireless access is always provided;

BYOWS (Bring your own web server).

</p>

<h2> Directions</h2>

<p>

You’ll find us right in the center of downtown

Webville. If you need help finding us, check out our

<a href=“about/directions.html”> detailed directions</a> .

Come join us!

</p>

</body>

</html>
you are here �

299

visual selectors

Seeing selectors visually

We can only style
elements in the body,

Let’s take some selectors and see how they map
so we’re not showing
to the tree you just created. Here’s how this “h1”

the <head> element
selector maps to the graph:

and everything under it.

html
h1 {
head
body
font-family: sans-serif;

}

h1
p
p
h2
p

This selector matches any
img
a
em
a

<h1> elements in the page, and
there’s only one.

And here’s how the “h1, h2” selector looks:

html
h1, h2 {
body
font-family: sans-serif;

}

h1
p
p
h2
p
img
a
em
a

Now the selector
matches both <h1> and

<h2> elements.

If we use a “p” selector, here’s how that looks:

html
p {
body
font-family: sans-serif;

}

h1
p
p
h2
p

This selector matches all the
img
a
em
a

<p> elements in the tree.

300

Chapter 8

getting started with css

Sharpen your pencil

Color in the elements that are selected by these selectors: p, h2 {
font-family: sans-serif;

}

html
body
h1
p
p
h2
p
img
a
em
a
p, em {
font-family: sans-serif;

}

html
body
h1
p
p
h2
p
img
a
em
a
you are here �

301

winning with css

The Case of Brute Force versus Style

When we last left RadWebDesign in Chapter 4, they had just blown the corporate demo and lost RobotsRUs’ business. CorrectWebDesign was put in charge of the entire RobotsRUs site and got to work getting everything nailed down before the site launch later in the month. But, you’ll also remember that RadWebDesign decided to bone up on their XHTML & CSS. They decided to rework the RobotsRUs site on their own, using strict XHTML and style sheets, just to get some experience under their belt before they took on another consulting job.

Five-Minute

As fate would have it, just before RobotsRUs’ big site launch, it happened again: RobotsRUs called CorrectWebDesign with

Mystery
an urgent message. “We’re changing our corporate look and
we need all the colors, backgrounds, and fonts changed on our site.” At this point, the site consisted of almost a hundred pages, so CorrectWebDesign responded that it would take them a few days to rework the site. “We don’t have a few days!” the CEO said. Desperate, the CEO decided to cal in RadWebDesign for help. “You flubbed up the demo last month, but we really need your help. Can you help the CorrectWebDesign guys convert the site over to the new look and feel?”

RadWebDesign said they could do better than that; in fact they could deliver the entire site to them in less than an hour.

How did RadWebDesign go from disgrace to Web page
superheroes? What allowed them to change the look and feel of
a hundred pages faster than a speeding bullet?

302

Chapter 8

getting started with css

Uh, I think you
forgot to style the elixirs
and directions pages?

Getting the Lounge style into the
elixirs and directions pages

It’s great that we’ve added all this style to “lounge.html”, but what about

“elixir.html” and “directions.html”? They need to have a look that is consistent with the main page. Easy enough... just copy the style element and all the rules into each file, right? Not so fast. If you did that, then whenever you needed to change the style of the site, you’d have to change every single file – not what you want. But, luckily, there is a better way. Here’s what you’re going to do:

1

Take the rules in “lounge.html” and place
them in a file called “lounge.css”.

2

Create an external link to this file from your

“lounge.html” file.

3

Create the same external links in “elixir.html”

and “directions.html”.

4

Give all three files a good test drive.

you are here �

303

creating a css file

Creating the “lounge.css” file

You’re going to create a file called “lounge.css” to contain the style rules for all your Head First Lounge pages. To do that, create a new text file named “lounge.css” in your text editor.

Create “lounge.css” in

<html>

.

.

the “lounge” folder (the

.

</html>
root folder).

lounge.html
lounge

We often call CSS
h1, h2 {
files “style sheets”.

fon
col

}p {
lounge.css
green.jpg

<html>

<html>

.

.

about
beverages
images

.

.

blue.jpg

.

.

</html>

</html>
drinks.gif
directions.html
elixir.html
lightblue.jpg
red.jpg

Now type, or copy and paste from your “lounge.html” file, the CSS rules into the “lounge.css” file. Delete the rules from your “lounge.html” file while you’re at it.

Note that you should not copy the <style> and </style> tags because the “lounge.css” file contains only CSS, not XHTML.

h1, h2 {
font-family: sans-serif;
color: gray;

}

Your “lounge.css” file should
look like this. Remember, no
h1 {

<style> tags!

border-bottom: 1px solid black;

}

p {
color: maroon;

}

304

Chapter 8

getting started with css

Linking from “lounge.html” to the external style sheet

Now we need a way to tell the browser that it should style this page with the styles in the external style sheet. We can do that with an XHTML element called <link> . Here’s how you use the <link> element in your XHTML:

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”

“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” lang=”en” xml:lang=”en”>

<head>

<meta http-equiv=“Content-Type”

Here’s the XHTML that links
content=”text/html; charset=ISO-8859-1” />
to the external style sheet.

<title> Head First Lounge</title>

<link type=”text/css” rel=”stylesheet” href=”lounge.css” />

<style type=”text/css”>

</style>

You don’t need the <style> element

</head>
any more - just delete it.

<body>

<h1> Welcome to the Head First Lounge</h1>

<p>

<img src=“drinks.gif” alt=“Drinks” />

</p>

.

.

The rest of the XHTML is the same.

.

</p>

</body>

</html>

XHTML Up Close

Let’s take a closer look at the <link> element since you haven’t seen it before: And the style s

Use the link element

The type of this information is
heet is located
at this href (in this case w
to “link in” external

“text/css”. In other words, a
e’re
using a relativ
information.

CSS style sheet.

e link, but it could
be a full-blown URL).

<link type=”text/css” rel=”stylesheet” href=”lounge.css” /> The rel attribute specifies the relationship between

<link> is an
the XHTML file and the thing you’re linking to. We’re
empty element.

linking to a style sheet, so we use the value “stylesheet”.

you are here �

305
creating an external link

Linking from “elixir.html” and “directions.html”

to the external style sheet

Now you’re going to link the “elixir.html” and “directions.html” files just as you did with “lounge.html”. The only thing you need to remember is that

“elixir.html” is in the “beverages” folder, and “directions.html” is in the

“about” folder, so they both need to use the relative path “../lounge.css”.

So, all you need to do is add the following <link> element to both files:

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”

“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” lang=”en” xml:lang=”en”>

<head>

<meta http-equiv=“Content-Type” content=”text/html; charset=ISO-8859-1” />

<title> Head First Lounge Elixirs</title>

<link type=”text/css” rel=”stylesheet” href=”../lounge.css” />

</head>

<body>

.

This is “elixir.html”. Just add the <link> line.

.

.

</body>

</html>

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”

“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” lang=”en” xml:lang=”en”>

<head>

<meta http-equiv=“Content-Type” content=”text/html; charset=ISO-8859-1” />

<title> Head First Lounge Directions</title>

<link type=”text/css” rel=”stylesheet” href=”../lounge.css” />

</head>

<body>

.

Same for “directions.html”. Add the <link> line her

.

e.

.

</body>

</html>

306

Chapter 8

getting started with css

Test driving the entire lounge...

Save each of these files and then open

“lounge.html” with the browser. You should
see no changes in its style, even though the
styles are now coming from an external file.

Now click on the “elixirs” and “detailed
directions” links.

Wow! We have a whole new style for the

Elixirs and Directions pages with only a one
line change to the HTML in each file! Now
you can really see the power of CSS.

you are here �

307

use css for flexibility

The Case of Brute Force versus Style

So, how did RadWebDesign become Web page superheroes?

Or, maybe we should first ask how the “do no wrong”

CorrectWebDesign firm flubbed things up this time? The root of the problem was that CorrectWebDesign was creating the

RobotsRUs pages using circa 1998 techniques. They were
putting their style rules right in with their HTML

(copying and pasting them each time), and, even
worse, they were using a lot of old HTML elements

Five-Minute
like <font> and <center> that have now been deprecated. So, when the call came to change the

Mystery
look and feel, that meant going into every Web page and making changes to the CSS. Worse, it meant going
through the HTML to change elements as well.

Solved

Compare that with what RadWebDesign did: they used strict

XHTML 1.0, so they had no old presentation HTML in their
pages, and they used an external style sheet. The result? To change the style of the entire site, all they had to do was go into their external style sheet and make a few changes to
the CSS, which they easily did in minutes, not days. They
even had time to try out multiple designs and have three
different versions of the CSS ready for review before the site launch. Amazed, the RobotsRUs CEO not only promised

RadWebDesign more business, but he also promised them the
first robot that comes off the assembly line.

308

Chapter 8

getting started with css

Sharpen your pencil

Now that you’ve got one external style file (or “style sheet”), use it to change all the paragraph fonts to “sans-serif” to match the headings. Remember, the property to change the font style is “font-family”, and the value for sans-serif font is “sans-serif”. You’ll find the answer on the next page.

The headings use sans-serif fonts,
which don’t have “serifs” and have a
very clean look.

The paragraphs still use the
default serif fonts, which have

“serifs”, and are often considered
more difficult to read on a
computer screen.

any
serifs.

you are here �

309

understanding inheritance

Sharpen your pencil

Solution
h1, h2 {

font-family: sans-serif;

color:

gray;

}

h1 {

border-bottom: 1px solid black;

}

p {

font-family: sans-serif;

Just add a font-family property

color:

maroon;
to your paragraph rule in the

}

“lounge.css” file.

I’m wondering if that is
really the best solution. Why are
we specifying the font-family for EACH
element? What if someone added a <blockquote>
to the page - would we have to then add a rule
for that too? Can’t we just tell the whole
page to be sans-serif?

310

Chapter 8

getting started with css

It’s time to talk about your inheritance...

Did you notice when you added the font-family
property to your “p” selector that it also affected the
font family of the elements inside the <p> element?

Let’s take a closer look:

When you added the font-family
property to your CSS p selector, it
changed the font family of your

<p> elements. But it also changed
the font family of the two links
and the emphasized text.

The elements inside the <p> element inherit the
font-family style from <p>

Not every style is
inherited. Just some

Just like you can inherit your blue eyes or brown hair from your parents, elements can inherit are, like font-family.

styles from their parents. In this case, the <a> and <em> elements inherited the font-family style from the <p> element, which is their parent element. It makes sense that changing your paragraph style would change the style of the elements in the paragraph, doesn’t it? After all, if it didn’t, you’d have to go in and add CSS rules for every inline Not to mention, error-element in every paragraph in your whole site... which would definitely be so NOT fun.

prone, tedious, and

Let’s take a look at our XHTML tree to see how inheritance works: time-consuming.

If we set the font-family of all the <p> elements, here are all the elements that would be affected.

html

The <p> elements, of course, would

The <a>, <em>, and <a>
be styled with the font-family.

body
elements in the two
paragraphs inherit the
h1
p
p
h2
p
font-family from their
parent elements, the

The <img> element is a

<p> elements.

child of a paragraph, but
img
a
em
a
it doesn’t have any text,
so it’s not affected.

you are here �

311

moving rules to the body element

What if we move the font up the family tree?

If most elements inherit the font-family property, what if we move it up to the <body> element? That should have the effect of changing the font for all the <body> element’s children, and children’s children.

We’re going to move the font-family
property from the paragraphs and
html
headings to the body.

body

Now all these elements are going to
inherit the font-family.

h1
p
p
h2
p

And so are their children.

img
a
em
a

Remember, images
don’t have text.

Wow, this is powerful. Simply by changing the font-
family property in the body rule, we could change
the font for an entire site.

What are you waiting for... give it a try

Open your “lounge.css” file and add a new rule that selects the <body> element. Then remove the font-family properties from the headings and paragraph rules, because you’re not going to need them anymore.

Here’s what you’re going to do.

body {

First, add a new rule that selects

font-family: sans-serif;
the <body> element. Then add the

}

font-family property with a value
h1, h2 {
of sans-serif.

font-family: sans-serif;

color:

gray;

}

Then, take the font-family
h1 {
property out of the h1, h2

border-bottom: 1px solid black;
rule, as well as the p rule.

}

p {

font-family: sans-serif;

color:

maroon;

}

312

Chapter 8

getting started with css

Test drive your new CSS

As usual, go ahead and make these changes in the “lounge.css”

style sheet, save, and reload the “lounge.html” page. You shouldn’t expect any changes, because the style is the same. It’s just coming from a different rule. But you should feel better about your CSS
because now you can add new elements to your pages and they’ll automatically inherit the sans-serif font.

Surprise, surprise. This doesn’t look any
different at all, but that is exactly what we
were expecting, isn’t it? All you’ve done is move
the sans-serif font up into the body rule and
let all the other elements inherit that.

Okay, so now that the whole
site is set to sans-serif with
the body selector, what if I want one
element to be a different font? Do

I have to take the font-family out
of the body and add rules for every
element separately again?

you are here �

313

when you don’t want to inherit

Overriding inheritance

By moving the font-family property up into the body, you’ve set that font style for the entire page. But what if you don’t want the sans-serif font on every element? For instance, you could decide that you want

<em> elements to use the serif font instead.

The font-family property is set in
html
the body rule, so every element inside
the body inherits the sans-serif
body
font-family property from <body>.

h1
p
p
h2
p
img
a
em
a

But you’ve decided you want your <em>
elements to have the serif font-f
ins
amil
tead. Y
y
ou need to override the
inheritance with a CSS rule.

Well, then you can override the inheritance by supplying a
specific rule just for <em> . Here’s how you add a rule for <em> to override the font-family specified in the body:

body {

font-family: sans-serif;

}

h1, h2 {

color:

gray;

}

h1 {

border-bottom: 1px solid black;

}

p {

color:

maroon;

}

To override the font-family property
inherited from body, add a new rule
em {
selecting em with the font-family

font-family: serif;
property value set to serif.

}

314

Chapter 8

getting started with css

Test drive

Add a rule for the <em> element to your CSS with a font-family property value of serif, and reload your “lounge.html” page:

Notice that the “Dance Dance

Revolution” text, which is the text in
the <em> element, is now a serif font.

As a general rule, it’s not a good idea to change fonts
in the middle of a paragraph like this, so go ahead and
change your CSS back to the way it was (without the em
rule) when you’re done testing.

there are no

Dumb Questions

Q:

such as font color (the color property), the

How does the browser know

Q: This stuff gets complicated. Is
which rule to apply to <em> when I’m
font-family, as you’ve just seen, and other
there any way I can add comments to
overriding the inherited value?

font related properties such as font-size,
font-weight (for bold text), and font-style
remind myself what the rules do?

A:

(for italics) are inherited. Other properties,

With CSS, the most specific rule
such as border, are not inherited, which

A: Yes. To write a comment in your
is always used. So, if you have a rule for
makes sense, right? Just because you want CSS just enclose it between /* and */. For

<body>, and a more specific rule for <em>
a border on your <body> element doesn’t
instance:

elements, it is going to use the more specific mean you want it on all your elements. A

/* this rule selects all para-
rule. We’l talk more later about how you
lot of the time you can fol ow your common
graphs and colors them blue */
know which rules are most specific.

sense (or just try it and see), and you’l get
the hang of it as you become more familiar

Notice that a comment can span multiple

Q:

with the various properties and what they do. lines. You can also put comments around How do I know which CSS

CSS and browsers will ignore it, like:

properties are inherited and which are

Q:

/* this rule will have no effect
not?

Can I always override a property
that is being inherited when I don’t want
because it’s in a comment

A:

it?

p { color: blue; } */

This is where a good reference
really comes in handy, like O’Reilly’s CSS

A:

Pocket Reference. In general, all of the

Yes. You can always use a more
styles that af ect the way your text looks,
specific selector to override a property from
a parent.

you are here �

315

styling individual paragraphs

I was thinking it would
be cool to have the text below
each elixir match the color of
the elixir. Can you do that?

We’re not sure we agree with the
aesthetics of that suggestion,
but, hey, you’re the customer.

Can you style each of these paragraphs separately
so that the color of the text matches the drink? The
problem is that using a rule with a “p” selector applies
the style to all <p> elements. So, how can you select these paragraphs individually?

That’s where classes come in. Using both XHTML and

CSS, we can define a class of elements, and then apply
styles to any element that belongs to that class. So, what
exactly is a class? Think of it like a club – someone
starts a “greentea” club, and by joining you agree to all
the rights and responsibilities of the club, like adhering to their style standards. Anyway, let’s just create the class and you’ll see how it works.

Green text.

Blue text.

Purple text.

Red text... oh,
we don’t need to
change this one.

316

Chapter 8
getting started with css

Adding a class to “elixir.html”

Open up the “elixir.html” file and locate the “Green Tea Cooler” paragraph.

This is the text we want to change to green. All you’re going to do is add the <p> element to a class called greentea. Here’s how you do that:

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”

“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” lang=”en” xml:lang=”en”>

<head>

<meta http-equiv=“Content-Type” content=“text/html; charset=ISO-8859-1” />

<title> Head First Lounge Elixirs</title>

<link type=“text/css” rel=”stylesheet” href=”../lounge.css” />

</head>

To add an element to a class, just add

<body>
the attribute “class” along with the name

<h1> Our Elixirs</h1>
of the class, like “greentea”.

<h2> Green Tea Cooler</h2>

<p class=“greentea”>

<img src=“../images/green.jpg” />

Chock full of vitamins and minerals, this elixir

combines the healthful benefits of green tea with

a twist of chamomile blossoms and ginger root.

</p>

<h2> Raspberry Ice Concentration</h2>

<p>

<img src=“../images/lightblue.jpg” />

Combining raspberry juice with lemon grass,

citrus peel and rosehips, this icy drink

will make your mind feel clear and crisp.

</p>

<h2> Blueberry Bliss Elixir</h2>

<p>

<img src=“../images/blue.jpg” />

Blueberries and cherry essence mixed into a base

of elderflower herb tea will put you in a relaxed

state of bliss in no time.

</p>

<h2> Cranberry Antioxidant Blast</h2>

<p>

<img src=“../images/red.jpg” />

Wake up to the flavors of cranberry and hibiscus

in this vitamin C rich elixir.

</p>

</body>

</html>

And, now that the green tea paragraph belongs to the greentea class, you just need to provide some rules to style that class of elements.

you are here �

317
class selectors

Creating a selector for the class

To select a class, you write the selector like this:

Then use a “.” to
specify a class.

Last is the
class name.

The p selector
is first.

p.greentea {

And her

color: green;
e’s the rule... make any
text in a paragraph in the

}

greentea class the color green.

This selector selects
all paragraphs in the
greentea class.

So now you have a way of selecting <p> elements that belong to a certain class.

All you need to do is add the class attribute to any <p> elements you want to be green, and this rule will be applied. Give it a try: open your “lounge.css” file and add the p.greentea class selector to it.

body {
font-family: sans-serif;

}

h1, h2 {
color: gray;

}

h1 {
border-bottom: 1px solid black;

}

p {
color: maroon;

}

p.greentea {
color: green;

}

318

Chapter 8

getting started with css

A greentea test drive

Save, and then reload to give your new class a test drive.

Here’s the new greentea class
applied to the paragraph. Now
the font is green and matches
the Green Tea Cooler. Maybe
this styling wasn’t such a bad
idea after all.

Sharpen your pencil

Your turn: add two classes, “raspberry” and “blueberry”, to the correct paragraphs in “elixir.html”, and then write the styles to color the text blue and purple, respectively. The property value for raspberry is “blue” and for blueberry is “purple”. Put these at the bottom of your CSS file, under the greentea rule: raspberry first, and then blueberry.

Yeah, we know you’re probably thinking, how can a
raspberry be blue? Well, if Raspberry Kool-aid is
blue, that’s good enough for us. And seriously, when
you blend up a bunch of blueberries, they really are
more purple than blue. Work with us here.

you are here �

319

dealing with class selectors

Taking classes further...

You’ve already written one rule that uses the greentea class to change any paragraph in the class to the color “green”:

p.greentea {
color: green;

}

But what if you wanted to do the same to all <blockquote> s?

Then you could do this:

blockquote.greentea, p.greentea {

Just add another selector to handle
color: green;

<blockquote>s that are in the greentea

}

class. Now this rule will apply to <p> and

<blockquote> elements in the greentea class.

And in your XHTML you’d write:

<blockquote class=”greentea”>

So what if I want to
add <h1>, <h2>, <h3>, <p>, and

<blockquote> to the green tea
class? Do I have to write one
huge selector?

No, there’s a better way. If you want all
elements that are in the greentea class
to have a style, then you can just write
your rule like this:

.greentea {
color: green;

}

If you leave out all the element names,
and just use a period followed by a
class name, then the rule will apply to
all members of the class.

320

Chapter 8

getting started with css

Cool! Yes, that works.

One more question... you said
being in a class is like being in a
club. Well, I can join many clubs.

So, can an element be in more
than one class?

Yes, elements can be in more than one class.

It’s easy to put an element into more than one class. Say
you want to specify a <p> element that is in the greentea, raspberry, and blueberry classes. Here’s how you Place each class
would do that in the opening tag:

name into the
value of the class

<p class=”greentea raspberry blueberry”>
attribute, with a
space in between
each. The ordering

So, for example, I could
doesn’t matter.

put an <h1> into my “products”

class that defines a font size and
weight, and also a “specials” class
to change its color to red when
something’s on sale?

Exactly. Use multiple classes when you want
an element to have styles you’ve defined in
different classes. In this case, all your <h1>
elements associated with products have a
certain style, but not all your products are
on sale at the same time. By putting your

“specials” color in a separate class, you can
simply add only those elements associated with
products on sale to the “specials” class to add
the red color you want.

Now you may be wondering what happens when an element belongs to multiple classes, all of which define the same property – like our <p> element up there. How do you know which style gets applied? You know each of these classes has a definition for the color property. So, will the paragraph be green, blue (raspberry), or purple?

We’re going to talk about this in great detail after you’ve learned a bit more CSS, but on the next page you’ll find a quick guide to hold you over.

you are here �

321
intro to applying styles

The world’s smallest & fastest guide to how
styles are applied

Elements and document trees and style rules and classes... it can get downright confusing.

How does all this stuff come together so that you know which styles are being applied to which elements? As we said, to fully answer that you’re going to have to know a little more about CSS, and you’ll be learning that in the next few chapters. But before you get there, let’s just walk through some common sense rules-of-thumb about how styles are applied.

First, do any selectors select your element?

Let’s say you want to know the font-family property value for an element. The first thing to check is: is there a selector in your CSS file that selects your element? If there is, and it has a font-family property and value, then that’s the value for your element.

What about inheritance?

If there are no selectors that match your element, then you rely on inheritance. So, look at the element’s parents, and parents’ parents, and so on, until you find the property defined.

When and if you find it, that’s the value.

Struck out again? Then use the default

If your element doesn’t inherit the value from any of its ancestors, then you use the default value defined by the browser. In reality, this is a little more complicated than we’re describing here, but we’ll get to some of those details later in the book.

What if multiple selectors select an element?

Ah, this is the case we have with the paragraph that belongs to all three classes:

<p class=”greentea raspberry blueberry”>

There are multiple selectors that match this element and define the same color property.

That’s what we call a “conflict”. Which rule breaks the tie? Well, if one rule is more specific than the others, then it wins. But what does more specific mean? We’ll come back in a later chapter and see exactly how to determine how specific a selector is, but for now, let’s look at some rules and get a feel for it:

Here’s a rule that selects any old
p { color: black;}

paragraph element.

This rule selects members of the greentea class.

.greentea { color: green; }

That’s a little more specific.

And this rule selects only paragraphs that are in
p.greentea { color: green; }

the greentea class, so that’s even more specific.

These rules also select only paragraphs in a
p.raspberry { color: blue; }

particular class. So they are about the same in
p.blueberry { color: purple; }

specificity as the p.greentea rule.

322

Chapter 8

getting started with css

And if we still don’t have a clear winner?

So, if you had an element that belonged only to the greentea class there would be an obvious winner: the p.greentea selector is the most specific, so the text would be green. But you have an element that belongs to all three classes: greentea, raspberry, and blueberry. So, p.greentea, p.raspberry, and p.blueberry all select the element, and are of equal specificity. What do you do now? You choose the one that is listed last in the CSS file. If you can’t resolve a conflict because two selectors are equally specific, you use the ordering of the rules in your style sheet file.

That is, you use the rule listed last in the CSS file (nearest the bottom). And in this case, that would be the p.blueberry rule.

In your “lounge.html” file, change the greentea paragraph to include al the classes, like this:

Exercise <p class=”greentea raspberry blueberry”> Save, and reload. What color is the Green Tea Cooler paragraph now?

Next, reorder the classes in your XHTML:

<p class=”raspberry blueberry greentea”>

Save, and reload. What color is the Green Tea Cooler paragraph now?

Next, open your CSS file and move the p.greentea rule to the bottom of the file.

Save, and reload. What color is the Green Tea Cooler paragraph now?

Finally, move the p.raspberry rule to the bottom of the file.

Save, and reload. What color is the Green Tea Cooler paragraph now?

After you’ve finished, rewrite the green tea element to look like it did originally:

<p class=”greentea”>

Save, and reload. What color is the Green Tea Cooler paragraph now?

you are here �

323

language comparison: css and xhtml

Tonight’s talk: CSS & XHTML compare languages

CSS

XHTML

Did you see that? I’m like Houdini! I broke right
out of your <style> element and into my own
file. And you said in Chapter 1 that I’d never
escape.

Don’t get all excited; I still have to link you in
for you to be at all useful.

Have to link me in? Come on; you know your
pages wouldn’t cut it without my styling.

Here we go again... while me and all my
elements are trying to keep things structured,
you’re talking about hair highlights and nail
color.

If you were paying attention in this chapter, you
would have seen I’m downright powerful in what

I can do.

Okay, okay, I admit it; using CSS sure makes
my job easier. All those old deprecated styling
elements were a pain in my side. I do like the
fact that my elements can be styled without
inserting a bunch of stuff in the XHTML,
other than maybe an occasional class attribute.

Wel now, that’s a little better. I like the new
attitude.

But I still haven’t forgotten how you mocked
my syntax... <remember>?

324

Chapter 8
getting started with css

CSS

XHTML

You have to admit XHTML is kinda clunky, but
that’s what you get when you’re related to an
early ’90s technology.

I call it standing the test of time. And you think

CSS is elegant? I mean, you’re just a bunch of
rules. How’s that a language?

Are you kidding? I’m very expressive. I can
select just the elements I want, and then
describe exactly how I want them styled. And
you’ve only just begun to see al the cool styling

I can do.

Oh yeah?

Yup; just wait and see. I can style fonts and
text in al kinds of interesting ways. I can even
control how each element manages the space
around it on the page.

Hmmm... sounds as if you have a little too
much power; I’m not sure I like the sound of
that. After all, my elements want to have some
control over their own lives.

Bwahahahaa. And you thought you had me
controlled between your <style> tags. You’re
going to see I can make your elements sit, bark,
and rollover if I want to.

Whoa now! Security... security?!

you are here �

325

testing your inheritance skills

Who gets the inheritance?

Sniff, sniff; the <body> element has gone to that great browser in the sky. But he left behind a lot of descendants and a big inheritance of color “green”. Below you’ll find his family tree. Mark all the descendants that inherit the <body> element’s color green. Don’t forget to look at the CSS below first.

body
h1
p
h2
p
h2
blockquote
a
em
a
img
p
p
em
em
a

Here’s the CSS. Use this to
body {
determine which of the abov

color: green;
e

}

elements hit the jackpot and
get the green (color).

p {

color: black;

}

326

Chapter 8

getting started with css

BE the Browser

Below, you’ll find the CSS file

If you have errors in your CSS,

“style.css”, with some errors in it.

usually what happens is all the rules

Your job is to play like you’re the
below the error are ignored. So, get
browser and locate all the errors.

in the habit of looking for errors now,

After you’ve done the
by doing this exercise.

exercise look at the
end of the chapter to
see if you caught all
the errors.

The file “style.css”

<style>
body {
background-color: white
h1, {
gray;
font-family: sans-serif;

}

h2, p {
color:

}

<em> {
font-style: italic;

}

</style>
you are here �

327

validating css

The exercise got me
thinking... is there a way to
validate CSS like there is with

HTML and XHTML?

Of course!

Those W3C boys and girls aren’t just sitting
around on their butts, they’ve been working hard.

You can find their CSS validator at:

http://jigsaw.w3.org/css-validator/

Type that URL in your browser and we think
you’ll feel quite at home when you get there.

You’re going to find a validator that works almost
exactly like the HTML and XHTML validators.

To use the CSS version,
just point the validator to
your CSS URL, upload a
file with your CSS in it, or
just paste it into the form
and submit.

You shouldn’t encounter
any big surprises, like
needing DOCTYPEs or
character encodings with

CSS. Go ahead, give it a
try (like we’re not going
to make you do it on the
next page, anyway).

328

Chapter 8

getting started with css

Making sure the Lounge CSS validates

Before you wrap up this chapter, wouldn’t you feel a lot better if all that Head First Lounge CSS validated? Sure you would. Use whichever method you want to get If your CSS didn’t validate, check
your CSS to the W3C. If you have your CSS on a server, type your URL into the it with the CSS a few pages back
form; otherwise, either upload your CSS file or just copy and paste the CSS into the and find any small mistakes you’ve
made, then resubmit.

form. (If you upload, make sure you’re directing the form to your CSS file, not your XHTML file.) Once you’ve done that, click on “Check”.

This is just telling you that the

CSS needs correct XHTML to
style, so make sure your XHTML

(or HTML) also validates.

Here are some warnings about the CSS. These
are more suggestions than real warnings. For
instance, all these warnings are telling you to set a
background color on the headings and paragraphs.

And here’s all the valid CSS,
which is ALL your CSS, so this
means your CSS validates.

there are no

Dumb Questions

There’s no “green badge of success” when

Q:

you pass validation like there is when you

Do I need to worry about those
validate XHTML. So check the top of

warnings? Or do what they say?

the page for “Errors”. If you don’t see
that, your CSS validated!

A: It’s good to look them over, but
you’l find some are more in the category of
suggestions than “must do’s”. The validator
can err on the side of being a lit le anal, so
just keep that in mind.

you are here �

329

getting a feel for some other properties
top
text-align

Property

Controls the

Use this property to align your text
position of the
to the left, center, or right.

top of the

Soup
element.

letter-spacing This lets you set the spacing
between letters. L i k e t h i s.

Use color to set the font
color of text elements.

background-color
color

This property controls the

Use this property for
background color of an element.

italic or oblique text.

This property controls the
weight of text. Use it to
border
font-style
make text bold.

This property puts a border around an

This property lets you
element. You can hav
change how list items
font-weight
e a solid border, a
ridged border, a dotted border...

look in a list.

left
list-style

This is how you tell an

If you need space
element how to position its
left side.

margin between the edge of an
element and its content,

This property sets the
use margin.

Use this property
space between lines in a
to put an image
text element.

Makes text bigger
behind an element..

or smaller.

line-height
font-size
background-image

CSS has a lot of style properties.

You’ll see quite a few of these in
the rest of this book, but have a
quick look now to get an idea
of all the aspects of style
you can control with CSS.

330

Chapter 8

getting started with css

It looks like you’re
getting the hang of this style
stuff. We’re looking forward to
seeing what you come up with in
the next couple of chapters.

BULLET POINTS

n

CSS contains simple statements, called rules.

n

The <link> element is used to include an
external style sheet.

n

Each rule provides the style for a selection of

XHTML elements.

n

Many properties are inherited. For instance,
if a property that is inherited is set for the

n

A typical rule consists of a selector along with
one or more properties and values.

<body> element, all the <body>’s child
elements will inherit it.

n

The selector specifies which elements the rule
applies to.

n

You can always override properties that are
inherited by creating a more specific rule for
the element you’d like to change.

n

Each property declaration ends with a
semicolon.

n

Use the class attribute to add elements to
a class.

n

All properties and values in a rule go between

{ } braces.

n

Use a “.” between the element name and the
class name to select a specific element in that

n

You can select any element using its name as
the selector.

class.

n

Use “.classname” to select any elements that

n

By separating element names with commas,
you can select multiple elements at once.

belong to the class.

n

An element can belong to more than one class

n

One of the easiest ways to include a style in

HTML is the <style> tag.

by placing multiple class names in the class
attribute with spaces between the names.

n

For XHTML and for sites of any complexity,
you should link to an external style sheet.

n

You can validate your CSS using the W3C
validator, at http://jigsaw.w3.org/css-validator.

you are here �

331

time for some mental pushups

XHTMLcross

Here are some clues with mental twist and turns that will help you burn alternative routes to CSS right into your brain!

1

2

3

4

5

6

7

8

9

10

11

12

13

Across

Down

1. Defines a group of elements.

1. With inheritance, a property set on one element

2. Ornamental part of some fonts.

is also passed down to its _______.

4. Styles are defined in these.

2. You can place your CSS inside these tags in an

7. Fonts without serifs.

HTML file.

9. Each rule defines a set of properties and?

3. Won this time because they used external style

10. How elements get properties from their
sheets.

parents.

5. Property that represents font color.

11. Use this element to include an external style

6. Property for font type.

sheet.

7. An external style file is called this.

12. Selects an element.

8. They really wanted some style.

13. Reality show.

332

Chapter 8

getting started with css

Markup Magnets Solution

Like this.

html

Remember drawing the diagram of XHTML elements in

Chapter 3? You did that again for the Lounge’s main page.

head
body

Here’s the answer:

title
p
q
html
head
body
meta
title
style
h1
p
p
h2
p
img
a
em
a
you are here �

333

exercise solutions

Sharpen your pencil

Solution

The selected elements are colored:

p, h2 {
font-family: sans-serif;

}

html
body
h1
p
p
h2
p
img
a
em
a
p, em {
font-family: sans-serif;

}

html
body
h1
p
p
h2
p
img
a
em
a

334

Chapter 8

getting started with css

Sharpen your pencil

Solution

Your turn: add two classes, “raspberry” and “blueberry” to the correct paragraphs in “elixir.html” and then write the styles to color the text blue and purple respectively. The property value for raspberry is “blue” and for blueberry is “purple”.

body {
font-family: sans-serif;

}

h1, h2 {
color: gray;

}

h1 {
border-bottom: 1px solid black;

}

p {
color: maroon;

}

p.greentea {
color: green;

}

p.raspberry {
color: blue;

}

p.blueberry {
color: purple;

}

you are here �

335

exercise solutions

Sharpen your pencil

Solution

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”

“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” lang=”en” xml:lang=”en”>

<head>

<meta http-equiv=“Content-Type” content=“text/html; charset=ISO-8859-1” />

<title> Head First Lounge Elixirs</title>

<link type=“text/css” rel=”stylesheet” href=”../lounge.css” />

</head>

<body>

<h1> Our Elixirs</h1>

<h2> Green Tea Cooler</h2>

<p class=“greentea”>

<img src=“../images/green.jpg” />

Chock full of vitamins and minerals, this elixir

combines the healthful benefits of green tea with

a twist of chamomile blossoms and ginger root.

</p>

<h2> Raspberry Ice Concentration</h2>

<p class=“raspberry” >

<img src=“../images/lightblue.jpg” />

Combining raspberry juice with lemon grass,

citrus peel and rosehips, this icy drink

will make your mind feel clear and crisp.

</p>

<h2> Blueberry Bliss Elixir</h2>

<p class=“blueberry” >

<img src=“../images/blue.jpg” />

Blueberries and cherry essence mixed into a base

of elderflower herb tea will put you in a relaxed

state of bliss in no time.

</p>

<h2> Cranberry Antioxidant Blast</h2>

<p>

<img src=“../images/red.jpg” />

Wake up to the flavors of cranberry and hibiscus

in this vitamin C rich elixir.

</p>

</body>

</html>

336

Chapter 8

getting started with css

Exercise solutions

Who gets the inheritance?

body {

color: green;

}

p {

color: black;

}

h1 and h2 get the inheritance

There are no CSS rules f
because they don’t have a color
or blockquote,
so blockquote a
body
lso inher
property, so they inherit their
its i
f
ts color
rom body. (But, sinc
color from body. Lucky them!

e p ov
color t
errides the
o black, the blockquote color
won’t matter.)

h1
p
h2
p
h2
blockquote
a
em
a
img
p
p

This one em is fortunate to be
em
em
a
a child of h2, who inherits the
body color. Since there’s no em
rule overriding the color with its

Unfortunately for these em
own property, this em inherits
elements, they are children

And, these poor a elements are
body’s color.

of parents who override the
also children of p, so they don’t
body color, the p element.

inherit the body color either.

So they don’t get any color
inheritance from body.

img is a child of p, so img
doesn’t inherit the color
from body. img wouldn’t get
a color inheritance anyway

(poor guy).

you are here �

337

exercise solutions

BE the Browser

Below, you’ll find a CSS file with
some errors in it. Your job is to
play like you’re the browser and

Exercise
locate all the errors. Did you
find them all?

solutions

No XHTML in your CSS! The

<style>

<style> tags are XHTML and
don’t work in a CSS style sheet.

body {

Missing semicolon.

background-color: white Missing }

Extra comma.

h1, {

Missing property name.

gray;
font-family: sans-serif;

}

h2, p {

Missing property value and semicolon.

color:

}

Using the XHTML tag instead of just

<em> {
the element name. This should be em.

font-style: italic;

}

</style>

No </style> tags needed in
the CSS stylesheet.

338

Chapter 8

getting started with css

1C L A S S

H

2

3

S

E

R

I

F

I

4

5

6

T

A

R U

L

E S

C

F

Y

D

D

O

O

L

W

R

L

N

E

E

E

O

T

7

8

B

S A N S S

E

R

I

F

-

L

D

T

F

O

9

E

Y

V A

L U E S

S

L

M

N

10

I N H E

R

I

T A N C

E

I

G

G

S

L

E

11

L

I N K

H

Y

G

12

S

E

L

E

C

T O R

U

E

Y

13

T R A D

I N G S

P

A C

E S

Across

Down

1. Defines a group of elements. [class]

1. With inheritance, a property set on one element

2. Ornamental part of some fonts. [serif]

is also passed down to its _______. [children]

4. Styles are defined in these. [rules]

2. You can place your CSS inside these tags in an

7. Fonts without serifs. [sansserif]

HTML file. [style]

9. Each rule defines a set of properties and?

3. Won this time because they used external style

In your “lounge.html” file, change the greentea paragraph to include al the

[values]

sheets. [RadWebDesign]

Exercise
classes, like this:

10. How elements get properties from their

5. Property that represents font color. [color]

Solutions
parents. [inheritance]

6. Property for font type. [font-family]

It’s purple because the

<p class=”greentea raspberry blueberry”>

11. Use this element to include an external style

7. An external style file is called this. [stylesheet]

sheet. [link]

8. They really wanted some style. [loungeguys]

blueberry rule is last in

12. Selects an element. [selector]

Save, and reload. What color is the Green Tea Cooler paragraph now?

purple
the CSS file.

Next reorder the classes in your XHTML:

It’s still purple because the

<p class=”raspberry blueberry greentea”>
ordering of the names in the

Save, and reload. What color is the Green Tea Cooler paragraph now?

purple
class attribute doesn’t matter.

Next open your CSS file and move the p.greentea rule to the bot om of the file.

Now, it’s green, because

Save, and reload. What color is the Green Tea Cooler paragraph now?

green
the greentea rule comes
last in the CSS file.

Final y, move the p.raspber y rule to the bot om of the file.

Now, it’s blue, because the

Save, and reload. What color is the Green Tea Cooler paragraph now?

blue
raspberry rule comes last

After you’ve finished, rewrite the green tea element to look like it did original y: in the CSS file.

<p class=”greentea”>

Okay, now the <p> element
only belongs to one class, so

Save, and reload. What color is the Green Tea Cooler paragraph now?

green
we use the most specific
rule, which is p.greentea.

you are here �

339

9 styling with fonts and colors

Expanding your

Vocabulary

Your CSS language lessons are coming along nicely. You already have the basics of CSS down and you know how to create CSS rules to select and specify the style of an element. Now it’s time to build your vocabulary, and that means picking up some new properties and learning what they can do for you. In this chapter we’re going to work through some of the most common properties that affect the display of text. To do that, you’ll need to learn a few things about fonts and color. You’re going to see you don’t have to be stuck with the fonts everyone else uses, or the clunky sizes and styles the browser uses as the defaults for paragraphs and headings. You’re also going to see there is a lot more to color than meets the eye.

this is a new chapter

341

common text properties

Text and fonts from 30,000 feet

A lot of the CSS properties are dedicated to helping you style your text. Using CSS, you can control typeface, style, color, and even the decorations that are put on your text, and we’re going to cover all these in this chapter. We’ll start by exploring the actual fonts that are used to display your pages. You’ve already seen the font-family property and in this chapter you’re going to learn a lot more about specifying fonts.

Before we dive in, let’s get the 30,000 foot view of some properties you can use to specify and change the look of your fonts. After that, we’ll take the fonts one by one and learn the ins and outs of using each.

Andale Mono

Customize the fonts in your pages with the font-family property.

Arial

Fonts can have a dramatic effect on your page designs. In CSS, fonts are divided into “font families” from which you can specify the fonts you’d Arial Black
like used in each element of your page. Only certain fonts are commonly Comic Sans
installed on most computers, so you need to be careful in your font Courier New
choices. In this chapter we’ll take you through everything you need to Georgia
know to specify and make the best use of fonts.

Impact
body {

Times New Roman

font-family: Verdana, Geneva, Arial, sans-serif;

Trebuchet MS

}

Verdana

Control the size of your fonts with the font-size property.

Font size also has a big impact on the design and the readability of your Web pages. There are several ways to specify font sizes with CSS, and in this chapter we’ll cover each one, but we’ll also teach you how to specify body is 14px
your fonts in a way that allows your users to increase the font size without affecting your designs.

h1 is 21px
p is 14px
h2 is 17px
body {

font-size: 14px;

}

342

Chapter 9
styling with fonts and colors

Add color to your text with the color property.

Aqua

Black

Blue

You can change your text color with the color property. To do that, it helps to know a little about Web colors, and we’ll take you through all the Fuchsia

Gray

Green
ins and outs of color, including the mysterious color “hex codes.”

Lime

Maroon

Navy

Olive

Orange

Purple
body {

color: silver;

Red

Silver

Teal

}

White

Yellow

Affect the weight of your fonts with the font-weight property.

Why settle for boring, average fonts when you can give them some extra lighter
weight when needed? Or, are your fonts looking too heavy? Slim them down to a normal weight. All this is easily done with the font-weight property.

normal
body {
bold

font-weight: bold;

}

bolder

Add even more style to your text with the text-decoration property.

none

Using the text-decoration property you can decorate your text with decorations including overlines, underlines, and line-throughs. And if you didn’t get enough of blinking text on the Web in the 1990s, the designers of CSS have underline
even included a blink value for text-decoration (although thankfully they don’t require browsers to implement it).

overline
body {
line-through

text-decoration: underline;

}

blink
you are here �

343
overview of font families

What is a font family anyway?

You’ve already come across the font-family property, and so far you’ve always specified a value of “sans-serif ”. You can get a lot more creative than that with the font-family property, but it helps to know what a font family is first. Here’s a quick rundown...

Each font-family contains a set of fonts that
share common characteristics. There are five
font families: sans-serif, serif, monospace,
cursive, and fantasy. Each family includes a
large set of fonts, so on this page you’ll see

Sans-serif Family
only a few examples of each.

Verdana Arial Black

Trebuchet MS

Arial

The serif family includes fonts with serifs.

A lot of people associate the look of

Geneva
these fonts with newspaper print.

Serifs are the
decorative barbs
and hooks on the
ends of the letters.

Serif Family

The sans-serif family includes fonts
without serifs. These fonts are usually
considered more readable on computer
screens than serif fonts.

Times

Sans-serif means

“without serifs”.

Times New Roman

Fonts aren’t consistently available from
one computer to another. In fact, the set of

Georgia
available fonts will vary depending on the
operating system as well as what fonts and
applications a user has installed. So keep
in mind that the fonts on your machine may
differ from what is available to your users.

344

Chapter 9
styling with fonts and colors

Monospace Family

Courier

The Monospace family is made up of fonts that have constant width characters. For instance, the horizontal space an “i” takes Courier New
up will be the same width that an “m” takes up. These fonts are primarily used to show software code examples.

Andale Mono

The Cursive family
includes fonts that
look handwritten. You’ll
sometimes see these fonts
used in headings.

Take a good look at the font families: serif
fonts have an elegant, traditional look,
while sans-serif fonts have a very clean and

Cursive Family
readable look. Monospace fonts feel like
they were typed on a typewriter. Cursive and

Fantasy fonts have a playful or stylized feel.

Comic Sans

Apple Chancery

Fantasy Family

The Fantasy font family contains
stylized decora

Last NinjA
tive fonts. These fonts
are usually not widely available and are
rarely used for serious Web designs.

Impact
you are here �

345

develop your sense of fonts

Font Magnets

Your job is to help the fictional fonts below find their way home to their own font family. Move each fridge magnet on the left into the correct font family on the right. Check your answers before you move on. Review the font family descriptions on the previous pages if you need to.

Bainbridge

Monospace Family

Fantasy Family

Cartoon

Palomino

Angel

Cursive Family

Iceland

Sans-serif Family

Messenger

Savannah

Serif Family

Crush

Nautica

Quarter

346

Chapter 9
styling with fonts and colors

Specifying font families using CSS

Okay, so there are a lot of good fonts out there from several font families. How do you get them in your pages? Well, you’ve already had a peek at the font-family property in the last chapter, when you specified a font-family of “sans-serif ” for the lounge. Here’s a more interesting example:

Usually your font-family specification contains a
list of alternative fonts, all from the same family.

body {

font-family: Verdana, Geneva, Arial, sans-serif;

}

You can specify more than one

Write font names as they
font using the font-family
are spelled, including upper-
property. Just type the font
and lower-case letters.

Always put a generic font family name at the
names separated by commas.

end, like “serif”, “sans-serif”, “cursive”, or

“monospace”. You’ll see what this does in a sec.

How font-family specifications work

Here’s how the browser interprets the fonts listed in your font-family specification: Check to see if the font

If Verdana isn’t

If Geneva isn’t

Verdana is available on the
available, then look

Finally, if none of the sp
available, then look f
ecific
or
computer and if so, use
for the font Geneva,
fonts can be found, jus
the f
t use
ont Arial, and if
it as the font for this
and if it is available,
whatever the browser consider
it is available, use it
s
element (in this case, the
use it for the body.

its default “sans-serif” f
for the body.

ont.

<body> element).

body {

font-family: Verdana, Geneva, Arial, sans-serif;

}

You don’t have to specify four alternative fonts; you
can have two, three, etc. In the last chapter we only
used one - the default sans-serif font - although
we don’t recommend that because it doesn’t give you
much control over the fonts you’d like used.

The font-family property gives you a way to create a list of preferred fonts.

Hopefully most browsers will have one of your first choices, but if not, you can at least be assured that the browser will provide a generic font from the same family.

Let’s get some fonts into your pages...

you are here �

347

improving tony’s journal

Dusting off Tony’s Journal

Now that you know how to specify fonts, let’s take
another look at Tony’s Segway’n USA page and
give it a different look. We’ll be making some small,
incremental changes to the text styles in Tony’s
page and while no single change is going to look
dramatically different, by the end of the chapter
we think you’ll agree the site has a slick new look.

Let’s get an idea of where we might make some
improvements and then let’s give Tony a new
font-family.

Remember that we haven’t applied
any styles to Tony’s site, so his site
is using a serif font-family for the
entire page.

The default size of the heading fonts is also pretty
large and doesn’t make for an attractive page.

The quote is just indented. It
would be nice to improve its look
a bit by adding some font-style.

Except for the photos, this page
is rather monochromatic, so we’ll
also add some font color to make
it a little more interesting.

348

Chapter 9
styling with fonts and colors

Getting Tony a new font-family

Let’s get Tony set up with a font-family. We’re going to start with some clean sans-serif fonts. First, create a new file, “journal.css” in the

“chapter9/journal” folder and add this rule:

body {
font-family: Verdana, Geneva, Arial, sans-serif;

}

We’re setting the

You’ll see Verdana
font-family prop
on mos
erty
t PCs.

And if all else

And Geneva on
fails, we have
on the <body> element.

most Macs.

the default

Remember, the
elements in the <body>

Arial is
sans-serif.

will inherit these f
common
onts.

We’ve chosen a set of
on both.

sans-serif fonts here.

Now you need to link Tony’s journal to the new style sheet file. To do that, open the file “journal.html” in the “chapter9/journal” folder. All you need to add is the

<link> element to link in the style in “journal.css”, like we did below.

Remember, you fixed up Tony’s journal to
be strict XHTML in Chapter 7.

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”

“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>

<html xmlns=“http://www.w3.org/1999/xhtml” lang=”en” xml:lang=”en”>

<head>

<meta http-equiv=“Content-Type” content=“text/html; charset=ISO-8859-1” />

<link type=“text/css” rel=“stylesheet” href=“journal.css” />

<title> My Trip Around the USA on a Segway</title>

</head>

Here’s where we’re

<body>
linking in the new

.

“journal.css” file.

.

.

</body>

</html>

After you’ve made this change, save the file, fire up your browser and load the page.

you are here �

349

some fonts questions

Test driving Tony’s new fonts

Open the page with the new CSS in the browser and you
should see we’ve now got a nice set of sans-serif fonts.

Let’s check out the changes...

The font definitely gives Tony’s Web page a
new look. The headings now have a cleaner look
without the serifs on the letters, although they
still look a tad large on the page.

The paragraph text is also
clean and very readable.

Because font-family is an inherited property,
all elements on the page are now using a
sans-serif font, even the list elements...

... and the <blockquote>s.

And if the serif fonts were more
your cup of tea, don’t let us stop you.

You can always redo the font-family
declaration to use serif fonts.

there are no

Dumb Questions Q:

Q:

Q:

Q:

So the font-family

Are “serif” and “sans-

How do I know which

How do I specify a font property is really a set of
serif” real fonts?

to use? Serif or sans-serif?

with multiple words in the
alternative fonts?

name, like Courier New?

A:

A: “serif” and “sans-serif” A: There are no rules.

A:

Yes. It’s basically a
are not the names of actual

However, on a computer display,

Just put double quotes
priority list of fonts. The first is
fonts. However, your browser
many people consider sans-serif
around the name in your font-
the font you’d like used, fol owed wil substitute a real font in the best for body text. You’ll
family declaration, like this:

by a good substitute, followed by place of “serif” or “sans-serif” if find plenty of designs that use
font-family: “Courier New”,
more substitutes, and so on. For the other fonts before it in the serif for body text, or mix serif

Courier;
the last font, you should specify
font-family declaration can’t be
fonts with sans-serif fonts. So,
the catch-al generic “sans-serif” found. The font used in its place it really is up to you and what or “serif”, which should be in the wil be whatever the browser kind of look you want your page
same family as all the fonts in
has defined as the default font in to have.

your list.

that family.

350

Chapter 9
styling with fonts and colors

How do I deal with everyone having
different fonts?

The unfortunate thing about fonts is that you

Andale Mono
can’t control what fonts are on your users’

computers. The best you can do is to create a

Arial
list of fonts that are most appropriate for your
pages and then hope the user has one of those

Arial Black
fonts installed. If they don’t, well, at least we

These fonts

Comic Sans
can count on the browser to supply a generic
are likely to
font in the same font family.

Courier New
be available on

At least, that’s the basic strategy for ensuring
both Windows

Georgia
your page is displayed using appropriate
and Macintosh
fonts. But it turns out, given the differences
computers.

Impact
in fonts between operating systems (especially

Times New Roman

Windows versus Mac), you do have to take
this a little further to really do your job well.

Trebuchet MS

What you need to do is ensure that your
font-family

Verdana
declaration includes fonts that
are likely to occur on both Windows and the

Mac (as well as any other platforms your users
might be using, like Linux or perhaps mobile
devices).

These fonts are

Geneva
most likely to be

Here’s a quick guide to some of the common

Courier
found on Macintosh
fonts on each operating system, but we
computers.

Helvetica
encourage you to explore this area more if you
need to closely control the fonts on your pages.

Times

Let’s take a look at

(1) We’d like for

(3) That’s okay, because we
our definition for Tony’s

Verdana to be
can probably count on Arial
pages again...

used, but...

to be on either Windows or

Macs, but if it’s not...

font-family: Verdana, Geneva, Arial, sans-serif;

(2) If it’s not, Geneva would

(4) Then that’s still
be nice, but this will probably
okay, we’ll just let the
only happen on Macs. But if
browser choose a sans-
it’s not...

serif font for us.

you are here �

351

how to specify font sizes

Adjusting font sizes

Now that Tony has a new set of fonts, we need to work on those font sizes, as most If you do things right, any
people find the default sizes of the headings a bit large, at least aesthetically. To do user will be able to increase
that, you need to know how to specify font sizes, and there are actually a few ways to the font sizes on your Web
do this. Let’s take a look at some ways to specify font-size and then we’ll talk page for readability. You’ll
about how best to specify font size so they are consistent and user friendly.

see how in a couple of pages.

You can specify your font size in pixels, just like the pixel dimensions you used for images in Chapter 5. When you specify font size in pixels, you’re telling px the browser how many pixels tall the letters should be.

font-size: 14px;

In CSS you specify pixels with
a number followed by “px”.

The px must come right after the number of

This says that the font-size
pixels. You can’t have a space in between.

should be 14 pixels high.

Here’s how you’d specify
h i p

14 pixels
font-size within a body rule.

Setting a font to 14 pixels high
body {
means that there will be 14

font-size: 14px;
pixels between the lowest part of

}

the letters and the highest.

Unlike pixels, which tell the font exactly how big it should be in pixels, a font size specified as a percentage tells the font how big it should be relative to another font size. So,

% font-size: 150%;

Here we’ve specified a body font size in
pixels, and a level one heading as 150%.

says that the font size should be

150% of another font size. But,
body {
which other font size? Well, since

font-size: 14px;
font-size is a property that is

}

inherited from the parent element,
h1 {
when you specify a % font size, it is

font-size: 150%;
relative to the parent element. Let’s

}

check out how that works...

352

Chapter 9

styling with fonts and colors

You can also specify font sizes using “em”, which, like percentage, is another relative unit of measure. With em you don’t specify a percentage; instead you em specify a scaling factor. Here’s how you use em:

Don’t mix this

This says that the
up with the

<em> element!

font-size: 1.2em;
font size should be
scaled by 1.2.

Say you use this measurement to specify the size of an

<h2> heading. Your <h2> headings will be 1.2 times the font size of the parent element, which in this case is It’s actually 16.8, but 1.2 times 14px, which is about 17px.

most browsers will
round it up to 17.

body {

font-size: 14px;

}

body is 14px

And here’s the <h2>
h1 {
specified by 1.2em.

font-size: 150%;

Here’s the <h1> specified

}

by a percentage.

h2 {

font-size: 1.2em;

}

h1 is 21px
p is 14px
h2 is 17px

If we draw a little document tree, you can see that <h1> inherits from <body>, so its font is going to be 150% of the body’s font size.

body is 14px
h1 is 21px
p is 14px

The <h1> heading is

Since we didn’t specify a font

150% of the <body>
size for <p>, it inherits the
font size, which is 21px.

<body> font size of 14px.

you are here �

353

using keywords for size

There’s one more way to specify font sizes: keywords. You
can specify a font size as
keywords
xx-small, x-small, small,
medium, large, x-large, or xx-large and the browser will translate these keywords into pixel values using defaults that are defined in the browser.

This is typically how the various keyword sizes relate to
one another. Each size is about 20% larger than the
xx-small
previous size and sma
x-small
ll is usually defined to be around

12 pixels in height. Keep in mind, however, that the
small
keywords aren’t always defined the same way in every
medium
browser, and that users can redefine them if they want.

large
body {
x-large

font-size: small;

}

xx-large

In most browsers this will result in the
body text being about 12 pixels.

So, how should I specify my font sizes?

You’ve got quite a few choices for specifying font sizes: px, em, percentages, and keywords. So, which do you use? Here’s a recipe for specifying font sizes that will give you consistent results for most browsers.

1

Choose a keyword (we recommend smal or medium) and specify it as the font size in your body rule. This acts as the default size for your page.

2

Specify the font sizes of your other elements relative to your body font size using either em or percentages (the choice between em and percentages is yours, as they are essentially two ways to do the same thing).

Nice recipe, but what’s good about it? By defining your fonts relative to the body font size, it’s really easy to change the font sizes in your Web page simply by changing the body font size. Want to redesign the page to make the fonts larger? If your body font size value is small, simply change it to medium and, voilà – every other element will automatically get larger in proportion because you specified their font sizes relative to the body’s font size. Better yet, say your users want to resize the fonts on the page. Again, no problem; using this recipe, all the fonts on the page will automatically readjust.

354

Chapter 9

styling with fonts and colors

Let’s look at how this all works. First, you set a size for your

<body> element. Then, you set all the other font sizes relative to that size, like this:

body { font-size: small; }

Internet Explo

Watch it!

rer
h1 { font-size: 150%; }

does NOT
h2 { font-size: 120%; }

support text
scaling when the font size
is specified using pixels.

That gives you a document tree that looks like this:

Unfortunately, Internet Explorer
users cannot

The f
re
ont size of <h1>

We’ve set <h2>’s
size fonts if your
font sizes are specified usin
is 150% the f
g
ont size
font size to 120%
pixels. So, that’s one reason to
of <body>.

stay awa
body is small
of its parent’s size.

y from pixel sizes. If you
use pixels, you’l be reducing the
accessibility of your pages for
many of your users.

h1 is 150% of body p is small h2 is 120% of body

Fortunately, if you fol ow the
recipe of supplying a keyword to
de

The <p> doesn’t have a font-size value set, so
fine your body’s font size, and
use relative sizes
by default, it inherits the <body> font size.

for your other
elements using em or %, then IE
wil properly scale your fonts if the
browser is asked to make the text

Now, let’s say you want to increase the size of the fonts on the page, bigger or smal er.

or perhaps the user does. Then you get a tree that looks like this: Now, let’s say you decide to make your
font size bigger, OR the user makes the
font size bigger using the browser.

body is large
h2 is still 120% the size of

All your other elements
the body font size. In this
automatically get bigger too,
case it’s 120% of “large”.

without you having to do a thing.

h1 is 150% of body p is large h2 is 120% of body

Now the body font size has changed to large, and everything else has changed too, in relation to the body font size. That’s great, because you didn’t have to go through and change all your other font sizes; all you had to do was change the body font size. And if you’re a user, everything happened behind the scenes. When you increased the text size, all the text got bigger because all the elements are sized relative to one another, so the page still looks good at a larger font size.

you are here �

355

setting up tony’s font sizes

Let’s make these changes to the
font sizes in Tony’s Web page

It’s time to try these font sizes in Tony’s Web page. Add the new properties to the

“journal.css” file in the “chapter9/journal” folder. Once you’ve made the changes, reload the page in the browser and check out the differences in the font size. If you don’t see a difference, check your CSS carefully for errors.

body {
font-family: Verdana, Geneva, Arial, sans-serif;
font-size: small;

Following our recipe, we’re using a font-size

}h1 {
of small for the <body> element. This will
font-size: 170%;
act as the base font size.

}h2 {

And we’ll set the other fonts relative to the
font-size: 130%;
body font size. In the case of <h1> we’ll try a

}

font size that is 170% of the base font size.

We’ll make the <h2> font size a tad
smaller than <h1>, or 130% of the
body font size.

Sharpen your pencil

If you specified <h1> and <h2>’s font sizes using em rather than percentage, what would their values be?

Answer: <h1> would be 1.7em and <h2> 1.3em.

356

Chapter 9

styling with fonts and colors

Test driving the font sizes

Here’s the new version with smaller
fonts. The design is starting to

Here’s the evolving journal, complete with new
look a little less clunky!

smaller fonts. Check out the differences...

This <h1> heading looks

Here’s the previous
much better now. It
version before the
doesn’t overwhelm the
change in font sizes.

body text and the
page in size.

The body text is a
tad smaller. The
default body text
font size is usually

16px, although it
does depend on the
browser. But it’s
still easily readable
at the “small” size,
which is probably
about 12px.

The <h2> heading
is a bit smaller too,
and is a good size
compared to the

<h1> heading.

you are here �

357
some more questions on font size
there are no

Dumb Questions

Q:

So, by defining a font size in the

You also are creating pages that are a lit le

Q: So rather than using the size

<body> element, I’m somehow defining a
harder to maintain because if you suddenly
keywords, can I use em or % in the body
default size for the page? How does that
want to increase the font sizes of al the
rule? If I use 90% for the font-size of the
work?

elements in a page, you have a lot of
changes to make.

body, what does that mean exactly? It’s

90% of what?

A: Yes, that’s right. By setting a font Q: What’s the difference between em size in your <body> element, you can then

A:

and %? They seem like the same thing.

Yes, you can do that. If you specify
define the other font sizes of your elements
a font size of 90% in your body rule, then
in relation to their parent. What’s so great
that would be 90% of the default font size,
about that? Wel , if you need to change the

A: They are basicaly two diferent ways which we just said is usualy 16 pixels, so font size, then all you need to do is change
to achieve the same thing. Both give you a

90% would be about 14 pixels. If you’d like a
the body font size, and everything else will
way to specify a size relative to the parent
font size slightly dif erent than the keywords
change in proportion.

font size. A lot of people find percent easier
provide, go ahead and use % or em.

Q:

to think about than em, and also easier

Do we really need to worry about
to read in your CSS. But you should use

Q: There seems to be so many
users resizing their browser fonts? I
whichever you want.

differences between browsers: font-
never do that.

Q:

family, font-size, various default settings,
and so on. How wil I ever know if my

A:

If I don’t specify any font sizes, do

I just get the default font sizes?

design looks good on other browsers?

Yes. Almost al browsers al ow their
user to make the text of a page bigger or
smal er, and many users take advantage

A:

A:

Yes, and what those sizes are

Great question. The easy answer
of this feature. If you define your fonts in a
depends on your browser, and even the
is that if you follow the guidelines in this
relative manner, then your users wil have no version of the browser you are running. But chapter then most of your designs are going trouble doing this. Just be careful not to use
in most cases the default body font size will
to look just fine in other browsers. However,
pixel sizes, because some browsers have
be 16 pixels.

you should know that they may look slightly
problems resizing those.

dif erent in dif erent browsers – the fonts

Q:

Q:

may be slightly bigger or smal er, spacing

And what are the default sizes for
here and there may be dif erent, etc. But,

I like the idea of using pixels
the headings?

all the differences should be very minor
because then my page wil look exactly
and should not af ect the readability of your
like I specify it.

A:

pages.

A:

Again, it depends on the browser,

However, if you really care about having
but in general, <h1> is 200% of the default

There is some truth to that – by
your pages looking almost identical in many
body text font size, <h2> is 150%, <h3>
using pixels for every element’s font size,
browsers, then you real y need to test them
is 120%, <h4> is 100%, <h5> is 90%, and
you are choosing the precise font size you
in lots of browsers. And, to real y take this

<h6> is 60%. Notice that by default <h4> is
want for each element. But you do that at
to the extreme, you’l find a variety of CSS
the same font size as the body font size, and
the cost of giving some of your users (the

“hacks” to try to make dif erent browsers

<h5> and <h6> are smaller.

ones using certain versions of Internet
behave the same. If you want to take it this

Explorer) the flexibility to pick a font size that
far, there’s nothing wrong with that, but just
is appropriate for their display and eyesight.

keep in mind a lot of these activities take
time and have diminishing returns.

358

Chapter 9

styling with fonts and colors

Changing a font’s weight

Starbuzz Coffee

The font-weight property allows you to control

Beverages
how bold the text looks. As you know, bold text looks
font-weight: normal;
darker than normal text and tends to be a bit fatter too.

You can make any element use bold text by setting the
font-weight property to bold, like this:

font-weight: bold;

You can also go the other way. If you have an element
that is set to bold by default, or is inheriting bold from a parent, then you can remove the bold style like this:

font-weight: normal;

Starbuzz Coffee

Beverages

There are also two relative font-weight properties:

font-weight: bold;
bolder and lighter. These will make your text style a little bolder or a little lighter relative to its
inherited value. These values are seldom used and
because not many fonts allow for slight differences in
the amount of boldness, in practice these two values
often have no effect.

You can also set your font-weight property to a
number between 100 and 900, but again, this is not
well supported across fonts and browsers and so is
not often used.

Sharpen your pencil

Write the CSS to change the headings in Tony’s page from their default bold value to normal weight. Then, add the rule to your CSS and give it a test drive. You’l find the answer to this one on the next page.

you are here �

359

using normal weight

Test drive the normal weight headings

Here’s what your CSS should look like after you make the change to use a normal font-weight for both the <h1> and <h2> headings: body {

font-family: Verdana, Geneva, Arial, sans-serif;

font-size: small;

}h1, h2 {

font-weight: normal;

}h1 {

font-size: 170%;

}h2 {

font-size: 130%;

}

Here we’re changing the font-weight
of both headings to normal in the
same CSS rule. It’s a good idea to
combine common properties into one
rule like this to avoid duplication.

And here are the results. The
headings are now lighter looking.

360

Chapter 9
styling with fonts and colors

Adding style to your fonts

You’re familiar with italic text, right? Italic text is slanted, and sometimes has extra curly serifs.

For example, compare these two styles:

not italic

The italic text is slanted to the right

Italic and oblique styles
italic
and has extra curls on the serifs.

are two styles that

You can add an italic style to your text in
give fonts a slanted

CSS using the font-style property:

A common mistake is to
write “italic” as “italics”.

appearance.

font-style: italic;

If you do, you won’t see
italic text. So remember
to check your spelling.

Unless you can control

However, not all fonts support the italic style,
so what you get instead is called oblique text.

the fonts and browsers

Oblique text is also slanted text, but rather
than using a specially designed slanted set of
your visitors are
characters in the font, the browser just applies
a slant to the normal letters. Compare these
using, you’l find that
non oblique and oblique styles:

sometimes you get italic,
not oblique

The regular letters are
slanted to the right in
and sometimes oblique,
oblique
the oblique style.

no matter which style

You can use the font-style property
you specify.

to get oblique text too, like this:

font-style: oblique;

So just go with italic

In practice, you’re going to find that, depending
on your choice of font and browser, sometimes
and don’t worry about
the two styles will look identical, and sometimes
the differences (you
they won’t. So, unless italic versus oblique is
very important to you, choose one and move
probably can’t control
on. If, on the other hand, it is important, you’ll
need to test your font and browser combination
them anyway).

for the best effect.

you are here �

361

using a font style

Styling Tony’s quotes
with a little italic

Now we’re going to use the font-style property
to add a little pizazz to Tony’s quotes. Remember
the Burma Shave slogan in the <blockquote>
element? We’re going to change the slogan to italic
style to set it off from the rest of the text. To do that we just need to style the <blockquote> with a font-style of italic, like this:

blockquote {

font-style: italic;

}

Add this new CSS rule to the CSS in your

“journal.css” file, save it, and give the page a
test drive. You should see the Burma Shave
slogan change to italic; here’s our test drive.

there are no

Dumb Questions

Q: The text for the <blockquote> is actualy inside a <p> that’s inside the <blockquote>. So, how did this change the paragraph to italic?

A: Remember, by default most elements get their font
styles from their parents, and the parent of this paragraph is the <blockquote> element. So the paragraph within the

<blockquote> inherits the italic style.

Q: Why didn’t we just put the text into an <em>
element inside the <blockquote>? Wouldn’t that do the same thing and make the <blockquote> italic?

Here’s the new style on the Burma Shave
slogan in Tony’s page. We got slanted text,
just like we wanted.

A: Remember that <em> is for specifying structure.

<em> says that a set of words should be emphasized. What we’re doing is styling a <blockquote>, we are not indicating that the text in the <blockquote> should be emphasized. So, while you’re right, on most browsers <em> is styled with italic, it’s not the right way to style the text in the <blockquote>.

Also, keep in mind that the style of <em> could change, so you shouldn’t count on <em> always being italic.

362

Chapter 9

styling with fonts and colors

Cool. Love the new look. Hey,
how about a little color in those
fonts? Say, ummm... the color of
my shirt? I love orange!

You’d think we could just tell you there
was a color property and send you on
your way to use it. But, unlike font sizes
or weights or text styles, you’ve got to
understand a fair bit about color to be able
to work with it and specify it in CSS.

So, over the next few pages, you’re going
to dive into color and learn everything
you need to know to use it on your pages:

how colors on the screen work, the various
ways of describing color in CSS, what
those mysterious hex codes are all about,
whether you should be worried about

“Web safe colors,” and what’s the easiest
way to find and specify colors.

you are here �

363
overview of web colors

How do Web colors work?

You’re starting to see that there are lots of places you can add color to your pages: background colors, border colors, and soon, font colors as well. But, how do colors on a computer actually work? Let’s take a look.

Web colors are specified in terms of how
much red, green, and blue make up the
color. You specify the amount of each
color from 0 to 100% and then add them

100% Red

100% Blue
all together to arrive at a final color. For
instance if you add 100% red, 100% green,
and 100% blue together, you get white.

Notice that on a computer screen, mixing
together colors results in a lighter color.

After all, this is light we’re mixing!

100% Green

Here’s red, green and blue being
mixed together. If you look at the
center you’ll see how they all add up.

60% Red

60% Blue

But, if you add, say, only 60% of each
component (red, green, and blue) then
what would you expect? Less white,
right? In other words, you get a gray
color, because we’re sending equal
amount of the three colors, but not as

60% Green
much light to the screen.

364

Chapter 9
styling with fonts and colors

On a computer screen, if 0% blue is added,
then blue doesn’t add anything to the color.

Or, say you mix together 80% red and 40%
green. You’d expect an orange color, right?

Well, that’s exactly what you’ll get. Notice

80% Red

0% Blue
that if a color is contributing zero, then it
doesn’t affect the other two colors. Again,
this is because there is no blue light being
mixed with red and green.

Mixing 80% red and

40% Green

40% green we get a
nice orange color.

And what if you mix 0% of red, green, and
blue, then what do you get? That means

0% Red

0% Blue
you’re sending no light of any kind to the
screen, so you get black.

0% Green
you are here �

365

the color names

Why do I need to know all
this “color theory”? Can’t I just
specify my colors by name? Like

“red”, “green”, or “blue”? That’s
what we’ve been doing so far.

You certainly can use
color names all you
like, but CSS defines the
names of only 17 colors.

Having seventeen colors in your palette
gets old pretty quickly and really limits
the expressiveness of your pages. We’re
going to show you how to specify colors
in a way that will allow you to name a
lot more than seventeen colors; in fact,
you’ll be able to work from a palette of
sixteen million colors.

Now, you’ve already seen a few examples
of colors in XHTML, and yes, they do
look a little funky, like #fc1257. So,
let’s first figure out how to specify colors
and then you’ll see how you can easily
use color charts or your photo-editing
application to pick your colors.

366

Chapter 9
styling with fonts and colors

How do I specify Web colors?

Let me count the ways...

CSS gives you a few ways to specify colors. You can specify the name of a color, specify a color in terms of its relative percentages in red, green and blue, or you can specify your color using a hex code, which is shorthand for describing the red, green, and blue components of the color.

While you might think that the Web would have decided on one format by now, all these formats are commonly used, so it’s good to know about them all. However, hex codes are by far the most common way of specifying Web colors. But, remember that all these ways of specifying color ultimately just tell the browser the Aqua

Black
amount of red, green, and blue that goes into a color.

Let’s work through each method of specifying colors in CSS.

Specify color by name

Blue

Fuchsia

The most straightforward way to describe a color in CSS is just to use its name. But, as you know, there are only seventeen colors that can Gray

Green
be specified this way. Let’s say you want to specify the color “silver”

as the background color of a body element; here’s how you write that in CSS:

Lime

Maroon
body {

background-color: silver;

Navy

Olive

}

Here’s the body rule.

And the background-color

And the color

Orange

Purple
property.

written as a name.

Red

Silver

So, to specify a color by name, just type the color name as the value of the property. CSS color names are case-insensitive, so you can type silver, Silver, or SILVER and all will work. Here are the Teal

White
seventeen predefined colors in CSS. Remember these are just names for predefined amounts of red, green, and blue.

Yellow

Color in a book happens by light bouncing off the printed page.

On a computer, the light is emitted by the screen, so these colors will look slightly different in your Web pages.

you are here �

367
using rgb values

Specify color in red, green and blue values

You can also specify a color as the amount of red, green, and blue. So, 80% Red
say you wanted to specify the orange color we looked at a couple of 0% Blue
pages back, which consisted of 80% red, 40% green, and 0% blue.

Here’s how you do that:

body {

40% Green

background-color: rgb(80%, 40%, 0%);

}

Begin with “rgb”, s

And then specify the percentages for
hort
for red, green, blue.

red, green, and blue within parentheses,
and with a % sign after each one.

You can also specify the red, green, and blue values as a numeric value between 0 and 255. So, instead of 80% red, 40% green, and 0% blue, Where did these numbers come from?

you can use 204 red, 102 green, and 0 blue.

80% of 255 is 204,

Here’s how you use straight numeric values to specify your color: 40% of 255 is 102, and

0% of 255 is 0.

body {

background-color: rgb(204, 102, 0);

}

To specify numeric values and not

We still start with “rgb”.

percentages, just type in the value
and don’t use a “%”.

there are no

Dumb Questions

Q: Why are there two different ways photo-editing applications often alow you widely used because people consider them to specify rgb values? Don’t percentages
to specify color values from 0 to 255 (if not,
a convenient way to specify color.

seem more straightforward?

you’ll see how to do that shortly).

Q:

A:

Q:

Is it important that I look at

Sometimes they are more

I never see anyone use rgb or
something like rgb(100, 50, 200) and
straightforward, but there is some sanity to
actual color names in their CSS. It seems know what color it is?

using numbers between 0 and 255. This
everyone uses the #00fc9a type of color
number is related to the number of values
codes.

A:

that can be held in one byte of information.

Not at all. The best way to know

So, for historical and technical reasons, 255

A:

what rgb(100, 50, 200) looks like is to load
is often used as a unit of measurement for

Using rgb percents or numeric
it in your browser or use a photo-editing
specifying red, green, and blue values in a
values are becoming more common, but you application to see it.

color. In fact, you might have noticed that
are right, “hex codes” are still the most

368

Chapter 9

styling with fonts and colors

Specify color using hex codes

Now let’s tackle those funky looking hex codes. Here’s the secret to them: each set of two digits of a hex code just represents the red, green, and blue component of the color. So the first two digits represent the red, the next two the green, and the last two represent the blue.

Like this:

Then specify the

Always start a hex code
red, green, and blue
with the # sign.

#cc6600 components, using
red green blue
two digits for each.

Wait a sec, how
is “f” or “c” a digit?

Those are letters!

Believe it or not, they are digits, but they’re
written using a notation only a computer
scientist could love.

Okay, here’s the second secret to reading hex codes: each set of two digits represents a number from 0 to 255. (Sound familiar?) The problem is that if we used numbers, we’d only be able to represent up to 99 in two digits, right? Well, not wanting to be constrained by something as simple as the digits 0-9, computer scientists decided they could represent all 255 values with the help of some letters too (A through F).

Let’s take a quick look at how hex codes really work and then we’ll show you how to get them from color charts or your photo editing application.

you are here �

369

understanding hex codes

The t wo minute guide to hex codes

The first thing you need to know about hex codes is that they aren’t based on ten digits (0 to 9) – they’re based on 16 digits (0 to F). Here’s how hex digits work: A

B

5

10

Using hex, you only need a single

4

6

9

11

C

3

12
digit to count all the way from

D

2

13

0 to 15. When you get above 9,

7 8

E
you start using letters.

1

14 F

15

0

So if you see a hex number like B, you know that just means 11. But, what does BB, or E1, or FF mean? Let’s disassemble a hex color and see what it actually represents.

In fact, here’s how you can do that for any hex color you might encounter.

Step one:

Separate the hex color into its three components.

Remember that each hex color is made up of a red, green and blue component.

The first thing you want to do is separate those.

Take your hex color and

#CC 66 00 break it up into its red,
green, and blue components.

Red

Blue

Green

CC

66

00

370

Chapter 9
styling with fonts and colors

Step two:

Convert each hex number into its decimal equivalent.

Now that you have the components separated you can compute the value for each from 0 to 255. Let’s start with the hex number for the red component: Take the right-most
number and write down

CC
its decimal value.

Now take the left-most

12
number and convert it to
its decimal value, and also
multiply it by 16.

12 * 16 = 192

Finally, add these two
numbers together.

192 + 12 = 204 So 204 is the decimal
equivalent of CC in hex.

Step three:

Now do this for the other two values.

Repeat the same method on the other two values. Here’s what you should get: To calculate 66, you have

CC

66

00

(6 * 16) + 6 = 102

To calculate 00, you have

204

102

0

(0 * 16) + 0 = 0

Step four:

There is no step four, you’re done!

That’s it. Now you’ve got the numbers for each component and you know exactly how much red, green, and blue go into the color. You can disassemble any hex color in exactly the same way. Now let’s see how you’ll usually determine Web colors.

you are here �

371

using a photo editor for web colors

Putting it all together

80% Red

0% Blue

You’ve now got a few different ways to specify colors. Take our orange color that is made up of 80% red, 40% green, and 0% blue. In CSS
we could specify this color in any of these ways:

40% Green
body {

background-color: rgb(80%, 40%, 0%);

Specify by the percentage

}

of red, green and blue.

body {

background-color: rgb(204, 102, 0);

Specify the amount of red, green and

}

blue on the scale 0-255.

body {

background-color: #cc6600;

Specify using a compact hex code.

}

How to find Web colors

The two most common ways to find Web colors are to use a color chart or an application like Photoshop Elements. You’ll also find a number of Web pages that allow you to choose Web colors and translate between rgb and hex codes.

Let’s check out Photoshop Elements (most photo-editing applications offer the same functionality).

Most photo-editing
applications provide a Color

Picker that allows you to
visually choose your color
by using one or more color
spectrums.

Once you’ve picked
a color, the Color

Color Pickers also

Picker will show
allow you to select
you the color as
only “Web safe” colors.

both rgb values and

We’ll talk about this
a hex code.

in a sec.

372

Chapter 9

styling with fonts and colors

Using an online color chart

You’ll also find some useful color charts on the

Web. These charts typically display Web colors
that are arranged according to a number of
different criteria with their corresponding hex
code. Using these colors is as easy as choosing
the colors you want in your page and copying
the hex codes into your CSS.

This chart is maintained by the wikipedia
at http://en.wikipedia.org/wiki/Web_colors

You’ll also find many others by searching
for “HTML color charts”.

Make sure you use the hex
code for your colors, not the
decorative name, which isn’t likely
to be supported across browsers.

there are no

Dumb Questions

Q:

you know have limited color displays, you
a dark hue for the text, and a light hue for
can pret y much count “Web-safe colors” as
the background. Some colors, when used

I heard that if I don’t use Web-safe a thing of the past.

together, can create strange visual ef ects
colors, my pages wil never look right on

(like blue and orange, or red and green),
other browsers. Why haven’t we talked
so try your color combinations out on some
about Web-safe colors?

Q: I know how to specify colors now, friends before launching them on the world.

but how do I choose font colors that work

A:

well together?

Back in the early days of Web

Q: I’ve seen hex codes like #cb0;
browsers, few people had computer screens
what does that mean?

that supported a lot of colors, so the

A: It would take an entire book to

Web-safe palet e of colors was created to
answer that question properly, but there
ensure that pages looked consistent on most are some basic guidelines to selecting A: You’re alowed to use shorthand
displays.

font colors. The most important is to use
if each two-digit pair shares the same

Today the picture has changed drastical y
colors with high contrast for the text and the
numbers. So, for instance, #ccbb00 can
and most Web users have computer
background to aid readability. For instance,
be abbreviated #cb0, or #11eeaa as #1ea.

displays that support mil ions of colors. So,
black text on a white background has the

However, if your hex code is something like
unless you have a special set of users that
highest contrast. You don’t always have to

#ccbb10, then you can’t abbreviate it.

stick with black and white, but do try to use
you are here �

373

put your hex skills to the test

Crack the Safe Challenge

Dr. Evel’s master plans have been locked away inside his personal safe and you’ve just received a tip that he encodes the combination in hex code. In fact, so he won’t forget the combination, he makes the hex code the background color of his home page. Your job is to crack his hex code and discover the combination to the safe. To do that, simply convert his Web color into its red, green, and blue decimal values and you’ll have the right-left-right numbers of his combination. Here’s the background Web color from his home page: body {

background-color: #b817e0;

}

Crack the code, and then write the combination here:

right
left
right

374

Chapter 9
styling with fonts and colors

Back to Tony’s page... We’re going to make the
headings orange, and add an underline too

Now that you know all about color, it’s time to add some color to Tony’s Web page. He wanted orange and he’s going to get orange. But, rather than making all his text orange – which would probably be unattractive and hard to read against a white background – we’re going to add a subtle splash of color in his headings.

The orange is dark enough that there is good contrast between the text and the background, and by color-coordinating with the orange in the photos (Tony’s shirt), we’re creating a color relationship between the headings and the photos that should tie the images and text together. And just to make sure the headings stand out and create separation between the journal entries, we’ll also add an underline to each heading. You haven’t seen how to add an underline yet, but let’s do it, and then we’ll look at more about text decorations.

Here are all the changes in the CSS. Make these changes in your “journal.css” file.

body {

font-family: Verdana, Geneva, Arial, sans-serif;

font-size: small;

}

We’re going to make both <h1> and <h2>
orange, so we’re putting the color property
h1, h2 {
in the shared rule.

font-weight: normal;

color: #cc6600;

Here’s the hex code for the orange color Tony
text-decoration: underline;
wants, otherwise known as rgb(80%, 40%, 0%).

}

h1 {

And here’s the way we create an

font-size: 170%;
underline. We use the text-decoration

}

property and set it to underline.

h2 {

font-size: 130%;

}

blockquote {

font-style: italic;

}

you are here �

375

testing and more hex colors

Test drive Tony’s orange headings

Once you’ve made the changes to your “journal.css”

file to add the color property to the “h1, h2” rule,
reload the Web page and check out the results.

Now both <h1> and <h2> headings
are orange. This ties in nicely with

Tony’s orange theme and shirt.

The headings are also set off further with underlines.

Hmmm... we thought this would be a good way to
distinguish the headings, but actually they seem to look
a little too much like clickable links, since people tend to think anything underlined in a Web page is clickable.

So, underlines may have been a bad choice.

Let’s quickly look at some other text
decorations, then we’ll reconsider these
underlines in the Web page.

Sharpen your pencil

What do all these colors have in common? Try each one in a Web page, say as a font color, or use your photo-editing application’s color picker to determine what colors they are by entering the hex code into the dialog box directly.

#111111

#444444

#777777

#aaaaaa

#dddddd

#222222

#555555

#888888

#bbbbbb

#eeeeee

#333333

#666666

#999999

#cccccc

376

Chapter 9
styling with fonts and colors

Everything you ever wanted to know about
text-decorations in less than one page

Text decorations allow you to add decorative effects to your text like underlines, overlines, line-throughs (also known as a strike-through) and, on some browsers, blinking text. To add a text decoration, just set the text-decoration property on an element, like this: This rule will cause the
em {

<em> element to have a

text-decoration: line-through;
line through the middle

}

of the text.

You can set more than one decoration at a time. Say you want underline and overline at the same time, then you specify your text decoration like this: em {

This rule results in the <em>

text-decoration: underline overline;
element having an underline

}

AND overline.

And if you have text that is inheriting text decoration you don’t want, just use the value “none”: em {

text-decoration: none;

With this rule, <em> elements

}

will have no decoration.

there are no

Dumb Questions

Q:

your XHTML as content that should be

I’ve been meaning to ask why the
deleted. There is a similar element cal ed

<ins> that marks content that should be

Q:

color property isn’t called text-color?

inserted. Typical y browsers wil style these

So if I have two different rules for
elements with a strike-through and underline
an <em>, and one specifies overline and

A: The color property realy controls the respectively. And with CSS you can style the other underline, wil they be added
foreground color of an element, so it controls them any way you like. By using <del> and together so I get both?

the text and the border color, although you

<ins>, you are marking the meaning of your
can give the border its own color with the
content in addition to styling it.

A:

border-color property.

No. You need to combine the

Q: When would you use the blink
two values into one rule to get both text

Q:

decoration?

decorations. Only one rule is chosen for the

I like the line-through decoration.

text-decoration, and decorations in separate

Can I use it on text I’m editing to indicate
rules are not added together. Only the rule
things that need to be deleted?

A: Blink is a holdover from an old
that is chosen for the text-decoration styling

Netscape style. Browsers aren’t required
wil determine the decoration used, so the
to implement it, and most people consider
only way to get two decorations is to specify

A: You could, but there’s a better way. using blink to be in bad Web taste. So we them both in the same text-decoration

XHTML has an element we haven’t talked
recommend forgetting we ever mentioned it.

declaration.

about called <del> that marks content in
you are here �

377

using a border instead of an underline

Removing the underline...

Let’s get rid of that confusing underline and instead add
a nice bottom border like we did in the Lounge. To do
that, open your “journal.css” file and make these changes

Add a border on the bottom of the <h1> and
to the combined “h1, h2” rule:

<h2> elements. You can almost read this like

English: “add a thin, dotted line with the
h1, h2 {
color #888888 on the bottom border”...

font-weight: normal;

color: #cc6600;
border-bottom: thin dotted #888888;

... In the next chapter we are going to go into
text-decoration: underline;
borders in detail. Hang on, we’re almost there!

}

Delete the text decoration.

And here’s how our new “underline” looks.

Definitely more stylish and less confusing
than a text decoration underline.

Now we’ve got borders under the <h1>
and <h2> element, not underlines.

Notice that borders extend all the way
to the end of the page, rather than
just under the text. Why? You’ll find
out in the next chapter.

378

Chapter 9

styling with fonts and colors

BULLET POINTS

� CSS gives you lots of control over the look of your
the font sizes if users want the text to be bigger or
fonts, including properties like font-family, font-
smaller.

weight, font-size, and font-style.

� You can make your text bold using the font-weight

� A font-family is a set of fonts that share common

CSS property.

characteristics.

� The font-style property is used to create italic or

� The font families for the Web are serif, sans-serif,
oblique text. Italic and oblique text is slanted.

monospace, cursive, and fantasy. Serif and sans-

� Web colors are created by mixing different amounts
serif fonts are most common.

of red, green, and blue.

� The fonts that your visitors will see in your Web

� If you mix 100% red, 100% green, and 100% blue,
page depend on the fonts they have installed on
you will get white.

their own computers.

� If you mix 0% red, 0% green, and 0% blue, you will

� It’s a good idea to specify font alternatives in your
get black.

font-family CSS property in case your users don’t
have your preferred font installed.

� CSS has 17 predefined colors, including black,
white, red, blue, and green.

� Always make the last font a generic font like serif
or sans-serif, so that the browser can make an

� You can specify which color you want using
appropriate substitution if no other fonts are found.

percentages of red, green, and blue, using
numerical values of 0-255 for red, green, and blue,

� Font-sizes are usually specified using px, em, %, or
or using a color’s hex code.

keywords.

� An easy way to find the hex code of a color you

� If you use pixels (“px”) to specify your font size,
want is to use a photo-editing application’s color
you are telling the browser how many pixels tall to
picker or one of many online Web tools.

make your letters.

� Hex codes have 6 digits, and each digit can be from

� em and % are relative font sizes, so specifying your

0-F. The first two digits represent the amount of
font size using em and % means the size of the
red, the second two the amount of green, and the
letters will be relative to the font size of the parent
last two the amount of blue.

element.

� You can use the text-underline property to create an

� Using relative sizes for your fonts can make your
underline for text. Underlined text is often confused
pages more maintainable.

as linked text by users, so use this property

� Use the font size keywords to set the base font size
carefully.

in your body rule, so that all browsers can scale
you are here �

379

a crossword on color

XHTMLcross

You’ve absorbed a lot in this chapter: fonts, color, weights, and styles. It’s time to do another crossword and let it all sink in.

1

2

3

4

5

6

7

8

9

10

11

12

13

Across

Down

3. Hex codes use this many different digits.

1. Fonts with little barbs on them.

4. Colors like #111111 through #EEEEEE, are all

2. You can specify fonts in terms of pixels, em, or
shades of _____.

________.

5. Similar fonts are grouped into ______.

3. Considered cleaner and easier to read on a

7. Browser that doesn't handle pixel font sizes
computer display.

well.

6. When you specify fonts in the font-family

8. Element that can be used to mark text for
property, you are specifying ______.

deletion.

11. A text decoration you would never use.

9. em and % are both this kind of size.

10. Font family almost never used in Web pages.

12. Controls how bold a font looks.

13. Underline and line-through are examples of
text _______.

380

Chapter 9

styling with fonts and colors

Markup Magnets Solutions

Your job is to help the fictional fonts below find their way home to their own font family. Move each fridge magnet on the left into the correct font family on the right. Check your answers before you move on. Here’s the solution.

Monospace Family

Fantasy Family

Messenger

Crush

Bainbridge

Cursive Family

Sans-serif Family

Iceland

Cartoon

Angel

Nautica

Serif Family

Savannah

Quarter

Palomino
you are here �

381

exercise solutions

Crack the Safe Solution

Dr. Evel’s master plans have been locked away inside his personal safe and you’ve just received a tip that he encodes the combination in hex code. In fact, so he won’t forget the combination, he makes the hex code the background color of his home page. Your job is to crack his hex code and discover the combination to the safe. To do that, simply convert his Web color into its red, green, and blue decimal values and you’ll have the right-left-right numbers of his combination. Here’s the background Web color from his home page: body {

background-color: #b817e0;

}

Crack the code, and then write the combination here:

(11 * 16) + 8 =

(1 * 16) + 7 =

(14 * 16) + 0 =

23

224
right

184
left
right

382

Chapter 9

styling with fonts and colors

Sharpen your pencil

Solution

What do all these colors have in common? You
can try each one in a Web page, or use the color
picker to determine what colors they are, by
entering the hex code into the dialog box directly.

#111111

#222222

#333333

#444444

All colors that use just

#555555

#666666
one digit in their hex

#777777
codes are grays, from

#888888
very dark (almost black)

#999999
to very light (almost

#aaaaaa
white).

#bbbbbb

XHTMLcross

#cccccc

#dddddd

Solution

#eeeeee

1

2

S

P

E

E

3

4

R

S

I X T E

E N

G R A Y

I

A

C

5

6

F O N T

-

F A M I

L

I

E S

S

L

N

7

-

I N T E

R N E

T E X

P

L O R

E

R

S

E

8

9

D E

L

R

E

L A T

I

V

E

R

N

10

I

F A N T A S

Y

11

F

T

B

12

W E

I

G H T

L

V

I

13

D E

C O R A T

I O N

S

K

Across

Down
you are here �

383

3. Hex codes use this many different digits.

1. Fonts with little barbs on them. [serif]

[sixteen]

2. You can specify fonts in terms of pixels, em, or

4. Colors like #111111 through #EEEEEE, are all

________. [percent]

shades of _____. [gray]

3. Considered cleaner and easier to read on a

5. Similar fonts are grouped into ______. [font-
computer display. [sans-serif]

families]

6. When you specify fonts in the font-family

7. Browser that doesn't handle pixel font sizes
property, you are specifying ______. [alternatives]

well. [internetexplorer]

11. A text decoration you would never use. [blink]

8. Element that can be used to mark text for
deletion. [del]

9. em and % are both this kind of size. [relative]

10. Font family almost never used in Web pages.

[fantasy]

12. Controls how bold a font looks. [weight]

13. Underline and line-through are examples of
text _______. [decoration]

10 the box model

Getting Intimate
with Elements

I think we’d be a little
closer if it weren’t for all
the padding, margins, and
this damn table.

To do advanced Web construction you really need to know
your building materials. In this chapter we’re going to take a close look at our building materials: the XHTML elements. We’re going to put block and inline elements right under the microscope and see what they’re made of. You’ll see how you can control just about every aspect of how an element is constructed with CSS.

But we don’t stop there – you’ll also see how you can give elements unique identities.

And, if that weren’t enough, you’re going to learn when and why you might want to use multiple style sheets. So, turn the page and start getting intimate with elements.

this is a new chapter

385

what we’re going to do with the lounge

The lounge gets an upgrade

You’ve come a long way in nine chapters, and
so has the Head First Lounge. In fact, over

There’s a new graphic for the
the next two chapters, we’re giving it a total
header of the page.

upgrade with all new content for the main page
and restyling it from scratch. And, just to entice
you, we’re going to give you a little sneak peek
before we even get started. Check this out – on
this page you’ll find the new unstyled lounge
page with all the new content. On the next page
you’ll find the stylized version that we’re going to
create by the end of the next chapter.

The lounge guys have supplied a
lot of new text describing the
lounge and what it offers.

They’ve included a set of
elixir specials for the week.

And they even let visitors sample some of the
music that is played in the lounge each week, a
common request of customers.

Finally, they’ve got some legalese in the
footer of the page with a copyright.

386

Chapter 10

the box model

We’ve got headings that match the site’s
color theme, an aquamarine. The fonts
are also a very readable sans-serif.

This paragraph has been highly stylized, which helps
set it off from the text and gives the page an
attractive look. It also looks like the font is a serif
font, which is different from the main text.

The elixirs have been
dramatically restyled into an
appetizing display of drinks.

The elixirs have also been moved over to
the side. How did that happen?

The new and improved,
ultra-stylish lounge

Not too shabby. Now the Lounge design might

The music CDs and artists are And the footer is centered
be a tad on the, well, “ultra-stylish” side for
styled now too.

and displayed in a very
you, but hey, it is a lounge. And we’re sure
small font.

that you can see this design is starting to look
downright sophisticated – just think what the
same techniques could do for your pages. Well,
after this chapter and the next, designs like this
are going to be easily within your reach.

you are here �

387
starting with simple styles

Setting up the new lounge

Before we start the major construction, let’s get familiar with the new lounge.

Here’s what you need to do:

1

Take a look at the “chapter10/lounge” folder and you’ll find the file “lounge.html”, with all new content. Open the file in your editor and have a look around. Everything should look familiar: head, paragraphs, a few images, and a list.

2

You’re going to spend most of this chapter adding style to this XHTML, so you need a place for your CSS. You’re going to create all new styles for the lounge in the style sheet file “lounge.css”, so you’ll find your <link> element in the <head> of “lounge.html” is still there, but the previous version of “lounge.css” style sheet is gone.

<link type=”text/css” rel=”stylesheet” href=”lounge.css” /> Remember, this <link> element tells the browser to look for an external style sheet called

“lounge.css”.

3

Next, you need to create the new “lounge.css” in the “chapter10/lounge” folder. This file is going to hold all the new CSS for the new lounge.

Starting with a few simple upgrades

Now you’re all ready to start styling the lounge. Let’s add a few rules to your CSS just to get some basics out of the way – like the font family, size, and some color – that will immediately improve the lounge (and give you a good review from the last chapter). So, open your “lounge.css” and add the following rules.

Here’s the default
body {
font size for the page.

font-size: small;

font-family: Verdana, Helvetica, Arial, sans-serif;

}

We’re going to go with a sans-serif font-
h1, h2 {
family for the lounge. We’ve picked a few

color: #007e7e;
font alternatives, and ended the declaration

}

with the generic sans-serif font.

We’re going to set the color of the <h1> and <h2> h1 {
elements to an aquamarine to match the glass in the logo.

font-size: 150%;

}

h2 {

Now let’s get some reasonable heading sizes for <h1> and <h2>.

font-size: 130%;

Since we’re setting two different sizes for these, we need separate

}

rules and can’t add them to the combined rule for <h1> and <h2>.

388

Chapter 10

the box model

A very quick test drive

Let’s do a quick test drive just to see how these
styles affect the page. Make sure you’ve made all the
changes; then save, and test.

Headings are now sans-serif
and a color that matches
the logo, creating a theme
for the page.

Paragraph text is also sans-serif
since every element inherits the

<body>’s font-family property.

The <h2> heading is also
styled with a new color and
sans-serif, but a tad smaller.

We haven’t applied any styles

This link looks oddly out of place
to the <h3> so it just inherits
with its default blue color. We’ll
the font-family property
have to fix that (later).

from <body>.

One more adjustment

We’re going to make one more adjustment to the
lounge before we move on to start making some bigger
changes. This adjustment involves a new property
you haven’t seen before, but, at this point, you’ve got
enough experience under your belt that we’re not going
to treat you with kid gloves every time a new property

Increasing the line height of your text
comes along. So, just jump in and give it a try.

can improve readability. It also gives

Here’s what we’re going to do: we’re going to adjust the
you another way to provide contrast
line height of the text on the entire page so that there’s between different parts of your page
more vertical space between each line. To do that we

(you’ll see how that works in a bit).

add a line-height property in the body rule:

Here we’re changing the space between each line to 1.6em,
body {
in other words, 1.6 times the font size.

font-size: small;

font-family: Verdana, Helvetica, Arial, sans-serif;

line-height: 1.6em;

}

you are here �

389

learning about line height

Checking out the new line height

As you might have guessed, the line-height property allows you to specify the amount of vertical space between each line of your text. Like other font-related properties, you can specify the line height in pixels, or using an em or percent value that’s relative to the font size.

Let’s see what the effect of the line-height property is on the lounge. Make sure you add the line-height property to your CSS file and then save. You should see the line height increase when you refresh.

Using the line-height property we’ve
increased the space between each line of
text from the default to 1.6em.

Before

After

The space between lines is
known as “leading” in the
publishing industry.

The line-height property is inherited, so by
setting it in the body, all the elements on the
page now have a line height of 1.6em.

Try a few different values for line-height, like 200%, .5em, and 20px to see the effect.

Which looks the best? The worst? Which is most readable? When you’re done, make Exercise
sure you change the line-height back to 1.6em.

390

Chapter 10

the box model

Getting ready for some major
renovations

After only a few pages of this chapter, you already have a ton of text style on the new lounge. Congrats!

Now things are going to get really interesting. We’re going to move from changing simple properties of elements, like size, color, and decorations, to really tweaking some fundamental aspects of how elements are displayed. This is where you move up to the big leagues.

But to move up to the big leagues, you’ve got to know the box model. What’s that? It’s how CSS sees elements. CSS treats every single element as if it were represented by a box. Let’s see what that means.

Every box is made up of a
content area along with optional

From the perspective of CSS, every
padding, border, and margins.

element is a box.

The content area, which holds
the content (text or an image,
for instance).

Our guarantee: at the lounge, we’re
committed to providing you, our guest,
with an exceptional experience every

The content area is surrounded
time you visit. Whether you’re just
by optional transparent padding.

stopping by to check in on email over
an elixir, or are here for an out-of-
the-ordinary dinner, you’ll find our
knowledgeable service staff pay attention

An optional border can be
to every detail. If you’re not fully satisfied
placed around the padding.

have a Blueberry Bliss Elixir on us.

And finally, an optional
transparent margin
surrounds everything.

All elements are treated as boxes:

paragraphs, headings, block quotes,
lists, list items, and so on. Even inline
elements like <em> and links are
treated by CSS as boxes.

you are here �

391

the box model

A closer look at the box model

You’re going to be able to control every aspect of the box with CSS: the size of the padding around the content, whether or not the element has a border (as well as what kind and how large), and how much margin there is between your element and other elements. Let’s check out each part of the box and its role: The content area holds the element’s
content. It’s typically just big enough
to hold the content.

What is the

Our guarantee: at the lounge, we’re
content area?

committed to providing you, our guest,

Every element starts with some
with an exceptional experience every
time you visit. Whether you’re just
content, like text or an image,
stopping by to check in on email over
and this content is placed inside
an elixir, or are here for an out-of-
a box that is just big enough

We’ve drawn an edge
the-ordinary dinner, you’ll find our
to contain it. Notice that the
around the content
knowledgeable service staff pay attention
to every detail. If you’re not fully satisfied
content area has no whitespace
area just so you know
have a Blueberry Bliss Elixir on us.

between the content and the
how big it is. But in a
edge of this box.

browser there is never
a visible edge around
the content area.

The browser adds optional padding around
the content area.

What is the padding?

Our guarantee: at the lounge, we’re

Any box can have a layer of padding
committed to providing you, our guest,
around the content area. Padding is
with an exceptional experience every
optional, so you don’t have to have it,
time you visit. Whether you’re just
stopping by to check in on email over
but you can use padding to create visual
an elixir, or are here for an out-of-
whitespace between the content and
the-ordinary dinner, you’ll find our
the border of the box. The padding
knowledgeable service staff pay attention
is transparent and has no color or
to every detail. If you’re not fully satisfied
decoration of its own.

have a Blueberry Bliss Elixir on us.

Using CSS, you’re going to be able to control the width of
the padding around the entire content area, or even control the padding on any one side (top, right, bottom, or left).

392

Chapter 10

the box model

Notice that the padding
separates the content area

Using CSS, you’re going to be able to control
from the border.

the width, color, and style of the border.

What is the border?

Our guarantee: at the lounge, we’re

Elements can have an optional
committed to providing you, our guest,
border around them. The border
with an exceptional experience every
surrounds the padding and,
time you visit. Whether you’re just

Border.

because it takes the form of a
stopping by to check in on email over
line around your content, borders
an elixir, or are here for an out-of-
the-ordinary dinner, you’ll find our
provide visual separation between

Padding.

knowledgeable service staff pay attention
your content and other elements
to every detail. If you’re not fully satisfied
on the same page. Borders can be
have a Blueberry Bliss Elixir on us.

Content.

various widths, colors, and styles.

Using CSS, you’re going to be able to control
the width of the entire margin, or of any
particular side (top, right, bottom, or left).

What is the margin?

The margin is also optional and

Our guarantee: at the lounge, we’re
surrounds the border. The
committed to providing you, our guest,
margin gives you a way to add
with an exceptional experience every
space between your element
time you visit. Whether you’re just
stopping by to check in on email over
and other elements on the
an elixir, or are here for an out-of-
same page. If two boxes are
the-ordinary dinner, you’ll find our
next to each other, the margins
knowledgeable service staff pay attention
act as the space in between
to every detail. If you’re not fully satisfied
them. Like padding, margins are
have a Blueberry Bliss Elixir on us.

transparent and have no color or
decoration of their own.

This is the entire element. We have a

Content.

content area, surrounded by optional
padding, surrounded by an optional border,

Padding.

Margin.

surrounded by an optional margin.

Border.

you are here �

393

how boxes can be configured

What you can do to boxes

The box model may look simple with just the content,
some padding, a border, and margins. But when you
combine these all together there are endless ways
you can determine the layout of an element with its
internal spacing (padding) and the spacing around it

(margins). Take a look at just a few examples of how
you can vary your elements.

Boxes

Borders

You can style a box to

Our guarantee: at the lounge, we’re

Our guarantee: at the lounge, we’re
committed to providing you, our guest,
have padding, a border,
committed to providing you, our guest,
with an exceptional experience every
with an exceptional experience every
time you visit. Whether you’re just
time you visit. Whether you’re just
and a margin.

stopping by to check in on email over
stopping by to check in on email over
an elixir, or are here for an out-of-
an elixir, or are here for an out-of-
the-ordinary dinner, you’ll find our
the-ordinary dinner, you’ll find our
knowledgeable service staff pay attention
knowledgeable service staff pay attention
to every detail. If you’re not fully satisfied
to every detail. If you’re not fully satisfied
have a Blueberry Bliss Elixir on us.

have a Blueberry Bliss Elixir on us.

You can have solid
borders, thick or thin.

Our guarantee: at the lounge, we’re

Our guarantee: at the lounge, we’re
committed to providing you, our guest,
committed to providing you, our guest,

Or no border at all.

with an exceptional experience every
with an exceptional experience every
time you visit. Whether you’re just
time you visit. Whether you’re just
stopping by to check in on email over
stopping by to check in on email over
an elixir, or are here for an out-of-

Or, just
an elixir, or are here for an out-of-
the-ordinary dinner, you’ll find our
the-ordinary dinner, you’ll find our
knowledgeable service staff pay attention
to every detail. If you’re not fully satisfied
knowledgeable service staff pay attention
padding and
have a Blueberry Bliss Elixir on us.

to every detail. If you’re not fully satisfied
have a Blueberry Bliss Elixir on us.

a border.

Or choose from

Our guarantee: at the lounge, we’re

Our guarantee: at the lounge, we’re
committed to providing you, our guest,
committed to providing you, our guest,
eight different
with an exceptional experience every
with an exceptional experience every
time you visit. Whether you’re just
time you visit. Whether you’re just
stopping by to check in on email over
stopping by to check in on email over
styles of borders,
an elixir, or are here for an out-of-
an elixir, or are here for an out-of-
the-ordinary dinner, you’ll find our
the-ordinary dinner, you’ll find our
knowledgeable service staff pay attention

Or just a
knowledgeable service staff pay attention
like dashed.

to every detail. If you’re not fully satisfied
to every detail. If you’re not fully satisfied
have a Blueberry Bliss Elixir on us.

have a Blueberry Bliss Elixir on us.

border.

Our guarantee: at the lounge, we’re

Or even color
committed to providing you, our guest,

Our guarantee: at the lounge, we’re
with an exceptional experience every
committed to providing you, our guest,
with an exceptional experience every
your borders.

time you visit. Whether you’re just
time you visit. Whether you’re just

Or a margin wi
stopping by to check in on email over
th
stopping by to check in on email over
an elixir, or are here for an out-of-
an elixir, or are here for an out-of-
the-ordinary dinner, you’ll find our
the-ordinary dinner, you’ll find our
no border and no
knowledgeable service staff pay attention
knowledgeable service staff pay attention
to every detail. If you’re not fully satisfied
to every detail. If you’re not fully satisfied
have a Blueberry Bliss Elixir on us.

have a Blueberry Bliss Elixir on us.

padding.

394

Chapter 10

the box model

Padding

Margins

With CSS you can

Our guarantee: at the lounge, we’re
control padding on any You have the same
committed to providing you, our guest,
with an exceptional experience every
side of the content
time you visit. Whether you’re just
level of control over
stopping by to check in on email over
an elixir, or are here for an out-of-
area. Here we’ve got a
the-ordinary dinner, you’ll find our
the margins. Here

Our guarantee: at the lounge, we’re
committed to providing you, our guest,
knowledgeable service staff pay attention
to every detail. If you’re not fully satisfied
lot of left and right
with an exceptional experience every
there’s a lot of top
time you visit. Whether you’re just
have a Blueberry Bliss Elixir on us.

stopping by to check in on email over
padding.

an elixir, or are here for an out-of-
and bottom margin.

the-ordinary dinner, you’ll find our
knowledgeable service staff pay attention
to every detail. If you’re not fully satisfied
have a Blueberry Bliss Elixir on us.

And here a lot of top
and bottom padding.

Our guarantee: at the lounge, we’re
committed to providing you, our guest,
with an exceptional experience every
time you visit. Whether you’re just
stopping by to check in on email over
an elixir, or are here for an out-of-
the-ordinary dinner, you’ll find our

And here’s a lot of

Our guarantee: at the lounge, we’re
knowledgeable service staff pay attention
committed to providing you, our guest,
with an exceptional experience every
to every detail. If you’re not fully satisfied
have a Blueberry Bliss Elixir on us.

left and right margin.

time you visit. Whether you’re just
stopping by to check in on email over
an elixir, or are here for an out-of-
the-ordinary dinner, you’ll find our
knowledgeable service staff pay attention
to every detail. If you’re not fully satisfied
have a Blueberry Bliss Elixir on us.

And here the
content is
offset to the

Our guarantee: at the lounge, we’re
committed to providing you, our guest,
with an exceptional experience every
bottom right
time you visit. Whether you’re just

And like padding,
stopping by to check in on email over
an elixir, or are here for an out-of-
with padding on
the-ordinary dinner, you’ll find our
you can specify all
knowledgeable service staff pay attention

Our guarantee: at the lounge, we’re
to every detail. If you’re not fully satisfied
committed to providing you, our guest,
the top and left.

have a Blueberry Bliss Elixir on us.

with an exceptional experience every
sides independently
time you visit. Whether you’re just
stopping by to check in on email over
to create margins
an elixir, or are here for an out-of-
the-ordinary dinner, you’ll find our
knowledgeable service staff pay attention
like this.

to every detail. If you’re not fully satisfied
have a Blueberry Bliss Elixir on us.

Content Area

Our guarantee: at
the lounge, we’re
committed to
providing you, our

You can even control
guest, with an
exceptional experience

And

Our guarantee: at the lounge, we’re committed to providing
every time you visit.

width and height in a
you, our guest, with an exceptional experience every time you Whether you’re just
visit. Whether you’re just stopping by to check in on email over stopping by to check
here the
an elixir, or are here for an out-of-the-ordinary dinner, you’ll in on email over an
variety of ways. Here,
find our knowledgeable service staff pay attention to every elixir, or are here for
detail. If you’re not fully satisfied have a Blueberry Bliss Elixir an out-of-the-ordinary
content
on us.

dinner, you’ll find our
the content area has
knowledgeable service
staff pay attention to
area is tall
every detail. If you’re
been made wide.

not fully satisfied have
a Blueberry Bliss Elixir
but thin.

on us.

you are here �

395

some details about boxes
there are no

Dumb Questions

Q:

Q:

It seems like knowing this

I’m not sure I get how
box stuff would be important if I were
elements get laid out and how
someone creating the software for a
margins fit into that.

Web browser, but how is this going to
help me make better Web pages?

A: Hold that thought. While you’re

A:

going to see a lit le of how margins

To go beyond simple Web pages interact with other elements in this that use the browser’s default layout,
chapter, we’l get way into this topic
you need to be able to control how
in Chapter 11 when we talk about
elements sit on the page, as well as the
positioning.

relative position of other elements. To do
that, you alter various aspects of each

Q:

element’s padding and margins. So to

So other than size, it sounds
create interesting Web page designs,
like I can’t really style padding and
you definitely need to know something
margins?

about the box model.

Q:

A: That’s basically right. Both are

Hey guys, love the shop talk,

What’s the difference between used to provide more visual space, and really do. But did you forget
padding and margin? They seem like
you can’t give the padding or margin a
you were in the middle of
the same thing.

direct color or any kind of decoration.

renovating the lounge?

But, because they are transparent, they

A:

will take on the color of any background

The margin provides space
colors or background images. One
between your element and other
dif erence between padding and margins
elements, while padding gives you extra
is that the element’s background color
space around your content. If you have

(or background image) wil extend under
a visual border, the padding is on the
the padding, but not the margin. You’ll
inside of the border and the margin on
see how this works in a bit.

the outside. Think of padding as part of
the element, while the margin surrounds

Q:

your element and buf ers it from the

Is the size of the content area
things around it.

determined solely by the size of the
content in it?

Q: I know they are all optional,
but do you need to have padding to

A: Browsers use a lot of different
have a border or a margin?

rules to determine the width and height
of the content area, and we’l be looking

A:

at that more in-depth later. The short

No, they are all totally optional
answer is that you can set the width and
and don’t rely on each other. So you
height yourself if you need control over
can have a border and no padding, or a
the size of the element.

margin and no border, and so on.

396

Chapter 10

the box model

Meanwhile back at the lounge...

We do have our work cut out for us on the lounge page, so let’s get back to it. Did you notice the blue, stylized paragraph when you looked at the final version of the lounge page in the beginning of the chapter? This paragraph contains text with the lounge’s guarantee to their customers, and obviously they want to really highlight their promise. Let’s take a close look at this paragraph, and then we’ll build it.

The paragraph has a

And the text looks
blue background.

serif, not sans-serif,
and it’s italic.

There’s even a
graphic in the
paragraph.

Notice the

The text is offset
paragraph looks
from the border.

indented a bit.

There’s a stylish, ragged
looking border.

you are here �

397

working through padding, borders, and margins

Sharpen your pencil

See if you can identify the padding, border and margins of this paragraph.

Mark all the padding and margins (left, right, top, and bottom): brain
power

?

Before going on to the next page, think about how you might use padding, borders, and margins to transform an ordinary paragraph into the “guarantee paragraph.”

398

Chapter 10
the box model

Creating the guarantee style

Let’s get started by making a few small changes to the style of the guarantee paragraph just to get a feel for how the paragraph’s box is set up.

To do that you’re going to add the paragraph to a class called “guarantee”

so that you can create some custom styles for just this paragraph. You’re then going to add a border along with a little background color, which will let you see exactly how the paragraph is a box. Then we’ll get to work on the rest of the style. Here’s what you need to do:

1

Open your “lounge.html” file and locate the paragraph that starts “Our guarantee”. Add a class called “guarantee” to the element like this: Add the class attribute along with a value of “guarantee”.

Remember, a class will allow you to style this paragraph
independently of the other paragraphs.

<p class=”guarantee”>

Our guarantee: at the lounge, we’re committed to providing
you, our guest, with an exceptional experience every time you visit. Whether you’re just stopping by to check in on email over an elixir, or are here for an out-of-the-ordinary dinner, you’ll find our knowledgeable service staff pay attention to every detail. If you’re not fully satisfied have a Blueberry Bliss Elixir on us.

</p>

2

Save your “lounge.html” file and open the “lounge.css” file. You’re going to add a border and background color to the guarantee paragraph. Add the following CSS to the bottom of your style sheet and then save.

The first three properties add a border to any
element that is in the guarantee class. So far
that’s just this paragraph.

.guarantee {

We’re making the color of the border black...

border-color: black;

... and one pixel thick...

border-width: 1px;
border-style: solid;

... and solid.

background-color: #a7cece;

}

We’re also giving the element a background color, which
will help you see the difference between padding and
margins, and make the guarantee look good.

you are here �

399

a first cut on paragraph styling

A test drive of the paragraph border

Reload the page in your browser and you’ll now see the guarantee paragraph with an aquamarine background and a thin black border around it. Let’s examine this a little more closely...

It doesn’t look like the paragraph has any
padding around the content - there is no
space between the text and the border.

There isn’t a noticeable margin between

But there does seem to be a margin on the top
the left and right edges of the
and bottom of the paragraph element.

paragraph and the browser window edges.

Here’s what the paragraph would look like if we drew it
as a box model diagram:

We’ve got a top and bottom margin.

Our guarantee: at the lounge, we’re committed to providing you, our guest, with an exceptional experience every time you visit. Whether you’re just stopping by to check in on email over an elixir, or are here for an out-of-the-ordinary dinner, you’ll find our knowledgeable service staff pay attention to every detail. If you’re not fully satisfied have a Blueberry Bliss Elixir on us.

But the left and right

And we have a border, but it’s right up against the content, which margins are very small.

means the padding is set very small, or there’s no padding at all.

400

Chapter 10

the box model

Padding, border, and margins for the guarantee

Now that you’ve seen how the padding, border, and margins are currently set on the guarantee paragraph, let’s think more about how we’d actually like them to look.

We definitely need some padding
all around the content.

Our guarantee: at the lounge, we’re
committed to providing you, our guest,
with an exceptional experience every
time you visit. Whether you’re just
stopping by to check in on email over
an elixir, or are here for an out-of-
the-ordinary dinner, you’ll find our
knowledgeable service staff pay attention
to every detail. If you’re not fully satisfied
have a Blueberry Bliss Elixir on us.

We’re also going to need a

And we want some more margin
slightly different border.

space around the paragraph.

This border looks ragged,
not like a solid line.

Adding some padding

Let’s start with the padding. CSS has a padding property that you can use to set the same padding for all four sides of the content. You can set this property either to a number of pixels or a percentage of area inside the border. We’ll use pixels and set the padding to 25 pixels.

.guarantee {

border-color: black;
border-width: 1px;
border-style: solid;
background-color: #a7cece;

We’re adding 25 pixels of padding
padding: 25px;
to all sides of the content (top,

}

right, bottom, and left).

you are here �

401

testing the padding

A test drive with some padding

When you reload the page in your browser, you’ll notice the text in the guarantee paragraph has a little more breathing room on the sides now. There’s some space between the text and the border, and it’s much easier to read.

Notice that the background
color is under both the content

Now you can see 25 pixels of space between the
and the padding. But it doesn’t
edge of the text content and the border.

extend into the margin.

Now let’s add some margin

Margins are easy to add using CSS. Like padding, you can
specify the margin as a percentage or in pixels. You’re going to add a 30-pixel margin around the entire guarantee paragraph.

Here’s how you do that:

.guarantee {

border-color: black;
border-width: 1px;
border-style: solid;
background-color: #a7cece;
padding: 25px;

We’re adding 30 pixels of margin to all sides of the
margin: 30px;
content (top, right, bottom, and left).

}

402

Chapter 10

the box model

A test drive with the margin

When you reload the lounge page, you’ll see the paragraph is really beginning to stand out on the page. With the margins in place, the paragraph looks inset from the rest of the text, and that, combined with the background color, makes it look more like a “call out” than an ordinary paragraph. As you can see, with only a few lines of CSS, you’re doing some powerful things.

Now we have 30 pixels of margin on all sides.

If you look at the guarantee paragraph as it’s supposed to look in its final form, it has an italic, serif font, a line height greater than the rest of the page, and if you’re looking real y close, gray text. Write the CSS below to set the line height Exercise
to 1.9em, the font style to italic, the color to #444444, and the font family to Georgia, “Times New Roman”, Times, serif. Check your CSS with the answers in the back of the chapter, then type it in and test.

you are here �

403

background images

Adding a background image

You’re almost there. What’s left? We still need to get the white “guarantee star”

graphic into the paragraph and work on the border, which is a solid, black line.

Let’s tackle the image first.

If you look in the “chapter10/lounge/images” folder, you’ll find a GIF image called

“background.gif ” that looks like this:

This image is a simple star-like
pattern in white against a
transparent background. Notice
that it also has a matte around
it that matches the color of
the background.

Now, you just need to get that image into your paragraph element, so you’ll be using an <img> element, right? Not so fast. If you’re adding an image to the background of an element, there is another way. Using CSS, you can add a background image to any element using the background-image property.

Let’s give it a try and see how it works:

Here are the properties you added

.guarantee {
in the exercise on the previous page.

line-height: 1.9em;

font-style: italic;

font-family: Georgia, “Times New Roman”, Times, serif;

color: #444444;
border-color: black;
border-width: 1px;
border-style: solid;
background-color: #a7cece;
padding: 25px;
margin: 30px;
background-image: url(images/background.gif);

}

Add this to your CSS, save, and reload your page.

404

Chapter 10

the box model

Wait a sec, it seems
like we have two ways to put
images on a page. Is background-
image a replacement for the

<img> element?

No, the background-image property
has a very specific purpose, which is to set
the background image of an element. It isn’t
for placing images in a page – for that you
definitely want to use the <img> element.

Think about it this way: a background image
is pure presentation, and the only reason you
would use a background-image is to
improve the attractiveness of your element. An

<img> element, on the other hand, is used to
include an image that has a more substantial
role in the page, like a photo or a logo.

Now, we could have just placed the image
inside the paragraph, and we could probably
get the same look and feel, but the guarantee
star is pure decoration – it has no real meaning
on the page and it’s only meant to make
the element look better. So, background-
image makes more sense.

you are here �

405

more about the background-image property

Test driving the background image

Well, this is certainly an interesting test drive – we have a background image, but it appears to be repeated
many times. Let’s take a closer look at how to use CSS
background images, and then you’ll be able to fix this.

Here’s the guarantee star image in the background.

Notice that it sits on top of the background color,
and because it has a transparent background, it
lets the color show through.

Also notice that background images, like the background
color, only show under the content area and padding,
and not outside the border in the margin.

CSS Up Close

The background-image property places an image in the background of an element. Two other properties also affect the background image: background-position and background-repeat.

background-image: url(images/background.gif);

The background-image property is set

Notice that no quotes are
to a URL, which can be a relative path
required around the URL.

or a full blown URL (http://...).

406

Chapter 10
the box model

Fixing the background image

By default, background images are repeated. Luckily there is a no-repeat value for the background-repeat property. Also, by default, browsers position a background image in the top, left of the element, which is where we want it, but let’s also add a background-position property just to give it a try.

.guarantee {

line-height: 1.9em;

font-style: italic;

font-family: Georgia, “Times New Roman”, Times, serif;

color: #444444;
border-color: black;
border-width: 1px;
border-style: solid;
background-color: #a7cece;
padding: 25px;
margin: 30px;
background-image: url(images/background.gif);
background-repeat: no-repeat;

You’ve got two new
background-position: top left;
properties to add.

}

We want the
background image

And we want it in
to not repeat.

the top left corner.

The background-position property sets the position of the image and can be specified in pixels, or as a percentage, or by using keywords like top, left, right, bottom, and center.

Places the image in the top, left of the element.

background-position: top left;

There are many different ways to position things in CSS and we’ll be talking more about that in two chapters.

By default, a background image is “tiled”, or repeated over and over to fill the background space.

The background-repeat property controls how this tiling behaves.

Here are the other background-repeat values you can use.

background-repeat: repeat;

Display the image once, don’t
no-repeat
repeat the image at all.

Sets the image to repeat both
repeat-x

Repeat the image only horizontally.

horizontally and vertically. This is the
repeat-y
default behavior.

Repeat the image only vertically.

inherit

Just do whatever the parent element does.

you are here �

407

getting more sophisticated with padding

Another test drive of the background image

Here we go again. This time, it looks like we’re
much closer to what we want. But, since this is a
background image, the text can sit on top of it. How
do we fix this? That’s exactly what padding is for!

Padding allows you to add visual space around the
content area. Let’s increase the padding on the left
and see if we can nail this down once and for all.

This is much better. Now
the image isn’t repeated.

But we’d really like for
the text not to run over
the top of the image.

How do you add padding only on the left?

For padding, margins, and even borders, CSS has a property for every direction: top, right, bottom, and left. To add padding on the left side, use the padding-left property, like this:

.guarantee {

line-height: 1.9em;

font-style: italic;

font-family: Georgia, “Times New Roman”, Times, serif;

color: #444444;
border-color: black;
border-width: 1px;

We’re using the padding-left property to
border-style: solid;
increase the padding on the left..

background-color: #a7cece;
padding: 25px;

Notice that we first set the padding on all sides
to 25 pixels, and then we specify a prop
padding-left: 80px;
erty for
margin: 30px;
the left side.

background-image: url(images/background.gif);
background-repeat: no-repeat;
background-position: top left;

Order matters here - if you switch the order, then

}

you’ll set the padding for the left side first, and then
the general padding property will set all sides back to 25
pixels, including the left side!

408

Chapter 10

the box model

Are we there yet?

Make sure you save your changes and reload the
page. You should see more padding on the left side
of the paragraph, and the text is now positioned
well with respect to the guarantee star. This is a
great example of where you use padding instead
of margins. If you need more visual space around
the content area itself, use padding, as opposed to if
you want space between elements or the sides of the
page, in which case, use margin. In fact, we could

The padding look

We could increase the
actually use a little more margin on the right side to
s great.

Now the tex
margin on the right
set the paragraph off even more. Let’s do that, and
t is well
positioned wi
now to give this a little
then all we need to do is fix the border.

th respect
to the graphic.

more of a “call out”

And we still need look on the page.

a better border.

How do you increase the margin just on the right?

You do this just like you did with the padding: add another property, See the pattern? There’s a property
margin-right, to increase the right margin.

to control all sides together, and
properties for each side if you want
to set them individually.

.guarantee {

line-height: 1.9em;

font-style: italic;

font-family: Georgia, “Times New Roman”, Times, serif;

color: #444444;
border-color: black;
border-width: 1px;
border-style: solid;
background-color: #a7cece;

Remember we’re already setting
padding: 25px;
the margins to be 30 pixels.

padding-left: 80px;
margin: 30px;

And now we’re going to override that setting for the right
side, and set it to 250 pixels.

margin-right: 250px;
background-image: url(images/background.gif);
background-repeat: no-repeat;
background-position: top left;

}

Add the new margin-right property and reload. Now the 250 pixels
paragraph should have 250 pixels of margin on the right side.

you are here �

409

overview of borders

A t wo-minute guide to borders

There’s only one thing left to do to perfect the guarantee paragraph: add a better border. Before you do, take a look at all the different ways you can control the border of an element.

Border Style

The border-style property controls the visual style of the border. There are eight border styles available, from a solid line to dotted lines to ridges and grooves.

border-style: groove;

To specify a border style just use the
border-style property and a value of one
of the available styles.

borders.html

09/30/2005 10:48 PM
borders.html

09/30/2005 10:49 PM

Solid

The solid style is
borders

Nothings

Go with solid,

The dotted
just what it sounds

Once you go
are the
the original.

style looks like
better
like, a solid border.

dotted you’ll
a series of dots.

looking
never go back.

only way
that dotted
to go

And the dashed
style is just a

Except

Ignore dotted,

The double style

But I'm

Go with
set of dashes
use dashed.

uses two lines.

dashed
double
double, I’m
round the
twice the fun.

border.

borders.html

09/30/2005 10:49 PM
good

Nah, inset

A groove style

The inset style

I like to

I’m the only
looks like a groove
borders

I’m the border
looks like an inset
think

“in” style:

in the page

Yea but I
that’s got the
that sinks into
are th
inset. e
outset of

(difficult to see
groove
groove.

the page.

way
in a book).

the box
borders.html

09/30/2005 10:49 PM
file:///Volumes/Macintosh%20HD/Users/eric/HFDP/HeadFirst/HTML/Chapters/Chapter9/Code/borders/borders.html Page 1 of 3
file:///Volumes/Macintosh%20HD/Users/eric/HFDP/HeadFirst/HTML/Chapters/Chapter9/Code/borders/borders.html Page 2 of 3

The ridge style

I like to

Ruffles

The outset style looks

Go with me, I’ve
looks like a raised

I’m more fun;
like an outset that
think
been better since
ridge on the page.

have

I’ve got ridges.

rises from the page.

outset
the
o
outset. f
ridged
the box
borders

Ruffles
have

410

Chapter 10
ridged
borders
file:///Volumes/Macintosh%20HD/Users/eric/HFDP/HeadFirst/HTML/Chapters/Chapter9/Code/borders/borders.html Page 3 of 3
file:///Volumes/Macintosh%20HD/Users/eric/HFDP/HeadFirst/HTML/Chapters/Chapter9/Code/borders/borders.html Page 3 of 3

the box model

Border Width

Border Color

The border-width property controls

The border-color property sets the color
the width of the border. You can use
of the border. This works just like setting
keywords or pixels to specify the width.

font colors; you can use color names, rgb
values, or hex codes to specify color.

border-width: thin;
border-color: red;
border-width: 5px;
border-color: rgb(100%, 0%, 0%);
border-color: #ff0000;

You can specify widths using the keywords thin,
medium, or thick, or by the number of pixels.

1px

Use border-color

2px
to specify the color

3px
of a border. You
can use any of the
thin

4px
common ways to
medium

5px
specify color.

thick

6px

Specifying Border Sides

Just like margins and padding you
border-top-color
border-right-color
can specify border style, width,
border-top-style
border-right-style
or color on any side (top, right,
bottom, or left):

border-top-width
border-right-width
border-top-color: black;
border-top-style: dashed;
border-top-width: thick;
border-bottom-color
border-left-color
border-bottom-style
border-left-style

These properties are for the top border
border-bottom-width
border-left-width
only. You can specify each side of the
border independently.

you are here �

411

getting fancy with borders

Border fit and finish

It’s time to finish off the guarantee paragraph. All we need to do is give it a ragged-looking border. But which style is that? The available styles are solid, double, dotted, dashed, groove, ridge, inset, and outset. So how do we make it look ragged? It’s actually just a trick: we’re using a dashed border that has its color set to white (matching the background color of the page). Here’s how you do it. Begin by just making the border dashed. Find the border-style property in your “lounge.css” and change it, like this: Here we’ve changed
border-style: dashed;
the border from solid

to dashed.

Go ahead and save the file and reload. You should see a border like this: Now, to get a ragged-looking border, just set the color of the border to white. This makes the border look like it is cutting into the background color. Give it a try: find the border-color property and set it to white.

border-color: white;

And here we’ve changed
the border color from

black to white.

Save the file and reload again. Now you should see the ragged border: Browsers don’t always agree on the size

Watch it! of thin, medium, and thick.

Browsers can have different default sizes for the
keywords thin, medium, and thick, so if the size
of your border is real y important to you, consider
using pixel sizes instead.

412

Chapter 10

the box model

Nice! I can’t wait to see
the entire page remodeled.

Take a break and have an
iced chai on me!

Congratulations!

Bravo! You’ve taken an ordinary HTML
paragraph and transformed it into something
a lot more appealing and stylish using only
fifteen lines of CSS.

It was a long trip getting here, so at this point
we encourage you to take a little break. Grab
yourself an iced chai and take a little time to
let things sink in – when you come back, we’ll
nail down a few more of the fine points of CSS.

you are here �

413

when to use classes

Welcome back, and good timing. We’re just about to listen
in on an interview with an XHTML class...

The Class Exposed

This week’s interview: are
classes always right?

Head First: Hey, Class; you know we’ve been making good use of you, but we still don’t know a lot about you.

Class: Well, there’s not all that much to know. If you want to create a “group, ”

so to speak, that you can style, just come up with a class, put your elements in it, and then you can style all the elements in that class together.

Head First: So the class lets you take sets of elements and apply one or more style properties to them?

Class: Exactly. Say you have some holiday-themed areas in your page; one Halloween, one Christmas. You could add all Halloween elements to the

“halloween” class and all Christmas elements to the “christmas” class. Then you can style those elements independently, say orange for Halloween and red for Christmas, by writing rules that apply to each class.

Head First: That makes a lot of sense. We just saw a good example of that in this chapter, didn’t we?

Class: I’m not sure, I was off working. You’ll have to catch me up.

Head First: Well, we have a paragraph on the Head First Lounge page that contains a written guarantee from the owners, and they want this paragraph to stand out independently of the other paragraphs.

Class: So far, so good... but let me ask you this: are there a few of these paragraphs, or just the one?

Head First: Well, I don’t think there is any reason to have multiple guarantee paragraphs and I don’t see the same style being applied anywhere else in the page, so just the one.

Class: Hmmm, I don’t like the sound of that. You see, classes are meant to be used for styles that you want to reuse with multiple elements. If you’ve got one unique element that you need styled, that’s not really what classes are for.

Head First: Wait a second – a class seemed to work perfectly... how can this be wrong?

Class: Whoa, now, don’t freak out. All you need to do is switch your class attribute to an id attribute. It will only take you a minute.

414

Chapter 10
the box model

Head First: An id attribute? I thought those were for those destination anchors, like in Chapter 4?

Class: ids have lots of uses. They’re really just unique identifiers for elements.

Head First: Can you tell us a little more about id attributes? This is all news to me. I mean, I just went through an entire chapter using class incorrectly!

Class: Hey, no worries; it’s a common mistake. Basically all you need to know is that you use a class when you might want to use a style with more than one element. And, if what you need to style is unique and there’s only one on your page, then use an id. The id attribute is strictly for naming unique elements.

Head First: Okay, I think I’ve got it, but why does it really matter? I mean, class worked just fine for us.

Class: Because there are some things you really want only one of on your page.

The guarantee paragraph you mentioned is one example; but there are better examples, like the header or footer on your page, or a navigation bar. You’re not going to have two of those on a page. Of course, you can use a class for just one element, but someone else could come along and add another element to the class, and then your element won’t have a unique style anymore. It also becomes important when you are positioning HTML elements, which is something you haven’t gotten to yet.

Head First: Well, okay, Class. This conversation has certainly been educational for us. It sounds like we definitely need to convert that paragraph from a class to an id. Thanks again for joining us.

Class: Anytime, Head First!

brain
power

?

Choose whether you’d use class or id for
the following elements:

id
class
id
class

❏ ❏ A paragraph containing the footer of a

❏ ❏ A set of <p> elements containing movie page.

reviews.

❏ ❏ A set of headings and paragraphs that

❏ ❏ An <ol> element containing your to do contain company biographies.

list.

❏ ❏ An <img> element containing a “picture

❏ ❏ <q> elements containing Buckaroo Bonzai of the day.”

quotes.

or using id.

tes f
t candida
ea
r
e g
list ar

, and the to do
y
the da
e of

, the pictur
ooter
he f
er: T

Answ
you are here �

415
identifying elements

The id attribute

Because you’ve already used ids on <a> elements, and because you already know how to use a class attribute, you’re not going to have to learn much to use the id attribute.

Say you have a footer on your page. There’s usually only one footer on any page, so that sounds like the perfect candidate for an id. Here’s how you’d add the identifier “footer” to a paragraph that contains the footer text:

Similar to a class, just add the

Unlike a class, you can only
attribute “id” and choose a
have one element in your
unique id name.

page with an id of “footer”.

<p id=”footer”>Please steal this page, it isn’t copyrighted in any way</p> Each element can
id names must start with a letter and be
have only one id.

followed by only letters and digits. No
spaces or special characters are allowed.

Giving an element an id is similar to adding an element to a class. The only differences are that the attribute is called “id”, not “class”, an element can’t have multiple ids, and you can’t have more than one element on a page with the same id.

there are no

Dumb Questions

Q:

What’s the big deal? Why do I need an id just to
instance, when you start positioning elements on a page, you’ll prove something is unique on the page? I could use a class need each element you want to position to have a unique id.

exactly the same way, right?

Q:

A:

Can an element have an id and also belong to a
class?

Well, you can always “simulate” a unique id with a class,
but there are many reasons not to. Say you’re working on a Web project with a team of people. One of your teammates is going A: Yes, it can. Think about it this way: an id is just a
to look at a class and think it can be reused with other elements. unique identifier for an element, but that doesn’t prevent it from If, on the other hand, she sees an id, then she’s going to know belonging to one or more classes (just like having a unique that’s for a unique element. There are a couple of other reasons name doesn’t prevent you from joining one or more clubs).

ids are important that you won’t see for a few chapters. For 416

Chapter 10
the box model

But how do I use id in CSS?

You select an element with an id almost exactly like you select an element with a class. To quickly review: if you have a class called “specials”, there are a couple of ways you can select elements using this class. You could select just certain elements in the class, like this:

p.specials {

color: red;

This selects only paragraphs that are in the specials class.

}

Or, you can select all the elements that belong to the “specials” class, like this:

.specials {

This selects all elements in the specials class.

color: red;

}

Using an id selector is very similar. To select an element by its id, you use a “#” character in front of the id (compare this to class, where you use a “.” in front of the class name).

Say you want to select any element with the id “footer”:

#footer {

color: red;

This selects any element that has the id “footer”.

}

Or, you could select only a <p> element with the id “footer”, like this: p#footer {

color: red;

This selects a <p> element if it has the id “footer”.

}

The only other difference between class and id is that an id selector should match only one element in a page.

you are here �

417
using and selecting an id

Using an id in the lounge

Our “guarantee paragraph” really should have an id since it’s intended to be used just once in the page. While we should have designed it that way from the beginning, making the change is going to be quite simple.

Step One: change the class attribute to an id in your “lounge.html”: Just change the class
attribute to an id.

<p id=”guarantee”>

Our guarantee: at the lounge, we’re committed to providing
you, our guest, with an exceptional experience every time you visit. Whether you’re just stopping by to check in on email over an elixir, or are here for an out-of-the-ordinary dinner, you’ll find our knowledgeable service staff pay attention to every detail. If you’re not fully satisfied have a Blueberry Bliss Elixir on us.

</p>

Step Two: change the “.guarantee” class selector in “lounge.css” to an id selector: Just change the “.” to a

“#” in the selector.

#guarantee {

line-height: 1.9em;

font-style: italic;

font-family: Georgia, “Times New Roman”, Times, serif;

color: #444444;
border-color: white;
border-width: 1px;
border-style: dashed;
background-color: #a7cece;
padding: 25px;
padding-left: 80px;
margin: 30px;
margin-right: 250px;
background-image: url(images/background.gif);
background-repeat: no-repeat;
background-position: top left;

}

418

Chapter 10

the box model

Step Three: save your changes and reload the page.

Well, everything should look

EXACTLY the same. But, don’t
you feel much better now that
everything is as it should be?

there are no

Dumb Questions

Q: So why did you make the selector #guarantee rather A: No. You’l often know when you design your pages if an than p#guarantee?

element is going to be unique or not. We only did things this way in the chapter because, wel , you didn’t know about id when we A:

started. But don’t you think we tied id into the story rather nicely?

We could have done either and they both would select
the same thing. On this page we know that we will always have a paragraph assigned to the id, so it doesn’t real y mat er (and

#guarantee is simpler). However, on a more complex set of pages Q: In Chapter 4 we used the id attribute with the <a> you might have some pages where the unique id is assigned to, element to create a destination anchor. When I put an id on say, a paragraph, and on others it’s assigned to a list or block other types of elements, do they become destinations too?

quote. So you might want several rules for the id, like p#someid, and blockquote#someid, depending on which kind of element is on the page.

A: That’s the idea, and most modern browsers support this,

Q:

but older browsers don’t.

Should I always start with a class, and then change it
to an id when I know it’s going to be unique?

you are here �

419

using more than one style sheet

Remixing style sheets

Before we wind this chapter down, let’s have a little fun
remixing some style sheets. So far you’ve been using only
one style sheet. Well, who ever said you can’t use more
than one style sheet? You can specify a whole set of style sheets to be used with any XHTML. But you may be
wondering why anyone would want to? There are a couple
of good reasons. Here’s the first one...

Imagine that the Head First Lounge takes off, gets
franchised, does the IPO, and so on (all thanks to you
and your terrific Web work, of course). Then there
would be a whole corporate Web site with hundreds of
pages, and obviously you’d want to style those pages
with external CSS style sheets. There would be various
company divisions and they might want to tweak the styles
in individual ways. And the lounge franchises also might
want some control over style. Here’s how that might look:

We use al the
corporate colors and
fonts, but we add in a few
special touches of our own, like
a different line height.

We’ve set up all
the main styles to be used

We’ve got a young,
by the company Web sites.

hip clientele. We tweak

Fonts, colors, and so on.

the colors a bit and add a little
edge, but overal we use the
division’s main styles.

Beverage

Division

Corporate

Seattle Lounge

(part of the Beverage

Division)

420

Chapter 10
the box model

Using multiple style sheets

So how do you start with a corporate style and then allow the division and the lounge franchises to override and make changes to the styles? You use several style sheets, like this:

In your XHTML you can
specify more than one style
sheet. Here, we’ve got three.

One style sheet

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”

for the entire

“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”> corporation.

<html xmlns=“http://www.w3.org/1999/xhtml” lang=“en” xml:lang=“en” >

<head>

<meta http-equiv=“Content-Type” content=“text/html; charset=ISO-8859-1” />

<title> Head First Lounge</title>

<link type=“text/css” href=“corporate.css” rel=“stylesheet” />

<link type=“text/css” href=“beverage-division.css” rel=“stylesheet” />

<link type=“text/css” href=“lounge-seattle.css” rel=“stylesheet” />

</head>

<body>

And the lounge in Seattle

.

has its own tweaks in

The beverage division can add

.

their style sheet.

to the corporate style a little,
or even override some of the

.

corporate styles.

</body>

Order matters! A style

</html>
sheet can override the
styles in the style sheets
linked above it.

there are no

Dumb Questions

Q: So the order of the style sheets Q: Do I ever need this for a simple Q: Can you say more about how the matters?

site?

style for a specific element is decided?

A: Yes, they go top to botom, with A: You’d be surprised. Sometimes A: We talked a litle about that in the style sheets on the bottom taking
there’s a style sheet you want to base your

Chapter 8. And for now, just add to that
precedence. So if you have, say, a font-
page on, and rather than changing that style knowledge that the ordering of the style family property on the <body> element in
sheet, you just link to it, and then supply
sheets linked into your file matters. Then in
both the corporate and the division style
your own style sheet below that to specify
the next chapter, after you’ve learned a few
sheets, the division’s takes precedence,
what you want to change.

other CSS details, we’re going to go through
since it’s the last one linked in the XHTML.

exactly how the browser knows which style
goes with which element.

you are here �

421

targeting media types

Style sheets - they’re not just for
desktop browsers anymore...

If you’re interested in more

And now for the second reason you might want to have multiple information on print styles
style files. Let’s say you want to have slightly different styles and styles for mobile devices,
for computer screens, PDAs, or mobile devices, and printed
endix for
check out the app
versions of your pages. There is an optional attribute for the some pointers.

<link> element called media, that you can use to specify the kinds of devices your style files are intended for.

The media attribute allows you to specify
the type of device this style sheet is for.

<link type=”text/css” rel=”stylesheet” href=”lounge-screen.css” media=”screen” /> Here we’re specifying that this
style sheet is appropriate for
computer screens.

You can specify multiple <link> elements with different media types in one XHTML file, like this:

If you don’t supply a media
type then the style file should
be suitable for all devices.

<link type=”text/css” href=”lounge.css” rel=”stylesheet” />

<link type=”text/css” href=”lounge-print.css” rel=”stylesheet” media=”print” />

<link type=”text/css” href=”lounge-mobile.css” rel=”stylesheet” media=”handheld” /> Now we have two other <link>
elements, one that specifies
print and one for small devices
with small screens and limited
communication speeds.

422

Chapter 10

the box model
there are no

Dumb Questions

Q: That’s pretty cool. So I can set Q: Say you have a “handheld” link Q: So we have screen (computers), up different style sheets for different
and a link that applies to all browsers;
print (print-like media), handheld (mobile
devices?

which one gets applied?

devices and cel phones). What else is
there?

A: Yes, you can set up several style A: The handheld browser wil grab both sheets and then link to them all in your
of them. But, assuming the “handheld” link

A: Here are a few more: aural (for

XHTML. It’s the browser’s job to grab the
is below the “al ” link, the handheld rules
speech browsers), Braille (for people
right style sheet based on the media type.

take precedence, just like we talked about
who need tactile readers), projection (for
before with the corporate, division, and
projected presentations or slides), tty
lounge CSS files.

(for teletypes and terminals), and tv (for
televisions, of course).

In your “chapter10/lounge/print” folder, you’l find “print.css”. Open up “lounge.html”

in the “chapter10/lounge” folder and add a new link to this style sheet for the media type “print”. Make sure you also add the at ribute media=“screen” to the <link> Exercise element that links to “lounge.css”, so you have one style sheet for the screen, and one for the printer. Then save, reload the page, and choose your browser’s “Print”

option. Run to the printer to see the result!

<link type=”text/css” href=”print/print.css”

rel=”stylesheet” media=”print” />

Here’s the new link you need to
add to your “lounge.html” file.

Here’s the printed version. You’ve totally
changed how the page looks when it’s
printed, using CSS. That structure versus
presentation thing is really paying off.

Unfortunately, not all browsers
support the media attribute, so if
you didn’t get this result, try a
newer browser.

Optional printer required, not included with book.

you are here �

423

review of boxes, backgrounds, classes, and ids

BULLET POINTS

n

CSS uses a box model to control how

n

Use the line-height property to add space
elements are displayed.

between lines of text.

n

Boxes consist of the content area and optional

n

You can place an image in the background
padding, border, and margin.

of an element with the background-image
property.

n

The content area contains the content of the
element.

n

Use the background-position and background-
repeat properties to set the position and tiling

n

The padding is used to create visual space
around the content area.

behavior of the background image.

n

Use the class attribute for elements that you

n

The border surrounds the padding and content
and provides a way to visually separate the
want to style together, as a group.

content.

n

Use the id attribute to give an element a
unique name. You can also use the id

n

The margin surrounds the border, padding,
and content, and allows space to be added
attribute to provide a unique style for an
between the element and other elements.

element.

n

There should only be one element in a page

n

Padding, border, and margin are all optional.

with a given id.

n

An element’s background will show under the
content and the padding, but not under the

n

You can select elements by their id using the
margin.

id # selector; for example #myfavoriteid.

n

An element can have only one id, but it can

n

Padding and margin size can be set in pixels
or percentages.

belong to many classes.

n

You can use more than one style sheet in your

n

Border width can be set in pixels or by using
the keywords thin, medium, and thick.

XHTML.

n

If two style sheets have conflicting property

n

There are eight different styles for borders,
including solid, dashed, dotted, and ridge.

definitions, the style sheet that is last in the

XHTML file will receive preference.

n

When setting margins, padding, or the border,

CSS provides properties for setting all the

n

You can target media devices such as “print”

sides (top, right, bottom, left) at once, or it
or “handheld” by using the media attribute in
allows them to be set independently.

your <link> element.

424

Chapter 10

the box model

XHTMLcross

You’re really expanding your HTML & CSS skills. Strengthen those neural connections by doing a crossword. All the answers come from this chapter.

1

2

3

4

5

6

7

8

9

10

11

12

Across

Down

2. CSS sees every element as a _____.

1. Publishing term for the space between lines.

4. The preferred font-style used in the guarantee
family

2. Which kind of elixir do you get if you're not
paragraph.

fully satisfed?

5. Optional <link> attribute for other kinds of

3. By default, background images do this.

______.

6. Property used to increase the space between

7. Between padding and margin.

lines of text.

9. We changed the ______ class to an id.

8. Padding, borders and margins are all ________.

10. If you want your element to have a unique style,
use this kind of selector.

11. The space between the content and the border.

12. Style of border we used on the guarantee
paragraph.

you are here �

425

exercise solutions

XHTMLcross Solution

1

2

L

B O X

3R

E

L

4G E O R G I A

U

5

6

P

D

M E D

I A

L

7

8

B O R D E

R

I

B

I

P

A

N

E

N

9

T

T

G U A R A N T E

E

10

I D

R

-

O

Y

H

N

B

E

A

L

I

11

L

P

A D D

I N G

G

S

H

12

D A S H E D

T

Across

Down

2. CSS sees every element as a _____. [box]

1. Publishing term for the space between lines.

4. The preferred font-style used in the guarantee

[leading]

paragraph. [georgia]

2. Which kind of elixir do you get if you're not

5. Optional <link> attribute for other kinds of
fully satisfed? [blueberrybliss]

______. [media]

3. By default, background images do this. [repeat]

7. Between padding and margin. [border]

6. Property used to increase the space between

9. We changed the ______ class to an id.

lines of text. [line-height]

[guarantee]

8. Padding, borders and margins are all ________.

10. If you want your element to have a unique style,

[optional]

use this kind of selector. [id]

11. The space between the content and the border.

[padding]

12. Style of border we used on the guarantee
paragraph. [dashed]

426

Chapter 10

the box model

Sharpen your pencil

See if you can identify the padding, border and margins of this paragraph.

Solution

Mark all the padding and margins (left, right, top, and bottom): Top margin

Top padding

Right
padding

Left

Right
margin
margin

Left
padding

Bottom padding

Bottom margin
you are here �

427

exercise solutions

If you look at the guarantee paragraph as it’s supposed to look in its final form, it has a italic, serif font, a greater line height than the rest of the page, and if you’re Exercise
looking real y close, gray text. Write the CSS below to set the line height to 1.9em, Solutions
the font style to italic, the color to #444444, and the font family to Georgia, ‘Times New Roman’, Times, serif. Here’s the solution... did you test it?

You can add the new properties anywhere in
the rule. We added them at the top.

.guarantee {

line-height: 1.9em;

font-style: italic;

font-family: Georgia, “Times New Roman”, Times, serif;

color: #444444;
border-color: black;
border-width: 1px;
border-style: solid;

Notice that if a font name has spaces in it
background-color: #a7cece;
you should surround it with quotes.

padding: 25px;
margin: 30px;

}

An italic, serif font.

Increased line height.

Gray color gives the
text a softer look.

428

Chapter 10

11 divs and spans

Advanced Web Construction

Some builders say

“measure twice, cut once.”

I say “plan, div, and span.“

It’s time to get ready for heavy construction. In this chapter we’re going to roll out two new XHTML elements, called <div> and <span>. These are no simple “two by fours,” these are full blown steel beams. With <div> and

<span>, you’re going to build some serious supporting structures, and once you’ve got those structures in place, you’re going to be able to style them all in new and powerful ways. Now, we couldn’t help but notice that your CSS toolbelt is really starting to fill up, so it’s time to show you a few shortcuts that will make specifying all these properties a lot easier. And, we’ve also got some special guests in this chapter, the pseudo-classes, which are going to allow you to create some very interesting selectors. (If you’re thinking that “pseudo-classes” would make a great name for your next band, too late, we beat you to it.)

this is a new chapter

429

a new lounge assignment

You know, we’d love it if
you could make the elixir specials
a little more attractive on the

Web page. Could you make it look
just like our handout menu?

The elixir
mixer, Alice

Weekly Elixir

Specials

Lemon Breeze

The ultimate healthy drink,
this elixir combines herbal
botanicals, minerals, and
vitamins with a twist of
lemon into a smooth citrus
wonder that will keep your
immune system going all
day and all night.

Chai Chiller

Not your traditional chai,
this elixir mixes mat

Here’s the handout menu with the elixir
é with
chai spices and adds
an extra chocolate kick
specials. Wow, the design is a lot different
for a caffeinated taste
sensation on ice.

than the rest of the page: it’s thin, the
text is centered, there are red headings, an
aquamarine border around the whole thing,
and even some cocktail graphics at the top.

Black Brain Brew

Want to boost your
memory? Try our Black

Brain Brew elixir, made
with black oolong tea and
just a touch of espresso.

Your brain will thank you
for the boost.

Join us any evening for these and all
our wonderful elixirs.

430

Chapter 11
divs and spans

A close look at the elixirs XHTML

Alice sure has asked for a tall order, hasn’t she? She wants us to take the existing lounge XHTML and make it look like the handout menu. Hmmm... that looks challenging, but we do have CSS on our side, so let’s give it a try. But, before we jump right into styling, let’s get an overview of the existing XHTML. Here’s just the XHTML snippet for the elixir specials; you’ll find it in “lounge.html” in the “chapter11/lounge” folder:

The elixir specials section begins

We have

<h2> Weekly Elixir Specials</h2>
with an <h2> heading.

three
elixirs,

<p>

Each elixir has
each with

<img src=“images/yellow.gif” alt=“Lemon Breeze Elixir” /> an image in a
the same </p>

<p> element.

structure. <h3> Lemon Breeze</h3>

...a name, in an

<p>

<h3> heading...

The ultimate healthy drink, this elixir combines

herbal botanicals, minerals, and vitamins with

...and a

a twist of lemon into a smooth citrus wonder
descr

that will keep your immune system going all
iption,

day and all night.

also in a

</p>
paragraph.

<p>

<img src=“images/chai.gif” alt=“Chai Chiller Elixir” />

</p>

And this

<h3> Chai Chiller</h3>
structure is

<p>
repeated for

Not your traditional chai, this elixir mixes mat&eacute; each elixir.

with chai spices and adds an extra chocolate kick for

a caffeinated taste sensation on ice.

</p>

<p>

<img src=“images/black.gif” alt=“Black Brain Brew Elixir” />

</p>

<h3> Black Brain Brew</h3>

<p>

Want to boost your memory? Try our Black Brain Brew

elixir, made with black oolong tea and just a touch

of espresso. Your brain will thank you for the boost.

</p>

And, finally, at the

<p>
bottom, there is

Join us any evening for these and all our
another paragraph, with

other wonderful

<a href=“beverages/elixir.html”

some text and a link to

title=“Head First Lounge Elixirs”>
the real elixirs page.

elixirs</a> .

</p>
you are here �

431

a new element called div

This looks tough, guys. There
are a lot of style changes we’ve
got to make, and the elixirs style
doesn’t real y match the rest of
the page.

Jim: Come on, Frank, you know we can just create a class or two and then style all the elixir elements separately from the rest of the page.

Frank: That’s true. Maybe this isn’t so bad. I’m sure there is a simple property to make text align to the center And we know how to handle the colored text.

Jim: Wait a sec, what about that border around everything?

Frank: Piece of cake. We just learned how to make borders. Remember, every element can have one.

Joe: Hmm, I don’t think so. If you look at the XHTML, this is a bunch of <h2> , <h3> , and <p> elements. If we put separate borders on every element, they’ll just look like separate boxes.

Frank: You’re right, Joe. What we need is an element to nest all these other elements inside, so we can put a border on that. Then we’ll have one border around everything in the elixirs section of the page.

Joe

Jim: Well, I see why you get paid the big bucks, Frank. Could we nest the Jim

Frank
elixir stuff inside a <p> element, or a <blockquote> ?

Frank: We can’t use <p> because <p> can’t contain other block elements, and the headings and paragraphs are obviously block elements. I don’t think we’d want to do that anyway; paragraphs are for text.

Joe: And <blockquote> ’s not right either, because this is an elixir menu, not a quote.

Frank: Actually, I think we’re on the right track. I’ve been reading a certain book on HTML & CSS and I’m just up to a section on a new element called

<div> . I think it might be the tool we need.

Joe: <div> – what’s that? It sounds like it’s for math.

Frank: That’s not far off, because a <div> lets you divide your page into logical sections or groupings.

Jim: Hey, that sounds like exactly what we need!

Frank: Yup. Let me show you guys how to divide a page into logical sections, and then I’ll show you what I know about <div> ...

432

Chapter 11

divs and spans

Let’s explore how we can divide

We’ve drawn an outline
of the PetStorz page.

a page into logical sections

Take a look at the Web page to the right: it’s a Web
page for PetStorz.com and we’re going to spend a few
h1
pages looking at how we might add some additional
h2
structure to it by identifying some logical sections and
then enclosing those inside a <div> element.

p

This is a pretty normal
h2
looking page: lots of
headings, paragraphs,
p
and an image in there.

p

But by just focussing on the structure of the page,
you can’t really tell a whole lot about the page.

p
img

What elements make up the header? Is there a
footer on the page? What are the content areas?

Identifying your logical sections

Okay, so our job is to locate “logical sections”

h1
in this page. What’s a logical section? It’s just
a group of elements that are all related on the
page. For instance, in the PetStorz.com Web
h2
page, there are some elements that are used for

Cats
the cats area on the page, and some that are
p
used for dogs. Let’s check it out.

The PetStorz page has two main content
h2
areas, one for cats, and one for dogs. It

Dogs
has some other areas too, but we’ll come
p
back to those.

In this case, both the cats and dogs sections
p
consist of two elements, a heading and a
paragraph. But often these groupings can
p
contain many more elements.

img
you are here �

433
how to mark logical sections with divs

Using <div>s to mark sections

Let’s nest the elements in each
grouping in a <div> element.

h1

Now that you know which elements belong
in each section, you can add some XHTML
div
to mark up this structure. The common
h2
way to do this is to place <div> opening

Here’s our cat group.

and closing tags around the elements that
p
belong to a logical section. Let’s first do this
pictorially, and then we’ll come back to the
real markup in a couple of pages.

div
h2

And here’s our
dog group.

p
p
p
img

Labelling the <div>s

Just by nesting your elements in
h1

<div> s, you’ve indicated that all those
div id=“cats”

elements belong to the same group.

Here we’ve added an id

But you haven’t given them any kind
of “cats” to the first
h2
of label that says what the grouping

<div> to indicate what
means, right?

the logical section is for.

p

A good way to do that is to use an id
attribute to provide a unique label for
div id=“dogs”

the <div> . For instance, let’s give the

And likewise for dogs.

cats <div> an id of “cats” and the
h2
dogs <div> an id of “dogs”.

p
p
p
img

434

Chapter 11

divs and spans
brain
power

?

Page One

Page Two

On a referral from the Starbuzz
h1

CEO, you’ve been asked to
h1
come in and consult on style
div id=“cats”

h2
changes to PetStorz main
h2
page. How quickly would you
p
p
understand the PetStorz Web
page if you were shown Page
h2
div id=“dogs”

One?

h2
p

What about Page Two?

p
p
p
p
img
p
img

Adding some style

Now the <div>s
h1
have a little style.

Okay, so you’ve added some logical
div id=“cats”

structure to the PetStorz page, and you’ve

By setting the
also labeled that structure by giving each
h2
background on the

<div> a unique id. That’s all you need

<div>, it also shows
to start styling the group of elements
p
through the elements
contained in the <div> .

contained in the <div>.

The elements in the <div> will a
div id=“dogs”

lso

Here we have two rules, one
inherit some properties from the
h2
for each <div>. Each <div> is

<div>, just as any child element
selected by an id selector.

does (like font-size, color, etc).

p

Each rule sets the

#cats {
p
background-image
background-image: url(leopard.jpg);

}

property. For cats we
p
have a leopard image,
img

#dogs {
and for dogs we have
background-image: url(mutt.jpg);
a mutt image.

}

you are here �

435
nesting divs

Exposing even more structure

There are a couple of reasons you might
div id=“header”

want to add more structure to your

Now we’ve added
h1
pages with <div> s. First, you may
another <div> with an
want to further expose the underlying
div id=“cats”

id indicating this is the
logical structure of your pages, which
h2
header of the page.

can help others understand them, and
p
also help in maintaining them. Second,
there are times when you need the
structure so that you have a way to apply
div id=“dogs”

style to a section. Often, you’ll want to
h2
add the structure for both reasons.

So, in the case of PetStorz, we could

And another indicating
p
take this to the next level and add a few
the footer of the page.

more <div> s...

p
div id=“footer”

p

Adding this structure through <div>s
img
can even help you think through your
page design. For instance, does this
lone <p> really need to be here?

div id=“header”

Adding structure on structure
h1

And you don’t have to stop there. It is
div id=“pets”

common to nest structure, too. For instance,
div id=“cats”

in the PetStorz page, we have a cat section
h2
and a dog section, and the two together are
logically the “pets” section of the page. So,
p
we could place both the “cat” and “dog”

<div> s into a “pets” <div> .

div id=“dogs”

h2
p

Now we’ve marked up this XHTML so that
we know there is a logical section in the page
p
with “pets” content in it. Further, that “pets”

section has two logical subsections, one for
div id=“footer”

“cats” and one for “dogs”.

p
img

436

Chapter 11
divs and spans
there are no

Dumb Questions

Q:

So, a <div> acts like a container
if it is helpful to add a “pets” section

Q: I was having a little trouble
that you can put elements into to keep
that contains both “cats” and “dogs” to
fol owing the <div> within <div> stuff,
them all together?

the PetStorz page, by al means add it.

However, if it provides no real benefit, then
with the “pets” and “cats” and “dogs”.

Could you explain that a little more?

A:

it just complicates your page. After working

It sure does. In fact, we often
with <div>s for a while, you’l start to get a
describe <div>s as “containers”. Not only
feel for when and how much to use them.

A: Sure. You’re used to elements being
do they act as logical containers that you
nested in other elements, right? Like a <p>
can use to hold a bunch of related elements

Q: Do you ever put <div>s in a class nested in a <body> nested in an <html> (like the “cat” elements) together, but when
instead of giving it an id?

element. You’ve even seen lists nested
we start styling <div>s and using them for
within lists. The <div> is real y no dif erent;
positioning in the next chapter, you’l see
you’re just nesting an element inside another
they act as graphical containers, too.

A: Wel, remember that an element can element, and, in the case of PetStorz, we’re Q:

have an id and be in one or more classes at
using it to show larger chunks of structure

(a “cats” and “dogs” nested in a “pets”

Beyond the structure I’m already
the same time, so the choice isn’t mutual y
section). Or, you might use <div>s to have a
putting into my pages with headings and
exclusive. And, yes, there are many times
beer section nested in a beverages section
paragraphs and so on, should I also be
you create <div>s and place them into
nested in a menu section.

adding a higher level of structure with
classes. Say you have a bunch of album

<div>s?

sections in a page of music playlists; you

But, the best way to understand why you’d
might put al the elements that make up the
want something like a <div> within a <div> is

A:

album into a <div> and then put them al in a by using them and encountering a situation Yes and no. You want to add
class cal ed “albums”. That identifies where
where they mean something to you. Put this
structure where it has a real purpose, but
the albums are, and they can al be styled
in the back of your mind and you’l see an
don’t add structure for structure’s sake.

together with the class. At the same time
example soon enough where we need one.

Always keep your structure as simple as
you might give each album an id so that it
possible to get the job done. For instance,
can have additional style applied separately.

Use, don’t abuse, <div>s in your pages. Add additional structure where it helps you separate a page into logical
sections for clarity and styling. Adding <div>s just for the sake of creating a lot of structure in your pages
complicates them with no real benefit.

you are here �

437
adding divs to the lounge

Meanwhile, back at the lounge...

Okay, enough “theory” about <div> s – let’s get one into the lounge page. Remember, we’re trying to get all the elixir elements into a group and then we’re going to style it to make it look like the elixir handout.

So, open up your “lounge.html” file in the “chapter11/lounge” folder, locate the elixirs elements, and then insert opening and closing <div> tags around them.

Here’s the opening tag,

<div id=“elixirs”>
and we’ve given it an id of

Remember we’re just
showing a snippet of

<h2> Weekly Elixir Specials</h2>

“elixirs” to identify it.

XHTML from the

<p>
entire file. When you

<img src=“images/yellow.gif” alt=“Lemon Breeze Elixir” /> open “lounge.html”, you’ll

</p>
see all the markup for

<h3> Lemon Breeze</h3>
the page.

<p>

The ultimate healthy drink, this elixir combines
herbal botanicals, minerals, and vitamins with
a twist of lemon into a smooth citrus wonder
that will keep your immune system going all
day and all night.

</p>

<p>

<img src=“images/chai.gif” alt=“Chai Chiller Elixir” />

</p>

<h3> Chai Chiller</h3>

<p>

Not your traditional chai, this elixir mixes mat&eacute; with chai spices and adds an extra chocolate kick for
a caffeinated taste sensation on ice.

</p>

<p>

<img src=“images/black.gif” alt=“Black Brain Brew Elixir” />

</p>

<h3> Black Brain Brew</h3>

<p>

Want to boost your memory? Try our Black Brain Brew
elixir, made with black oolong tea and just a touch
of espresso. Your brain will thank you for the boost.

</p>

<p>

Join us any evening for these and all our
other wonderful

<a href=“beverages/elixir.html”

title=“Head First Lounge Elixirs”> elixirs</a> .

</p>

And, her

</div>
e’s the closing tag.

438

Chapter 11

divs and spans

Taking the <div> for a test drive

That was easy, wasn’t it? Now that we’ve got a more
structured page, let’s fire up the browser and see
how it looks...

Hmmm... no change at all!

But that’s okay: the <div>
is pure structure, and it
doesn’t have any “look” or
default style in the page.

That said, a <div> is just a block
element, and you can apply any styles
you want to it. So, once you know how
to style a block element (and you do),
you know how to style a <div>.

brain

Weekly Elixir

Specials
power

?

Lemon Breeze

Remember, the goal here is to restyle the elixir content on the page The ultimate healthy drink,
this elixir combines herbal
so it looks like the handout.

botanicals, minerals, and
vitamins with a twist of
lemon into a smooth citrus
wonder that will keep your
immune system going all

Before we took a detour to learn about <div>s, we were trying to day and all night.

figure out how to get a border around the entire set of elixirs. Now that you’ve got a <div> in “lounge.html”, how would you go about adding a border?

Chai Chiller

Not your traditional chai,
this elixir mixes mat
é with
chai spices and adds
an extra chocolate kick
for a caffeinated taste
sensation on ice.

Black Brain Brew

Want to boost your
memory? Try our Black

Brain Brew elixir, made
with black oolong tea and
just a touch of espresso.

Your brain will thank you
for the boost.

Join us any evening for these and all
our wonderful elixirs.

you are here �

439

adding style to a div

Adding a border

Okay, now that you have a <div> around all the elements in the elixirs section, the fun begins: you can style it.

The first thing we want to reproduce in the elixirs handout is a border that wraps around all the elements in the elixirs section, right? Well, now that you actually have a <div> element that wraps around the elixirs section, you can style it and add a border. Let’s try that now.

You’ll need a new rule in the lounge’s CSS to select the <div> element using its id. Open up your “lounge.css” file in the “chapter11/lounge”

folder, and add this rule at the end:

#elixirs {

Add this at the end of your CSS file. It
border-width: thin;
selects the elixirs <div> element using its id,
border-style: solid;
and adds a thin, solid border in our favorite
border-color: #007e7e;
aquamarine color.

}

An over-the-border test drive

After you’ve added the CSS, save it and then reload
your “lounge.html” file. Here’s the border that you just added to the elixirs <div> element.

You added a visible border
to this <div>, but it still has
no padding and no margin.

We’ll need to add that too.

Notice that the border goes
around all the elements inside
the <div> element. The <div>
is a box like every other
element, so, when you add
a border, the border goes
around the content, which is
all the elements in the <div>.

440

Chapter 11

divs and spans

Adding some real style to
the elixirs section

The width of the elixirs
handout is narrower than the

So far, so good. We’ve found a way to get

There’s a background
rest of the page.

that border around the entire section. Now
image at the top.

you’re going to see how to use the <div> to
customize the styling of the entire elixirs section

The main heading
independent of the rest of the page.

and the paragraph

We obviously have some padding issues to deal
text are black, while
with, because the border is right up against the
the drink names are
content. But there’s a lot of other style we need
a red color that
to work out, too. Let’s take a look at everything
matches the red in
we need to take care of...

the logo.

The text and images
are centered, and
there’s padding on
the sides to add
space between the
text and the border.

The line-height of the
paragraphs looks a lot more
like the default line height for
the page (before we changed it
in the last chapter).

The font family is a sans-serif font, just
like the body font, so we don’t have to
change that. Remember that the <div>
element and all the elements nested in it
inherit the font family from the body.

This link is aquamarine.

you are here �

441
plan of attack

The game plan

That’s a lot of new style, so let’s get a game plan together before attacking it. Here’s what we need to do:

❏ First, we’re going to change the width of the elixirs <div> to make it narrower.

❏ Next, we’ll knock out some of the styles you’re already familiar with, like padding and the background image. We’ll also play with the text alignment, which you haven’t seen before.

❏ Then all we’ve got left are the text line heights and the heading colors. You’re going to see that you need to upgrade your CSS
selector skills just a bit to get those changed.

That’s a lot to do, so let’s get started.

Working on the elixir width

We’d like the elixirs to be quite narrow, so it looks like the narrow handout menu at the lounge; about 1/4 the width of a typical browser window should be about right. So, if most people set their browser windows to 800 pixels wide, that would be about 200
pixels. You’ve set the widths of padding, borders, and margins, but you’ve never set the width of an element before. To do that you use the width property, like this:

#elixirs {
border-width: thin;
border-style: solid;
border-color: #007e7e;
width: 200px;

}

The width property lets you specify the width of
the element’s content area. Here we’re specifying
that the content width be 200 pixels.

We’re setting this on the elixirs <div>. So the content in the elixirs <div> will be 200 pixels wide, and the browser’s layout rules will work to fit all the elements
nested in the <div> within that width.

Give this a try. Open your “lounge.css” and add this rule to the bottom.

442

Chapter 11

divs and spans

Test driving the width

Next, save the CSS and then reload the “lounge.html” file. You’ll see the elixirs section get much skinnier, thanks to the width you gave it. The width of the content in the <div> is now exactly 200 pixels. There’s also some interesting behavior you should check out...

Now all the content in the elixirs

<div> fits into a space that is 200
pixels wide. It doesn’t change, even if

Notice that the
you make your browser window really
height of the elixirs
wide, or really narrow. Try it!

section got a lot
taller. That’s because
we made it narrower,
so the content

200 pixels
takes up more room
vertically instead.

Compare the behavior of the <div>
to that of the other elements
when you make your browser
window wide. The paragraphs
automatically expand to fill the
width of the browser. We’ll talk
about that more in a sec...

brain
power

?

Can you resize your browser window to less than the width of the elixirs <div>? Some browsers won’t let you go that narrow; others will. If you can go narrower, compare the text in the elixirs

<div> with the rest of the text on the page. The other paragraphs resize themselves no matter how wide or narrow you go, but the elixirs <div> never gets narrower or wider than 200 pixels.

you are here �

443

more about box widths

I was wondering how the
width property relates to padding
and margins. Is this the width of the
content itself? Or the entire box
including the padding and margin?

The width property specifies the
width for the content area only.

To figure out the width of the entire box, you
need to add the width of the content area to the
width of the left and right margins, the left and
right padding, and the border width. Don’t forget
that you have to include twice the border width,
because there is a border on the left and the right.

total width
width

(specified
in width
property)

left margin width border width left padding width
right padding width
right margin width
border width

Our guarantee: at the lounge, we’re
committed to providing you, our guest,
with an exceptional experience every
time you visit. Whether you’re just
stopping by to check in on email over
an elixir, or are here for an out-of-
the-ordinary dinner, you’ll find our
knowledgeable service staff pay attention
to every detail. If you’re not fully satisfied
have a Blueberry Bliss Elixir on us.

444

Chapter 11

divs and spans

Wel then how do we
specify the width of the
entire element?

You don’t. You specify the width of the content area,
the padding, the border, and the margin. All of that
added together is the width of the entire element.

Say you set the content area width to be 300 pixels using the width property in a CSS rule.

And let’s say you’ve set the margins to 20 pixels, the padding to 10 pixels, and you have a 1 pixel border. What’s the width of your element’s box? Well, it’s the width of the content area added to the width of the left and right margins, the left and right padding, and the left and right border width. Let’ see how to calculate that...

(1) The content area is 300 pixels.

300 pixels

Our guarantee: at the lounge, we’re
committed to providing you, our guest,
with an exceptional experience every
time you visit. Whether you’re just
stopping by to check in on email over
an elixir, or are here for an out-of-
the-ordinary dinner, you’ll find our
knowledgeable service staff pay attention

(2) Figure out how much is taken up by
to every detail. If you’re not fully satisfied
have a Blueberry Bliss Elixir on us.

the margins, padding, and border.

ixels

300
ixels
ixels
ixel ixels
ixel

20 p 1 p 10 p

10 p 1 p 20 p

20 + 1 + 10

10 + 1 + 20

(3) It looks like 62 pixels are taken up, so
add that to the content area’s width of

31

31

300 pixels, and we have 300 + 62 = 362
pixels for the entire box.

31 + 31 = 62
you are here �

445

box width and height fine points
there are no

Dumb Questions

Q:

(which could be the <body>, a <div>, etc.).

Q:

If I don’t set the width of an

Q: What if I don’t have any margin,

What about the height?

element, then where does the width come padding, or borders?

from?

A: In general, the height of an element

A:

A: Then your content gets to use the is left at the default, which is auto, and the The default width for a block element entire width of the box. If the width of the browser expands the content area vertical y
is “auto”, which means that it wil expand to
content area is 300 pixels, and you have no
so al of the content is visible. Take a look
fil whatever space is available. If you think
padding, border, or margin, then the width of
at the elixirs section after we set the width
about any of the Web pages we’ve been
the entire box would also be 300 pixels.

to 200 pixels and you’ll see the <div> got a
building, each block element can expand to
lot taller.

the entire width of the browser, and that’s

Q:

You can explicitly set a height, but you
exactly what it does. Now, hold this thought,

What are the different ways I can
risk cut ing of the bot om of your content
because we’re going to go into this in detail
specify widths?

if your height isn’t big enough to contain
in the next chapter. Just remember that
it. In general, leave your element heights

“auto” al ows the content to fil whatever
unspecified so they default to auto. We’re
space is available (after taking padding,

A: You can specify an actual size
going to talk about this more in the next
border, and margin into account).

– usual y in pixels – or you can specify a
percentage. If you use a percentage, then
chapter as well.

the width is calculated as a percentage
of the width of container the element is in

Sharpen your pencil

Here’s a box that has all the widths labelled. What is the width of the entire box?

Your answer here

Our guarantee: at the lounge, we’re
committed to providing you, our guest,
with an exceptional experience every
time you visit. Whether you’re just
stopping by to check in on email over
an elixir, or are here for an out-of-
the-ordinary dinner, you’ll find our
knowledgeable service staff pay attention
to every detail. If you’re not fully satisfied
have a Blueberry Bliss Elixir on us.

ixels

200 pixels
ixels
ixels
ixels ixels
ixels

30 p 2 p 5 p

10 p 2 p 20 p

446

Chapter 11
divs and spans

Adding the basic styles to the elixirs

We’ve got the width out of the way. What’s left to do?

❏ First, we’re going to change the width of the elixirs <div> to make it narrower.

❏ Next, we’ll knock out some of the styles you’re already familiar We’re doing this step next.

with, like padding, text alignment, and the background image.

❏ Then all we’ve got left are the text line heights and the heading colors. You’re going to see that you need to upgrade your CSS
selector skills just a bit to get those changed.

Now we’re going to concentrate on some of the basic styles, like the padding, the text alignment, and also getting that background image of the cocktail glasses in the elixirs <div> . You’re already familiar with how most of this works, so let’s take a quick look at the CSS: Remember we’re going to apply all this style to the
elixirs <div> so that it only affects the <div> and The default padding on a <div> is 0 pixels, so
the elements it contains, not the entire page.

we’re going to add some padding to provide a bit
of space for the content. Notice that we’re not
adding any padding at the top because there’s
already plenty of room there thanks to the

#elixirs {
default margin on the <h2> heading (look back at
border-width: thin;
the last test drive and you’ll see there’s plenty of
border-style: solid;
room above the <h2>). But we do need it on the
border-color: #007e7e;
width: 200px;
right, bottom, and left.

padding-right: 20px;

We’re adding some margin on the left to indent
padding-bottom: 20px;
padding-left: 20px;
the elixirs from the rest of the page a bit.

This is going to come in handy later...

margin-left: 20px;

Use text-align on block elements to
text-align: center;
align the text they contain. Here we’re
going to center-align the text.

background-image: url(images/cocktail.gif);
background-repeat: repeat-x;

}

And finally we’re specifying an image to use in the background, in this case the cocktail image. We’re setting the background-repeat property to repeat-x, which will tile the image only in the horizontal direction.

you are here �

447

how text-align works

Test driving the new styles

Now it’s time to add those new properties to your

“lounge.css” file and reload the page. Let’s check out

The tiled image looks
the changes: the headings, the images, and the text
nice, and it only tiles
are all centered in the
horizontally.

<div> and have a little more
breathing room now that there’s some padding in
place. We’ve also got a little decoration at the top

We’ve got some
with the tiled cocktail image.

padding here, and
at the bottom
and left...

... and
everything’s
centered nicely.

Wait just a sec... why
does the text-align
property affect the alignment
of the images? Shouldn’t it align
only text? Seems like it should be
called something else if it aligns
images too.

Good point... it doesn’t seem right, does it? But the truth is that text-align will align all inline content in a block element.

So in this case, we’re setting the property on the <div> block element and all its inline content is nicely centered as a result. Just remember that text-align, despite its name, works on any kind of inline element. One other
thing to keep in mind: the text-align property should be set on block elements only. It has no effect if it’s used directly on inline elements (like <img> ).

448

Chapter 11

divs and spans

That’s interesting because

I noticed the text inside the

<div> is al inside other block elements,
like <h2>, <h3>, and <p>. So, if text-
align is aligning inline elements in the

<div> block element, how is the text
in these nested block elements
getting aligned?

Good catch. All the text inside the <div>
element is in nested block elements, but it is
all aligned now. That’s because these block
elements inherit the text-align property
from the <div> . So here’s the difference:

rather than the <div> itself aligning the
text in the headings and the paragraphs

(which it won’t do because these are block
elements), the headings and paragraphs
are inheriting the text-align value of

“center”, and then aligning their own content
to center.

So what? Well, if you think about it, this
gives you a lot of leverage when you use a

<div> , because you can wrap a section of
content in a <div> and then apply styles
to the <div> rather than each individual
element. Of course, keep in mind that not
all properties are inherited by default, so
this won’t work for all properties.

you are here �

449

calculating box widths

Sharpen your pencil

So now that you understand widths, what’s the total width of the elixirs box? To start with, we know the content area is 200 pixels.

We’ve also set some left and right padding that affects the width, as well as a border that’s set to “thin”. Just assume a thin border is 1 pixel thick, like it is on most browsers. And what about margins? We set a left margin value, but no right margin value, so the right margin is 0 pixels by default.

?

Here are all the properties that relate to width. Your job is to figure out the total width of the elixirs <div>.

Weekly Elixir
border-width: thin;

Specials
width: 200px;
padding-right: 20px;
padding-bottom: 20px;

Lemon Breeze
padding-left: 20px;

The ultimate healthy drink,
this elixir combines herbal
botanicals, minerals, and
margin-left: 20px;
vitamins with a twist of
lemon into a smooth citrus
wonder that will keep your
immune system going all
day and all night.

Chai Chiller

Not your traditional chai,
this elixir mixes mat
é with
chai spices and adds
an extra chocolate kick
for a caffeinated taste
sensation on ice.

Black Brain Brew

Want to boost your
memory? Try our Black

Brain Brew elixir, made
with black oolong tea and
just a touch of espresso.

Your brain will thank you
for the boost.

Join us any evening for these and all
our wonderful elixirs.

450

Chapter 11

divs and spans

We’re almost there...

We’re close to having the elixirs done. What’s left?

❏ First, we’re going to change the width of the elixirs <div> to make it narrower.

❏ Next, we’ll knock out some of the styles you’re already familiar with, like padding, text alignment, and the background image.

❏ Then all we’ve got left are the text line heights and the heading We’re on the last step.

colors. You’re going to see that you need to upgrade your CSS
selector skills just a bit to get those changed.

Sounds pretty easy, right? After all, you’ve done
all this before. In fact, given that you know
you can just set styles on the <div> and
they will be inherited, you can take care of

We’ve almost got this done,
this real fast.

we just need to change the
header colors and also the
line height.

Frank: Yeah, this is interesting.

The main elixirs heading, which is
an <h2> , has the aquamarine color
because there is already an <h2> rule in
the CSS. But we need for that to be black. Then
we’ve got the <h3> s in the elixirs, which need to be red.

Jim: Yeah, no problem, we’ll just add a few more rules.

Frank: But wait a sec... if we change the <h2> rule, or add an <h3> rule, then we’re going to change the heading colors on the entire page. We just want these colors in the elixirs section.

Jim: Oh, good point. Hmmm... Well, we could use two classes.

Frank: That would work, although it’s a bit messy. Anytime you add a new heading to the elixirs <div> you’ll have to remember to add it to the class.

Jim: Yeah, well, c’est la vie.

Frank: Actually Jim, before you use classes, go check out descendant selectors. I think they’ll work better here.

Frank

Jim: Descendant selectors?

Jim

Frank: Right, they’re just a way of specifying a selector like “select an

<h2> element, but only if it’s inside an elixirs <div> ”.

Joe: I’m not following.

Frank: Okay, let’s step through this...

you are here �

451

selecting only certain headings

What are we trying to do?

Let’s take a quick look at what we’re trying to do
to the heading colors.

What we have now
html

Here’s just the main
heading elements in the
body
lounge XHTML.

h1
h2
div id=”elixirs”

h2
h3
h3
h3

Right now the CSS says to color <h1>
and <h2> element text aquamarine. So
all <h1> and <h2> elements are that
color, even in the elixirs <div>.

h1, h2 {

color: #007e7e;

}

And here’s the rule specifying the <h1>
and <h2> color in the “lounge.css” file.

What we want
html

We want the <h1> and <h2> in
the main page to stay aquamarine.

body
h1
h2
div id=”elixirs”

h2
h3
h3
h3

And we want to change the <h2>
and <h3> elements in the elixirs
section to be black and red.

h1, h2 {

color: #007e7e;

But if we change the existing rule for <h2>, we’ll affect

}

the font color of every <h2> in the main page. And, if we add a new rule for <h3>, then any <h3>s that get added to the main page later will be red, which is not what we
want. Now, we could use a class like Jim suggested, but

?

we’re going to give Frank’s idea a try first...

452

Chapter 11

divs and spans

What we need is a way to select descendants

What we’re really missing is a way to tell CSS that we want to only select elements that descend from certain elements, which is kinda like specifying that you only want your inheritance to go to the children of one daughter or son. Here’s how you write a descendant selector.

Leave a space between
the parent name and
html
the descendant name.

body

Here’s the

And her
parent element.

e’s its
h1
h2
div id=”elixirs”

descendant.

h2
h3
h3
h3
div h2 {

Write the rest of
color: black;
your rule just like

}

you always do.

Here’s what this rule
selects in the lounge.

This rule says to select
any <h2> that is a
descendant of a <div>.

Now the only problem with this rule is that if someone created another <div> in the “lounge.html” file, they’d get black <h2> text, even if they didn’t want it.

But we’ve got an id on the elixirs <div> , so let’s use it to be more specific about which descendants we want:

html

Now the parent
element is the
body
element with

And here’s its
the id elixirs.

descendant.

h1
h2
div id=”elixirs”

h2
h3
h3
h3

#elixirs h2 {
color: black;

}

This rule selects the same element. But it’s more
specific, so if we added another <div> with an

This rule says to select any <h2> that is a

<h2> to the page, that’s okay because this rule
descendant of an element with the id “elixirs”.

selects only <h2>s in the elixirs <div>.

you are here �

453

more on selecting children

Sharpen your pencil

Your turn. Write the selector that selects only <h3> elements inside the elixirs <div>.

In your rule, set the color property to #d12c47. Also label the elements in the graph below that are selected.

html
body
h1
h2
div id=”elixirs”

div id=”calendar”

h2
h2
h3
h3
h3
h1
h2
h3
there are no

Dumb Questions

Q: Descendant usualy means child, Q: Well, is there a way to select a A: It works the same way. Just use grandchild, great-grandchild. Here, we’re
direct child?

more descendants, like this:

just selecting the child descendants,
right?

A:

#elixirs blockquote h2 {

Yes. For example, you could use
color: blue;

A:

“#elixirs > h2”, to select <h2> only if it is

}

That’s a really good point.

the direct child of an element with an id of

The selector “#elixirs h2” means ANY

“elixirs”.

This selects any <h2> elements that
descendant of elixirs, so the <h2> could be
descend from <blockquote>s that descend
a direct child of the <div> or nested down

Q:

from an element with an id of “elixirs”.

inside a <blockquote> or another nested

What if I need something more

<div> (making it a grandchild) and so on.

complex, like an <h2> that is the child of

So a descendant selector selects any <h2>
a <blockquote> that is in elixirs?

nested inside an element, no mat er how
deeply it is nested.

454

Chapter 11

divs and spans

Changing the color of the elixir headings

Now that you know about descendant selectors, let’s set the <h2> heading to black and the <h3> headings to red in the elixirs. Here’s how you do that:

#elixirs h2 {
color: black;

}

Here we’re using the descendant
selectors to target just the <h2>

#elixirs h3 {
and <h3> elements in the elixirs <div>.

color: #d12c47;

We’re setting <h2> to black, and <h3>

}

to a red color, using a hex code.

A quick test drive...

Go ahead and add these new properties to the bottom of your

“lounge.css” file, save, and reload “lounge.html”.

We’ve got black and red headings
in the elixirs section, and we
haven’t affected the aquamarine
color being used for <h2>
headings in the main page.

Now all we need to do is
fix the line height.

you are here �

455

another way to specify line height

Fixing the line height

Recall that in the last chapter we made the line height of the text in the lounge a little taller than normal. This looks great, but in the elixirs we want our text to be a normal, single-spaced, line height to match the handout. Sounds easy enough, right? Just set the line-height property on the <div> and everything will be fine, because line-height is inherited. The only problem is that the headings will also inherit the line-height, and we’ll end up with something like this.

If you set the line-height property on
the entire <div> then it will be inherited

#elixirs {
by all elements in the <div>, including the
line-height: 1em; headings. Notice that the line height in

}

the heading is too small and the two lines
are starting to run together.

Here are the f

The reason that the line-height for the elixirs heading is
ont sizes
of the elements. W
body size is “small”

too small is because every element in the elixirs
e set

<div>
body to “sma
inherits the line-height of 1em, or “1 times the font size of ll”, so that’s
inherited by elixir
the elixirs element”, which in this case is “small”, or about s.

div id=”elixirs”

12 pixels (depending on your browser). Remember, the
size is “small”

elixirs <div> is inheriting its font-size from the <body> The line-height of
element, which we set to “small.”

<h2> is set to 1 times
h2 is 120% of “small”

the font size of

What we really want is for all the elements in the elixirs
elixirs, which is “small”,

<div> to have a line-height that’s based not on the or about 12 pixels.

font-size of the elixirs <div> , but rather the font-size of each element itself. We want the <h2> heading to have body line-height is
a line-height that is 1 times its font-size (which is 120% of 1.6 times “small”

“small”), and the <p> should also have a line-height of 1
times its font-size (which is “small”). How can you do this?

Well, line-height is a bit special because you can use just a div id=”elixirs”

number instead of a relative measure – like em or % – for line-height is 1 times

We want <h2> to
line-height. When you use just a number, you’re telling

“small”, or about 12 pixels
have a line-height
each element in the elixirs <div> to have a line-height that is 1 times
of 1 times its own font-size, rather than the font-size of its own font size,
the elixirs
h2 is 120% of “small”

<div> . Give it a try; set the line-height of the that is, 14 pixels
elixirs <div> to 1, and you’ll see that it fixes the heading.

line-height is 1 times

(120% of small).

120% of small, or
about 14 pixels

Add a line-height of 1

#elixirs {
to the elixirs <div> to

The font-size of the p element is “small” (p inherits
line-height: 1;
change the line-height
its font-size from the elixirs <div>) so it will have a

}

of each element in it.

line-height of 12 pixels, which is what we want.

456

Chapter 11

divs and spans

Look what you’ve accomplished...

Take a look at the elixirs section now. You’ve
completely transformed it, and now it looks
just like the handout. And, other than adding

Remember, this is how the
a
elixirs section looked when

<div> and an id attribute to your XHTML, you were able to do this with just a few CSS
we started...

rules and properties.

By now, you should be realizing just how
powerful CSS is, and how flexible your Web
pages are when you separate your structure

(XHTML) from your presentation (CSS). You
can give your XHTML a whole new look,
simply by changing the CSS.

... and here’s
what it looks
like now.

Wow, that’s fantastic!

You were able to make the
elixirs section on the Web site
look like the handout, with
just a little CSS.

you are here �

457

specifying properties with shorthand

It’s time to take a little shortcut

You’ve probably noticed that there are quite a few CSS properties that seem to go together. For instance, padding-left, padding-right, padding-bottom, and padding-top. Margin properties are the same way. How about background-image, background-color, and background-repeat?

Those all set different property values on the background of an element. Have you also noticed it gets a little tedious typing all those in? There are better things to spend your time on than typing all this, right?

padding-top: 0px;

That’s a lot of typing just t
padding-right: 20px;
o
specify four number
padding-bottom: 30px;
s.

padding-left: 10px;

Well, here’s a special bonus for this chapter. You’re going to learn how to specify all those values without risking carpal tunnel. Here’s how:

Here’s the old school way of

And here’s the new and improved
specifying your padding.

way to write them as a shorthand.

padding-top: 0px;
padding-right: 20px;
padding: 0px 20px 30px 10px;
padding-bottom: 30px;
padding-left: 10px;
top right bottom left

You can use the same sort of shorthand with margins:

margin-top: 0px;
margin-right: 20px;
margin: 0px 20px 30px 10px;
margin-bottom: 30px;
margin-left: 10px;
top right bottom left

Just like padding, you can use
a shorthand to specify all your
margin values with one property.

If your padding or margins are the same value on all sides, you can make the shorthand really short:

This says that the padding
padding-top: 20px;
should be 20 pixels on
padding-right: 20px;
padding: 20px;
every side of the box.

padding-bottom: 20px;
padding-left: 20px; If all your padding values are the same, then you can write it like this.

458

Chapter 11

divs and spans

But there’s more...

Here’s another common way to abbreviate margins (or padding): top and bottom
margin-top: 0px;
are the same.

margin-right: 20px;
margin: 0px 20px;
margin-bottom: 0px;
right and left
t
margin-left: 20px;
op and bott
right and left
are the same.

If the top and bottom, as well as the r
om
ight and left
margins are the same, then you can use a shorthand.

And what about the border properties we mentioned?

You can use a shorthand for those too.

border-width: thin;

Rewrite border
border-style: solid;
properties as one
border: thin solid #007e7e;

border-color: #007e7e;
property. These can be
in any order you like.

The border shorthand is even more flexible than margins or padding because you can specify them in any order you like.

These are all perfectly
valid border shorthands.

border: solid thin;
border: solid thin #007e7e;
border: #007e7e solid;
border: #007e7e solid thin;
border: solid;

...and don’t forget the shorthand for backgrounds

You can also use shorthand for backgrounds:

Like border, values can go in any order
in this shorthand. There are also a
background-color: white;
few other values you can specify in the
background-image: url(images/cocktail.gif);
background-repeat: repeat-x;
shorthand, like background-position.

background: white url(images/cocktail.gif) repeat-x;
you are here �

459

shortcuts for fonts

And even more shorthands

No description of shorthands would be complete without mentioning font shorthands.

Check out all the properties we need for fonts: font-family, font-style, font-weight, font-size, font-variant, and don’t forget line-height.

Well, there’s a shorthand that wraps all these into one. Here’s how it works: Finally you need to add

Here are the properties that go into the
your font families. You only
font shorthand. Ordering matters here
need to specify one font,
unless we say otherwise...

You must specify but alternatives are highly
font size.

encouraged.

font: font-style font-variant font-weight font-size/line-height font-family

These values are all optiona

T
l. Y
he line-height is
ou

Use commas
can specify any combination of
optional. If you want
between your
them, but they need to come
to specify one, just
font family
before font-size.

put a / right after
the font-size and
names.

add your line height.

So let’s give this a try. Here are the font properties for the lounge body:

font-size: small;

font-family: Verdana, Helvetica, Arial, sans-serif;

line-height: 1.6em;

Now let’s map those to the shorthand:

We’re not using any of these, but
that’s okay, they’re all optional.

font: font-style font-variant font-weight font-size/line-height font-family

And now let’s write the shorthand:

font: small/1.6em Verdana, Helvetica, Arial, sans-serif; And here’s the shorthand version. Wow, that’s quite a
shorthand, huh? You’re going to be able to double your time at the slopes (or on the beach) now.

460

Chapter 11

divs and spans
there are no

Dumb Questions

Q:

Make it Stick

Should I always use shorthand?

A:

To remember the

Not necessarily. Some people find the long form more
ordering of the padding
and mar
readable. Shorthands do have the advantage of reducing the size gin shorthand
values, think of a
of your CSS files, and certainly they are more quickly entered clock labelled with top,
because they require less typing. However, when there is a
right, bottom, and left.

Then, alw
problem, they are a lit le more difficult to “debug” if you have ays go in a
clockwise direction: top
incorrect values or the wrong order. So, you should use whichever to right to bottom to left.

form is more comfortable because they are both perfectly valid.

margin: 0px 20px 30px 10px;

Q:

top right bottom left

Shorthands are more complex because I have to
remember the ordering and what is and isn’t optional. How do I memorize it all?

A:

a “reference manual.” Just pick one up, and should you need Wel , you’l be surprised how quickly it becomes second
to quickly look up property names or the syntax of a property, nature, but those of us in the “biz” have a little secret we like to call just grab your handy reference manual and look it up. We’re particularly fond of the CSS Pocket Reference by Eric Meyer.

It’s tiny and makes a great reference.

Exercise

It’s time to put all your new knowledge to work. You’ll notice that at the bottom of the lounge, there’s a small section with copyright information that acts as a footer for the page. Add a <div> to make this into its own logical section. After you’ve done that style it with these properties: Let’s make the text really small.

font-size: 50%;

You know, FINE PRINT.

text-align: center;
line-height: normal;

And let’s center the text.

margin-top: 30px;

We’re also setting the line-height to be

“normal”, which is a keyword you haven’t seen
yet. “Normal” allows the browser to pick an

And let’s add some top margin to give the appropriate size for the line-height, which is footer a little breathing room.

typically based on the font.

And while you’re at it, have a look over the entire “lounge.css” file. Is there anywhere you might want to simplify things with shorthands? If so, go ahead and make those changes.

you are here �

461

another lounge assignment

I saw the nice job you
did on the elixirs. Can you
give us a hand with the music
recommendations on the site?

We don’t need much, just
some simple styling.

All the CD titles are And all the artists

The lounge’s
in an italic font style.

are in bold.

resident DJ.

brain
power

?

What do you think is the best way to style the CD and artists in the

“What’s playing at the Lounge” section?

462

Chapter 11

divs and spans

I was thinking we could just
wrap <em> and <strong> elements
around the CDs and artists. On
most browsers that’s going to give
us italic and bold.

Frank: Yeah, but that’s kind of like using a <blockquote> just to indent text. What I mean is that we don’t really want to emphasize and strongly emphasize the CD and artists. We just want italic and bold.

Plus, what if someone changes the style for <em> and <strong> ?

That would show up on the CDs and artists too.

Jim: Well, I actually thought about that, but I couldn’t think of any other way to do it. I mean this is just text in the same list item. It’s not like we have any way to style it.

Jim

Frank

Frank: What do you mean?

Jim: We can only style elements, and here we just have a bit of text, like, “Music for Airports, Brian Eno”. We’d need an element around each piece of text to be able to style them differently.

Frank: Oh, right, right. I see what you mean.

Jim: I suppose we could use something like

<div class=”cd”>Music for Airports</div>

<div class=”artist”>Brian Eno</div> .

But that’s a block element, so that is going to cause linebreaks.

Frank: Ahhh, I think you’re on to something, Jim. There’s another element like <div> that is for inline elements. It’s called a <span> .

That could work out perfectly.

Jim: I’m game. How does it work?

Frank: Well, a <span> gives you a way to create a grouping of inline characters and elements. Here, let’s just give it a try...

you are here �

463
how to use spans

Adding <span>s in three easy steps

<span> elements give you a way to logically separate inline content in the same way that <div> s allow you to create logical separation for block level content. To see how this works, we’re going to style the music recommendations by first adding

<span> elements around the CDs and artists, and then we’ll write two CSS rules to style the <span> s. Here’s exactly what you’re going to do: 1

You’re going to nest the CDs and artists in separate <span> elements.

2

You’re going to add one <span> to the “cd” class and the other to the “artist” class.

3

You’re going to create a rule to style the “cd” class with italic, and the “artist” class with bold.

Steps one and t wo: adding the <span>s

Open your “lounge.html” file and locate the “Who’s playing at the Lounge”

heading. Just below that you’ll see the unordered list of recommendations.

Here’s what it looks like:

Each list item consists of a CD title, a
comma, and then the music artist.

<ul>

<li> Buddha Bar, Claude Challe</li>

<li> When It Falls, Zero 7</li>

<li> Earth 7, L.T.J. Bukem</li>

<li> Le Roi Est Mort, Vive Le Roi!, Enigma</li>

<li> Music for Airports, Brian Eno</li>

</ul>

Let’s try adding <span> s to the first CD and artist: Do the same for the artist. Nest it

Next, add a closing tag
in a <span> element, only this time

Just add a <span> opening tag along with after the CD ti put the <span> in the “artis
tle.

t” class.

the class attribute and a value of “cd”.

<ul>

<li><span class=”cd”> Buddha Bar</span> , <span class=”artist”> Claude Challe</span></li>

<li> When It Falls, Zero 7</li>

<li> Earth 7, L.T.J. Bukem</li>

<li> Le Roi Est Mort, Vive Le Roi!, Enigma</li>

<li> Music for Airports, Brian Eno</li>

</ul>

464

Chapter 11

divs and spans

Step three: styling the <span>s

Before we move on, save the file and reload it in your browser. Like a <div> , by default a <span> has no effect on style, so you should see no changes.

Now let’s add some style. Add these two rules to the bottom of your “lounge.css” file: We’re going to add a rule for each of
the new classes, cd and artist.

For CDs we’ll make
the font style italic.

.cd {

font-style: italic;

}

And for artists we’ll

.artist {
set the font-w

font-weight: bold;
eight

}

to bold.

Test driving the spans

That’s it. Save and reload. Here’s what you’ll see:

Nice job, guys. This
next one’s for you.

Now the
first music
recommendation
has the correct
styling.

you are here �

465

more on span

Sharpen your pencil

You need to finish the job. Add <span> elements to the rest of the music recommendations and test your page. You’ll find the solution in the back of the chapter.

<ul>

<li><span class=”cd”> Buddha Bar</span> , <span class=”artist”> Claude Challe</span></li>

<li> When It Falls, Zero 7</li>

<li> Earth 7, L.T.J. Bukem</li>

<li> Le Roi Est Mort, Vive Le Roi!, Enigma</li>

<li> Music for Airports, Brian Eno</li>

</ul>
there are no

Dumb Questions

Q:

spacing of the other inline elements around

When do I use a <span> rather
it, so the padding will overlap other inline
than another inline element like <em> or

Q:

elements.

Can I set properties like width on

<strong>?

<span> elements? Actual y, what about

Images are a lit le dif erent from other
inline elements. The width, padding, and

A:

inline elements in general?

margin properties al behave more like they

As always, you want to mark up your
do for a block element. Remember from
content with the element that most closely

A: You can set the width of inline

Chapter 5: if you set the width of an image
matches the meaning of your content. So,
elements like <span>, <em> and <strong>,
using either the width at ribute in the <img>
if you are emphasizing words, use <em>;
but you won’t notice any ef ect until you
element or the width property in CSS, the
if you’re trying to make a big point, use
position them (which you’l learn how to do in browser scales the image to fit the width you

<strong>. But, if what you real y want is
the next chapter). You can also add margin
specify. This can sometimes be handy if
to change the style of certain words, say,
and padding to these elements, as wel as
you can’t edit the image yourself to change
the names of albums or music artists on a
a border. Margins and padding on inline
the dimensions, and you want the image to
fan site Web page, then you should use a
elements work a lit le dif erently from block
appear bigger or smal er on the page. But

<span> and put your <span> elements into
elements – if you add a margin on al sides
remember, if you rely on the browser to
appropriate classes to group them and style
of an inline element, you’l only see space
scale your image, you may be downloading
them.

added to the left and right. You can add
more data than you need (if the image is
padding to the top and bot om of an inline
larger than you need).

element, but the padding doesn’t af ect the

466

Chapter 11

divs and spans

Hey guys, I know you think
you’re about done, but you
forgot to style the links. They’re
still that default blue color, which
kinda clashes with our site.

brain
power

?

Think about the <a> element. Is
there something about its style that
seems different from other elements?

you are here �

467

how to style links

The <a> element and its multiple personalities

Have you noticed that links act a little differently when it comes to style? Links are chameleons of the element world because, depending on the circumstance, they can change their style at a moment’s notice. Let’s take a closer look:

Here’s a link you’ve never clicked on
before. This is called an “unvisited link”,
or just ‘link”, and it’s blue by default.

And here’s a link you
have clicked on before.

We call these “visited
links”. Usually, visited
links are displayed
in a different color
than unvisited links so
that you can tell the
difference. In most
browsers, visited links

And if you hold your mouse over a link without
are purple by default.

clicking, this is called “hovering”. On some
browsers you’ll see a tool tip that displays the
text of the “title” attribute. And, if you pay
close attention, on some Web pages, you’ll see a
different style as you hover.

Unlike other elements, the style of an <a> element changes depending on its state. If the link has never been clicked on, it has one style, and if it has been clicked on, another. And if you hover over a link, it can have yet another style. Perhaps there’s more to styling <a> elements than meets the eye? You betcha... let’s take a look.

468

Chapter 11

divs and spans

How can you style elements
there are no
based on their state?

Dumb Questions

Q:

A link can be in a few states: it can be unvisited, visited, What happens if I just style the <a>
or in the “hover” state (and a couple of other states too).

element like a normal element? Like:

So, how do you take advantage of all those states? For
a { color: red; }

instance, it would be nice to be able to specify what the
visited and unvisited colors are. Or maybe highlight the
link when the user is hovering over it. If only there were A: You certainly can do that, but then your links
a way...

wil look the same in al states, which makes your
links less user-friendly because you can’t tell which

Well, of course there is, but if we told you it involves
ones you’ve visited and which ones you haven’t.

using pseudo-classes you’d probably just decide you’ve read enough for the night, and close the book. Right? But

Q:

hold on! Pretend we never said the word pseudo-class and What are the other link states you
let’s just look at how you can style your links:

mentioned?

Notice we have the element <a>, followed by a

A: There are two others: focus and active. The
focus state occurs when the browser focuses on your

“:”, followed by the state we want to select.

link. What does that mean? Some browsers al ow you

This selector is applied
to press your tab key to rotate through al the links on
a:link {
to links when they are
your page. When the browser comes to a link, that
color: green;
in an unvisited state.

link has the “focus.” The active state occurs when

}

the user first clicks on a link. One word of warning
about these two states: they aren’t well supported by
a:visited {

And this selector is
al browsers yet, so make sure and test them if they
color: red;
applied to links when
are important to your design.

}

they are visited.

a:hover {

Q:

And this selec

Can’t my links be in multiple states at
color: yellow;
tor
the same time? For instance, my link could be

}

is applied when you
hover over a link.

visited, have the mouse hovering over it, and the
user could be actively clicking on it all at once.

A: They sure can. You determine which style
is applied by the ordering of your rules. So, the
right ordering is general y considered to be: link,

Exercise
visited, focus, hover, and then active. If you use that

Add these rules to the bottom of your
ordering, you’ll get the results you expect.

“lounge.css” file and then save and reload

“lounge.html”. Play around with the links to

Q: Okay, I give. What’s a pseudo-class?

see them in each state. Note that you might
have to clear your browser history to see the
unvisited color (green). Once you’re done,

A: Only one of the most confusing words in the
make sure you take these rules out of your

CSS language. But, as you’ve seen, styling links is

“lounge.css” file before you continue.

pretty straightforward. So, let’s talk about pseudo-
classes...

you are here �

469

more on pseudo-classes

The Pseudo-class Exposed

This week’s interview: getting to know the
pseudo-class.

Head First: Welcome, Pseudo-class. It’s a

Pseudo-class: You can thank your browser
pleasure to have you here. I must confess that
for that. The browser goes through and adds
when they first asked me to do this interview,
all your <a> elements to the right pseudo-

I drew a blank. Pseudo-class? The only thing
classes. If a link’s been visited, no problem;
that came to mind was that ’80s Phil Collins
it goes into the “visited” class. Is the user
song.

hovering over a link? No problem, the

Pseudo-class: Uh, that would be Sussudio.

browser throws it in the “hover” class. Oh,

My name is Pseudo.

now the user isn’t hovering? The browser
yanks it out of the “hover” class.

Head First: Oops. Honest mistake.

Maybe we could start there. Can you tell us

Head First: Wow, I never knew. So there
a little about where Pseudo came from?

are all these classes out there that the browser
is adding and removing elements from

Pseudo-class: Pseudo usually means
behind the scenes.

something that looks like the real thing, but
isn’t.

Pseudo-class: That’s right, and it’s
damned important to know about, otherwise

Head First: And the last name? Class?

how would you give your links style that

Pseudo-class: Everyone knows what a
adapted to what state the link was in?

CSS class is. It’s a grouping you create to

Head First: So, Pseudo, do you just do
place elements in so you can style them
links?

together. Put “pseudo” and “class” together
and you have a pseudo-class: it acts like a

Pseudo-class: No, I do other elements
class, but it isn’t a real class.

too. Some browsers already support pseudo-
classes like active and hover on other types of

Head First: What’s not real about it if it
elements. And there are some other pseudo-
acts like a class?

classes, too. For instance, the pseudo-class

Pseudo-class: Okay, open up an XHTML

:first-child is assigned to the first child of
file and look for the class :visited, or :link, or
any element, like the first paragraph in

:hover. Let me know when you find one.

a <blockquote> . But be careful on
everything other than :link, :visited, and

Head First: I don’t see any.

:hover because browser support isn’t fully

Pseudo-class: And yet, a:link, a:visited,
there yet.

and even a:hover all allow you to specify

Head First: Well, I’ve certainly learned
style, just like they were classes. So, those are
something in this interview. Who knew that
pseudo-classes. In other words, you can style
song was actually called “Sussudio”?! Thanks
pseudo-classes, but no one ever types them
for being here Pseudo-class.

into their XHTML.

Head First: Well then, how do they work?

470

Chapter 11

divs and spans

Putting those pseudo-classes to work

Okay, let’s be honest. You’ve probably just learned the most important thing in this book: pseudo-classes. Why? No, no, not because it allows you to style elements based on various “classes” your browser decides they belong to, like :link or :first-child. And, no, not because they give you really powerful ways to style elements based on things that happen while your visitors are using your page, like :hover.

It’s because the next time you’re in that design meeting and you start talking about pseudo-classes with a real understanding, you’re going to move to the head of the class.

We’re talking promotions and bonuses... at a minimum, the awe and respect of your fellow Web buddies.

So, let’s put those pseudo-classes to good use. You’ve already added some pseudo-class rules to your “lounge.css” and they had a dramatic impact on the look of the links, but they’re probably not quite right for the lounge. So let’s rework the style a little: Okay, big change here. We’re using a descendant selector
combined with a pseudo-class. The first selector says
to select any unvisited <a> element that is nested in an element with the id “elixirs”. So we’re JUST styling the
links inside elixirs.

#elixirs a:link {

On these two we’re setting the color.

color: #007e7e;

For unvisited links, a nice aquamarine...

}

...and for visited links

#elixirs a:visited {
we’re using a dark gray.

color: #333333;

}

Now for the really interesting rule. W

#elixirs a:hover {
hen
the user is hovering ov
background: #f88396;
er the link, we’re
changing the background t
color: #0d5353;
o red. This

}

makes the link look highlighted when you
pass the mouse over it. Give it a try!

Open up your “lounge.css” and rework your a:link, a:visited, and a:hover rules to use the new descendant selector and the new Exercise
style definitions. Save, reload, and turn the page.

you are here �

471

using pseudo-classes for links

Test drive the links

When you reload you should see some new
style in the elixirs section. Keep in mind, to see
the unvisited links you may have to clear your
browser’s history, otherwise the browser will
know you’ve visited these links before.

Now we’ve got green unvisited
links, gray visited links, and a
very cool red highlight when
you hover over the link.

Sharpen your pencil

Your job is to give the “detailed directions” link in the lounge some style. Just like the elixirs link, we want all unvisited links to be aquamarine, and all visited links to be gray. However, we don’t want the other links in the lounge to have any hover style... that’s unique to the elixirs. So, how would you do it? Fill in the blanks to give the “detailed directions” link, and any other links you might add to the lounge later, this style. Check your answer in the back of the chapter and then make the changes in your lounge files.

____________ { __________: #007e7e; }

____________ { __________: #333333; }

472

Chapter 11

divs and spans

Isn’t it about time we talk about the “cascade”?

Well, well, we’re quite far into this book (473 pages to be exact) and we still haven’t told you what the “Cascade” in Cascading Style Sheets is all about. Truth be told, you have to know a lot about CSS to fully understand the cascade. But guess what, you’re almost there, so wait no more.

Here’s just one last piece of information you need to understand the cascade. You already know about using multiple style sheets to either better organize your styles or to support different types of devices. But there are actually some other style sheets hanging around when your users visit your pages. Let’s take a look: First, there are all
the style sheets you’ve

Note that there is a way for a reader
written for your page.

to actually override your styles. To do
that they put “!important” at the end
of a property declaration.

But some browsers also allow users
to create their own styles for

The Author

XHTML elements. If your style

(that’s you!)

sheet doesn’t define these styles,
the user’s style sheet is used instead.

And finally, you already
know that the browser
itself maintains a set of
default styles that are

The Reader
used if you don’t define

(your users)

the styles for an element.

These are also the styles
that are used if you don’t
have any author or reader
style sheets.

When the browser needs to determine
which style to apply to an element, it uses
all these style sheets. Priority is given first
to the author’s styles (that is, your styles),
then to the reader’s styles, and then
finally to the browser’s default styles.

The Browser
you are here �

473

what the cascade does

So, to review, as the page
authors, we can use multiple
style sheets with our XHTML. And, the
user might also supply their own styles,
and then the browser has its default styles,
too. And on top of al that we might have
multiple selectors that apply to the same
element. How do we figure out which
styles an element gets?

That’s actually another way of asking what
cascade does. The cascade is the way the
browser decides, given a bunch of styles
in a bunch of style sheets, which style is
going to be used. To answer that question
we need to bring everything together – all
the various style sheets hanging around,
the rules, and the individual property
declarations in those rules.

In the next two pages we’re going to step
through the nitty gritty details of how all
this works. The details involve a lot of
sorting and various details of determining
which rules are the most specific with
respect to an element. But here’s the payoff:

after going through the next two pages,
you’ll be able to get to the bottom of any
styles that don’t seem to be applied in the
way you expect, and further, you’re going
to understand more about the cascade than

99% of Web page developers out there

(we’re not kidding).

474

Chapter 11

divs and spans

The cascade

For this exercise, you need to “be the browser”. Let’s say you’ve got an <h1> element on a page and you want to know the font-size property for it.

Here’s how you do it:

Step one:

Gather all your style sheets together.

For this step you need ALL the styles sheets: the style sheets the Web page author has written, any style sheets that the reader has added to the mix, and the browser’s default styles. (Remember, you’re the browser now, so you have access to all this stuff !) Step two:

Find all the declarations that match.

We’re looking specifically for the font-size property, so look at all the declarations for font-size that have a selector which could possibly select the <h1> element. Go through all the style sheets and pull out any rules that match <h1> and also have a font-size property.

Remember we

Step three:

mentioned that the
reader could put

Now take all your matches, and sort them.

!important on their

Now that you’ve got all the matching rules together, sort them in the order of CSS properties, and if
author, reader, browser. In other words, if you wrote them as the author of the they do that, those
page, then they are more important than if the reader wrote them. And, in properties come first
turn, the reader’s styles are more important than the browser’s default styles.

when you sort.

Step four:

Now sort all the declarations by how specific they are.

Remember, we talked about this a little, way back in Chapter 8. You can intuitively think about a rule being more specific if it more accurately selects an element; for instance, the descendant selector “blockquote h1” is more specific than just the “h1” selector because it only selects <h1> s inside of

<blockquote> s. But there is a little recipe you can follow to calculate exactly how specific a selector is, and we’ll do that on the next page.

Step five:

Finally, sort any conflicting rules in the order they appear in their individual style sheets.

Now you just need to take the list, and order any conflicting rules so that the ones appearing later (closer to the bottom) of their respective style sheets are more important.

That way, if you put a new rule in your style sheet, it can override any rules before it.

That’s it! The first rule in the sorted list is the winner, and its font-size property is the one to use. Now let’s see how you determine how specific a selector is.

you are here �

475

calculating specificity

Welcome to the “What’s my specificity game”

In the old days we
used four numbers,

To calculate the specificity you start with a set of three numbers, like this: but that was before

XHTML... aren’t you

0 0 0
glad you’re learning
this now?

And then we just tally up various things from the selector, like this: Does the selector

Does the selector
have any classes
have any ids? One
or pseudo-classes?

Does the selector have
point each.

One point each.

any element names?

One point for each.

0 0 0

For instance, the selector “h1” has one element in it, so you get: Both “h1” and “h1.blue” have one
element, so they both get a “1” in

Read this as the
number one.

0 0 1
the right most number column.

“h1.blue” also has one class, so it gets

As another example, the selector “h1.blue” has one element and a “1” in the middle number column.

one class, so you’d get:

Read this as the

0 1 1

Neither have ids in their
number eleven.

selectors, so they both get a

“0” in the left number column

After you’ve tallied up all the ids, classes, and elements, the bigger the specificity number, the more specific the rule. So, since “h1.blue” has a specificity of 11, it is more specific than “h1”, which has a specificity number of 1.

Sharpen your pencilTry your hand at calculating the specificity of these selectors using the rules above: h1.greentea
ol li p
em
p img

.green
span.cd
a:link

#elixirs h1

#sidebar

476

Chapter 11

divs and spans
there are no

Dumb Questions

Q: What makes a specificity number Q: Can you say more about the Q: I can’t get the reader’s style sheet,
bigger than another?

!important thing?

so how can I ever figure out the way the
cascade works?

A: Just read them like real numbers: A: The reader can override a style by 100 (one hundred) is bigger than 010 (ten)

put ing an “!important” on the end of their

A: You can’t, but look at it this way: if
which is bigger than 001 (one), and so on.

property declarations like this:

the reader overrides your styles, then that

Q:

h1 {
is real y beyond your control. So just make
your pages look like you want them to using

What about a rule like “h1, h2”;
font-size: 200%
your styles. If the reader chooses to override
what is its specificity?

!important;
them, then they’l get what they ask for (for
better or for worse).

A:

}

Think of that as two separate rules:

and this wil override any author styles.

an “h1” rule, which has a specificity of “001”

and an “h2” rule that also has a specificity
of “001”.

Putting it all together

Woo hoo! It’s time for an example. Say you want to know the color property for this <h1> element:

<h1 class=”blueberry”>Blueberry Bliss Elixir</h1> h1 {
color: black;

Let’s take this through all the cascade steps:

Remember, you’re

}

the browser, because

Step one:

you’re trying to

Gather all your style sheets together.

figure out how to
display this <h1>
element.

The Browser
h1 {
color: #efefef;

}

body h1 {

That’s you (for now).

color: #cccccc;
h1.blueberry {

}

color: blue;

}

Usually, you’re the author

(the person writing the

CSS). But r

The Author

The Reader
ight now,
you’re the browser.

The person using the browser.

you are here �

477
using the cascade
body h1 {

Step two:

Reader
color: #cccccc;

Find all the declarations that match.

}

h1 {

Here are all the rules that
color: black;
could possibly match the <h1>

Browser

}

element and that contain
h1 {
the color property.

color: #efefef;

}

Step three:

Author
h1.blueberry {
color: blue;

Now take al your matches, and sort them by

}

author, reader, browser.

h1 {
color: #efefef;

}

Author
h1.blueberry {

Here we’ve just
color: blue;

}

reordered the
rules by author,
body h1 {

Reader
then reader, and
color: #cccccc;

}

then browser.

h1 {
color: black;

Browser

}

Step four:

Now sort the declarations by how specific they are. To do that we need to first calculate each specificity score, and then reorder the rules.

h1 {
h1.blueberry {
color: #efefef;

0 0 1
color: blue;

0 1 1

}

}

The rule with
h1.blueberry {

0 1 1
the blueberry
h1 {

0 0 1
color: blue;
class moves
color: #efefef;

}

}

to the top
body h1 {
because it has
body h1 {
color: #cccccc;

0 0 2
the highest
color: #cccccc;

0 0 2

}

}

specificity.

h1 {
h1 {
color: black;

0 0 1
color: black;

0 0 1

}

}

Notice that we only sort within the author,
reader, and browser categories. We don’t re-sort
the entire list, or else the “body h1” rule would
move above the “h1” rule set by the author.

478

Chapter 11
divs and spans

Step five:

Finally, sort any conflicting rules in the order
that they appear in their individual style sheets.

h1.blueberry {
color: blue;

}

Author

We’re okay here, because we don’t have
any conflicting rules at this point. The
h1 {
color: #efefef;
blueberry, with a score of 11, is the clear

}

winner. If there had been two rules with
a score of 011, then the rule appearing
body h1 {

Reader
color: #cccccc;
latest would be the winner.

}

h1 {
color: black;

Browser

}

We have a winner...

After sweating through the first choice of elements, the
sorting, more sorting, and being judged on specificity,
the “h1.blueberry” rule has risen to the top. So the color
property in the <h1> element will be blue.

there are no

Dumb Questions

Q: So, one more time: I get that

A: No. Think of each time you sort as Q: How much of this do I realy need the lower in the CSS file the higher
refining what you’ve done before. So first
to remember?

the precedence, but how does having
you sort for author, reader, browser. Then,
multiple links to style sheets in my
within each of those sortings, you sort for

XHTML work?

specificity. And then, for any elements that

A: You’re going to develop some
have the same specificity, you sort again
intuition for how al these style sheets fit

A:

based on the ordering in the style sheets.

together, and on a day to day basis that

It’s always top to bot om, whether it
intuition wil get you a long way. Every once
is in the same CSS file or not. Just pretend

Q:

in a while, though, you’l see a style popping
that you inserted the CSS all together right

Do readers really make their own
up in your pages that just boggles your
into your file in the order the files are linked.

style sheets?

mind, and that’s when you fal back on your

That’s the order that counts.

training. You’ll be able to work through the

Q:

A:

cascade and before you know it, you’l know

By and large, no. But there are
exactly what’s happening in your page.

So when you sort for specificity,
cases where people with visual impairments
you don’t re-sort everything?

do, and of course you’ve always got the
crowd that just has to tinker with everything.

But, since each reader is control ing only
how they see things, it real y shouldn’t factor
into your designs.

you are here �

479

when the cascade doesn’t provide a value

So, what happens if,
after all this, I still don’t
have any rules with a property
declaration for the property
value I’m trying to figure out?

Ah, good question. We actually talked about this a little in Chapter 8. If you don’t find a match for the property in
any rules in the cascade, then you try to use inheritance.

Remember that not all properties are inherited, like
border properties for instance. But for the properties that are inherited (like color, font-family, line-height, and so on), the browser looks at the ancestors of the element, starting with its parent, and tries to find a value for the property.

If it does, there’s your property value.

Got it. Hey, but what
if the property isn’t inherited
or I can’t find a value in the
ancestor’s rules? Then what?

Then the only thing left to do is fall back
on the default values that are set in the
browser’s style sheets, and all browsers
should have default styles for every element.

Oh, and why is this
called the “cascade”

anyway?

The name “cascade” was chosen because of the
way that styles coming from multiple style sheets can
all “cascade” down into the page, with the most specific
styling being applied to each element. (If that doesn’t clear things right up for you about why it’s called cascade, don’t feel bad. It didn’t make it any clearer for us, either. Just call it “CSS” and move on.)

480

Chapter 11
divs and spans

STOP! Do this exercise before going
on to the next chapter!

Super
brain
power

?

This is a special brain power; so special that we’re going to let you think about it between chapters. Here’s what you need to do: 1

Open the file “lounge.html” and locate the elixirs <div> .

2

Move the entire elixirs <div> section to the top of the file so it’s just below the paragraph that contains the
lounge logo.

3

Save and reload your page. What changed?

4

Open the file “lounge.css”.

5

Locate the “#elixirs” rule.

6

Add this declaration at the bottom of the rule:

float: right;

7

Save your file, and reload the page in your browser.

What changed? What do you think this declaration does?

you are here �

481

review of divs, spans, and pseudo-classes

BULLET POINTS

n

<div> elements are used to group related
n

You can use descendant selectors to select
elements together into logical sections.

elements nested within other elements. For
instance, the descendant selector

n

Creating logical sections can help you identify
the main content areas, header, and footer of
div h2 { ... }

your page.

selects all <h2>s nested in <div> elements

(including children, grandchildren, etc.).

n

You can use <div> elements to group
elements together that need a common style.

n

You can use shortcuts for related properties.

For instance, padding-top, padding-right,
padding-bottom, and padding-left are all

n

Use nested <div> elements to add further
structure to your files for clarity or styling. But
related to padding, and can be specified with
don’t add structure unless you really need it.

one shortcut rule, padding.

n

Padding, margin, border, background, and

n

Once you have grouped together sections of
content with <div> elements, you can style
font properties can all be specified with
the <div>s just like you would any other block
shortcuts.

element. For example, you can add a border
around a group of elements using the border
n

The <span> inline element is similar to the
property on the <div> they are nested in.

<div> element: it is used to group together
related inline elements and text.

n

The width property sets the width of the
content area of an element.

n

Just like with <div>, you can add <span>
elements to classes (or give <span> elements
unique ids) to style them.

n

The total width of an element is the width
of the content area, plus the width of any
padding, border, and margins you add.

n

The <a> element is an example of an element
with different states. The main <a> element
states are unvisited, visited, and hover.

n

Once you set the width of an element, it no
longer expands to fit the entire width of the
browser window.

n

You can style each of these states separately
with pseudo-classes. The pseudo-classes
used most often with the <a> element are :link,

n

Text-align is a property for block elements that
centers all inline content in the block element.

for unvisited links, :visited, for visited links,

It is inherited by any nested block elements.

and :hover, for the hover state.

n

Other elements support the :hover pseudo-

class, and some browsers also support the

:first-child, :active, and :focus pseudo-classes
for other elements.

XHTMLcross on Vacation

Since you’ve got a Super Brain Power to work on, we gave the XHTMLcross a vacation in this chapter. Don’t worry, he’ll be back in the next one.

482

Chapter 11

divs and spans

Sharpen your pencil

Solution

Here’s a box that has all the widths labelled. Your job was to figure out the width of an entire box. Here’s the solution.

30 + 2 + 5 + 200 + 10 + 2 + 20 = 269

Sharpen your pencil

Solution

So now that you understand widths, what’s the total width of the elixirs box? To start with, we know the content area is 200
pixels. We’ve also set some left and right padding that affects the width, as well as a border that’s set to “thin”. Just assume a thin border is 1 pixel thick, like it is on most browsers. And what about margins? We set a left margin, but no right margin, so the right margin is 0 pixels by default.

Your job was to figure out the total width of the elixirs <div>.

Here’s the solution.

20 + 20 + 200 + 1 + 1 + 0 + 20 = 262
ea
left padding
right padding
content ar
left border
right border
right margin
left margin

Sharpen your pencil

Solution

Your turn. Write the selector that selects only <h3> elements inside the elixirs <div>.

In your rule, set the color property to #d12c47. Also label the elements in the graph below that are selected. Here’s the solution.

#elixirs h3 {
color: #d12c47;

}

Here’s the rule. We select any

<h3> descendant of an element
with the id elixirs. And here’s
what the graph looks like.

html
body
h1
h2
div id=”elixirs”

div id=”calendar”

h2
h2
h3
h3
h3
h1
h2
h3
you are here �

483

exercise solutions

It’s time to put all your new knowledge to work. You’ll notice at the bottom of the lounge there’s a small section with copyright information that acts as a footer for the Exercise
page. Add a <div> to make this into its own logical section. After you’ve done that Solutions
style it with these properties:

Let’s make the text really small.

font-size: 50%;

You know, FINE PRINT.

text-align: center;

line-height: normal;

And let’s center the text.

margin-top: 30px;

We’re also setting the line-height
to be “normal”.

And let’s add some top margin to give the
footer a little breathing room.

Place <div> tags around the

And give it an id named “footer”.

copyright information.

<div id=”footer”>

<p>

&copy; 2005, Head First Lounge<br />

All trademarks and registered trademarks appearing on
this site are the property of their respective owners.

</p>

</div>

And here’s the CSS for the footer.

#footer {
font-size: 50%;
text-align: center;
line-height: normal;
margin-top: 30px;

}

484

Chapter 11

divs and spans

Sharpen your pencil

Solution

Your job was to finish adding the <span> elements to the rest of the music recommendations and test your page. Here’s the solution:

<ul>

<li><span class=”cd”> Buddha Bar</span> ,

<span class=”artist”> Claude Challe</span></li>

<li><span class=”cd”> When It Falls</span> ,

<span class=”artist”> Zero 7</span></li>

<li><span class=”cd”> Earth 7</span> ,

<span class=”artist”> L.T.J. Bukem</span></li>

<li><span class=”cd”> Le Roi Est Mort, Vive Le Roi! </span> ,

<span class=”artist”> Enigma</span></li>

<li><span class=”cd”> Music for Airports</span> ,

<span class=”artist”> Brian Eno</span></li>

</ul>
you are here �

485

exercise solutions

Sharpen your pencil

Solution

Your job is to give the “detailed directions” link in the lounge some style. Just like the elixirs link, we want all unvisited links to be aquamarine, and all visited links to be gray. However, we don’t want the other links in the lounge to have any hover style... that’s unique to the elixirs. So, how would you do it? Fill in the blanks to give the “detailed directions” link, and any other links you might add to the lounge later, this style. Here’s the solution.

____________ { __________: #007e7e; }

a:link
color

____________ { __________: #333333; }

a:visited
color

Sharpen your pencil Try your hand at caclulating the specificity of these selectors using the Solution cascade rules. Here’s the solution.

h1.greentea 0 1 1
ol li p

0 0 3
em

0 0 1
p img

0 0 2

.green

0 1 0
span.cd

0 1 1
a:link

0 1 1

#elixirs h1

1 0 1

#sidebar

1 0 0

486

Chapter 11

12 layout and positioning

Arranging Elements

You can bet all my divs and
spans are in the right place.

It’s time to teach your XHTML elements new tricks. We’re not going to let those XHTML elements just sit there anymore – it’s about time they get up and help us create some pages with real layouts. How? Well, you’ve got a good feel for the <div> and <span> structural elements and you know all about how the box model works, right? So, now it’s time to use all that knowledge to craft some real designs. No, we’re not just talking about more background and font colors, we’re talking about full blown professional designs using multi-column layouts. This is the chapter where everything you’ve learned comes together.

this is a new chapter

487

examining a two column page

Did you do the Super Brain Power?

If you didn’t do the Super Brain Power at the end of the last chapter, then march right back there and
do it. It’s required.

Okay, now that we have that out of the way, at
the end of the last chapter, we left you with a bit
of a cliffhanger. We asked you to move the elixirs

<div> up under the logo, and then add one little property to the elixirs rule in your CSS, like this:

float: right;

And, wow, what a difference one property
can make! All of a sudden the page has gone
from a fairly ordinary-looking Web page to a
great-looking Web page with two columns. It’s
immediately more readable and pleasant to the
eye.

So what’s the magic? How did this seemingly
innocent little property produce such big effects?

And, can we use this property to do even more
interesting things with our pages? Well, of course,
this is Head First, after all. But first, you’re
going to need to learn how a browser lays out
elements on a page. Once you know that, we can
talk about all kinds of ways you can alter how it
does that layout, and also how you can start to
position your elements on the page.

Here’s the good news: you already know all
about block elements and inline elements, and
you even know about the box model. These are
the real foundations of how the browser puts
a page together. Now all you need to know is
exactly how the browser takes all the elements in
a page, and decides where they go.

488

Chapter 12

layout and positioning

Use the flow, Luke

The Flow is what gives a CSS master his power. It’s an
energy field created by all living things. It surrounds us
and penetrates us. It binds the galaxy together....

Oh, sorry.

Flow is what the browser uses to lay out a page of

XHTML elements. The browser starts at the top of any

XHTML file and follows the flow of elements from top
to bottom, displaying each element it encounters. And,
just considering the block elements for a moment, it
puts a linebreak between each one. So the first element
in a file is displayed first, then a linebreak, followed by the second element, then a linebreak, and so on, from
the top of your file to the bottom. That’s flow.

And here’s the XHTML flowed

Here’s a little “abbreviated” XHTML.

onto a page.

Each block element is

<html>
taken in the order it
h1

<head>...</head>
appears in the markup,

<body>
h2
and placed on the page.

<h1>...</h1>

<h2>...</h2>
p

<p>...</p>

<h2>...</h2>

<p>...</p>

Each new block
h2

<p>...</p>
element causes a

<p>...</p>
linebreak.

p

</body>

</html>
p

Notice that elements
p
take up the full width
of the page.

you are here �

489

playing with flow

Here’s your page. Flow

BE the
the block elements in

“lounge.html” here.

Open your “lounge.html”

file and locate all the
block elements. Flow each
one on to the page to the
left. Just concentrate on
the block elements nested
directly inside the body
element. You can also
ignore the “float” property
in your CSS because you
don’t know what it does yet. Check
your answer before moving on.

Here are all the block
elements you’ll need to
complete the job.

h1
h2
pp p
p
pp p
divdiv
ul

490

Chapter 12

layout and positioning

What about inline elements?

Here’s another little

So you know that block elements flow top to
snippet of XHTML.

bottom, with a linebreak in between each element.

Easy enough. What about the inline elements?

Inline elements are flowed next to each other,

<p>
horizontally, from top left to bottom right. Here’s

Join us <em> any evening</em> for how that works.

these and all our other wonderful <a
href=”beverages/elixir.html” title=”Head

First Lounge Elixirs”> elixirs</a>.

</p>

If we take the inline
content of this <p> element
and flow it onto the page,
we start at the top left.

p

The inline elements are laid next to one
text
em
text
a
another horizontally, as long as there is
room on the right to place them.

Here, there’s room to fit all the inline
elements horizontally. Notice that text
is a special case of an inline element. The
browser breaks it into inline elements that

So what if we make the browser window
are the right size to fit the space.

a little thinner, or we reduce the size of
the content area with the width property?

Then there’s less room to place the inline
p
elements in. Let’s see how this works.

text
em
text

Now the content has been flowed left to
text
a
right until there’s no more room, and then
the content is placed on the next line. Notice
the browser had to break the text up a little
differently to make it fit nicely.

p
text
em
text

And if we make the content area even thinner,
text
look what happens. The browser uses as many lines
text
a
as necessary to flow the content into the space.

you are here �

491
how flow works

How it all works together

Now that you know how block and inline elements are
flowed, let’s put them together. We’ll use a typical page

Here, we’ve resized the browser
with headings, paragraphs, and a few inline elements like
window, squeezing all the content
spans, some emphasis elements, and even images. And,
into a smaller horizontal size.

we can’t forget inline text.

We’re starting with a browser

Things flow the same way, although in
window that’s been resized to
some places, the inline elements take
a fairly wide width.

up more vertical lines to fit.

Each block element is
flowed top to bottom
h1
text
as you’d expect, with a
text
linebreak in between each.

h2
text
h1
text
p
text
h2
text
text
p
text
h2
text
h2
text
p
span
em
span
p

And the inline
span
em
span
em
em
elements are
flowed from the
p
text
top left to the
p
text
bottom right
text
text
of the element’s
text
content area.

text
p
text
img
img
img
img
p
img
img
img
img

If the inline content of each block fits the
width of the content area, then it’s placed
there; otherwise, more vertical room is made for
the content and it’s continued on the next line.

Now the block elements take up
more vertical room because the inline
content has to fit into a smaller
horizontal space.

492

Chapter 12

layout and positioning

One more thing you should know about flow and boxes

Let’s zoom in just a bit and look at one more aspect of how the browser lays out block and inline elements. It turns out that the browser treats margins differently depending on which type of element is being placed on the page.

When the browser is placing t wo inline
elements next to each other...

When the browser has the task of placing two inline elements side by side, and those elements have margins, then the browser does what you might expect. It creates enough space between the elements to account for both margins. So, if the left element has a margin of 10 pixels and the right has a margin of 20
pixels, then there will be 30 pixels of space between the two elements.

margin
margin

Here we’ve got two images side

The Head First Lounge is, no doubt, the

During your stay at the lounge, you’ll
by side. Images are inline elements,
biggest trendsetter in Webville. Stop in
enjoy a smooth mixture of ambient and
to sample the eclectic offering of elixirs,
mystic sounds, filling the lounge and
teas, and coffees, or, stay a bit longer
adding an extra dimension to your dining
right? So, the browser uses both
and enjoy the multicultural culinary
experience. The decor surrounds you
menu that combines a harmony of taste,
with the relaxing sentiments of sights
texture, and color with the best in fresh
from eras past. And, don’t forget, the
of their margins to calculate the
and healthy ingredients.

lounge offers free wireless access to the

Internet, so bring your laptop.

space that goes between them.

When the browser is placing t wo block
elements on top of each other...

Here’s where things get more interesting. When the browser places two block elements on top of each other, it collapses their shared margins together. The height of the collapsed margin is the height of the largest margin.

The Head First Lounge is, no doubt, the
biggest trendsetter in Webville. Stop in

The Head First Lounge is, no doubt, the
to sample the eclectic offering of elixirs,
biggest trendsetter in Webville. Stop in

Their shared margin is
teas, and coffees, or, stay a bit longer
to sample the eclectic offering of elixirs,
and enjoy the multicultural culinary
teas, and coffees, or, stay a bit longer
menu that combines a harmony of taste,
the size of the larger
and enjoy the multicultural culinary
texture, and color with the best in fresh
menu that combines a harmony of taste,

When the browser
and healthy ingredients.

texture, and color with the best in fresh
of the two margins.

and healthy ingredients.

places two block
elements on top

Say the top element’s
of each other, it
bottom margin is 10
pixels, and the bottom

During your stay at the lounge, you’ll
collapses their

During your stay at the lounge, you’ll
enjoy a smooth mixture of ambient and
enjoy a smooth mixture of ambient and
mystic sounds, filling the lounge and
element’s top margin
mystic sounds, filling the lounge and
adding an extra dimension to your dining
margins.

adding an extra dimension to your dining
experience. The decor surrounds you
experience. The decor surrounds you
with the relaxing sentiments of sights
is 20 pixels. Then the
with the relaxing sentiments of sights
from eras past. And, don’t forget, the
from eras past. And, don’t forget, the
lounge offers free wireless access to the
lounge offers free wireless access to the

Internet, so bring your laptop.

collapsed margin will be

Internet, so bring your laptop.

20 pixels.

you are here �

493

questioning margins
there are no

Dumb Questions

Q:

element has a border, the margins will

So if I have a block element with a A: They sure can, although you won’t never touch, so they won’t collapse. But
zero margin, and a block element below
find that you set the margins of inline
if you remove the border, they will. This is
it with a top margin of 20, the margin
elements often. The one exception is
sometimes puzzling when you first see it
between them would end up being 20?

images. It is very common to not only set
happen, so put it in the back of your mind for
margins but also borders and padding on
when it occurs.

A:

images. And while we aren’t going to be

Right. If one of the margins is bigger, set ing any inline element margins in this Q: So how exactly does text work as
then the margin becomes the larger of the
chapter, we wil be set ing the border on one an inline element since its content is not two, even if one margin is zero. But if the
a little later.

an element?

margins are the same, say, 10 pixels, then
they just get col apsed together to 10 pixels

Q:

total.

What if I have one element nested

A:

inside another and they both have

Even if text is content, the browser

Q:

margins? Can they collapse?

needs to flow it onto the page, right? So the

Can inline elements real y have
browser figures out how much text fits on a
margins?

A:

given line, and then treats that line of text

Yes, that can happen. Here’s how
as if it were an inline element. The browser
to figure out when they wil : whenever you
even creates a lit le box around it. As you’ve
have two vertical margins touching, they
seen, if you resize the page, then all those
will collapse, even if one element is nested
blocks may change as the text is refit within
inside the other. Notice that if the outer
the content area.

We’ve been through seven
pages of “flow.” When are you going to
explain that one little property we put
into our CSS file? You know, the
float: right;

To understand float, you have
to understand flow.

It might be one little property, but the way it works is closely tied to how the browser flows elements and content onto the page.

But hey, you know that now, so we can explain float.

Here’s the short answer: the float property first takes an element and floats it as far left or right as it can (based on the value of float). It then flows all the content below it around the element.

Of course there’s a few more details, so let’s take a look...

494

Chapter 12
layout and positioning

How to float an element

Let’s step through an example of how you get
an element to float, and then we’ll look at what
it does to the flow of the page when you do.

h1
text
h2
text
p id=“amazing”

First, give it an identity
text

Let’s take one of these paragraphs and give
h2
text
it an id. We’d like to call it the “amazing
floating paragraph”, but we’ll just call it
p
span
em
span
em

“amazing” for short.

p
text
text
text
p
img
img
img
img
h1
text

Now give it a width
h2
text

A requirement for any floating element is that it
p id=“amazing”

have a width. We’ll make this paragraph 200 pixels
text
wide. Here’s the rule:

text
text

#amazing {
h2
width: 200px;
text

}

p
span
em
span
em

Now the paragraph is 200 pixels
p
text
wide, and the inline content
text
contained in it has adjusted to that
text
width. Keep in mind, the paragraph
is a block element, so no elements are
p
going to move up beside it because all
img
img
img
img
block elements have linebreaks before
and after them.

you are here �

495

how float works

Now float it
h1
text

Now let’s add the float property. The float
property can be set to either left or right. Let’s
h2
text
stick with right:

p id=“amazing”

#amazing {
width: 200px;
text
float: right;
text

}

text

Now that we’ve floated the “amazing” paragraph,
let’s step through how the browser flows it and
everything else on the page.

(1) First the browser flows the

(2) When the browser encounters
elements on the page as usual,
the floated element, it places it a
starting at the top of the file and
ll
the way to the right. It also remov
moving towards the bottom.

es
the paragraph from the flow, like
it’s floating on the page.

(3) Because the floated paragraph

Notice that the
h1
text
has been removed from the normal
block elements are
h2
text
flow, the block elements are filled in,
positioned under
like the paragraph isn’t even there.

the floated element.

h2
text
p id=“amazing”

That’s because the
text
text
floated element is no
p
longer part of the
span
em
text
normal flow.

em
span
text
p
text

(4) But when the inline elements

How
are positioned, they respect the
ever, when the
text
inline elements ar
boundaries of the floated element.

e
text
flow

So they are flowed around it.

ed within the
text
block elements, they
flow around the
p
borders of the
img
img
img
img
floating element.

496

Chapter 12

layout and positioning

Behind the scenes at the lounge

Now you know all about flow and how floated elements

Remember, in addition to setting the
are placed on the page. Let’s look back at the lounge and
elixirs <div> to float right, we also
see how this all fits together.

moved the <div> up just below the
logo at the top of the page.

Moving the <div> allowed us to float it to the
right and then have the entire page flow around
it. If we had left the elixirs <div> below the music
recommendations, then the elixirs would have been
floated right after most of the page had been placed.

All these elements follow the
elixirs in the XHTML, so
they are flowed around it.

Remember that the elixirs <div> is floating
on top of the page. All the other elements
are underneath it, but the inline content
respects the elixirs’ boundaries when they
are flowing into the page.

Also notice that the text wraps
around the bottom of the elixirs,
because the text is contained in a
block element that is the width of
the page. If yours doesn’t wrap, try
narrowing your browser window until
the text wraps underneath the elixirs.

you are here �

497

a new assignment: starbuzz

Move the elixirs <div> back to its original place below the music recommendations, then save and reload the page. Where does the Exercise element float now? Check your answer in the back and then put your elixirs

<div> back underneath the header.

Nice stuff. Do you
think I’m going to watch
these fantastic lounge designs and
not want you to improve Starbuzz?

You’ve got a blank check. . take

Starbuzz to the next level.

It looks like you’ve got a new assignment. Starbuzz
really could use some improvement. Sure, you’ve
done a great job of creating the typical top to
bottom page, but now that you know flow, you
should be able to give Starbuzz Coffee a slick new
look that is more user-friendly than the last design.

We do have a little secret though... we’ve been
working on this one a bit already. We’ve created
an updated version of the site. Your job is going
to be to provide all the layout. Don’t worry, we’ll
bring you up to speed on everything we’ve done so
far – it’s nothing you haven’t seen before.

498

Chapter 12

layout and positioning

The new Starbuzz

Let’s take a quick look at what we’ve got so
far, starting with the page as it looks now.

Then we’ll take a peek at the markup and
the CSS that’s styling it.

We’ve got a header now with a new spiffy Starbuzz logo and the company mission statement. This is actually just a GIF image.

We’ve got four sections: the header,
a main content section, a section
advertising something new called the

“Bean Machine,” and a footer.

Each section is a <div> that can
be styled independently.

It looks like we’ve got one
background color for the
page as a whole, and then
each <div> is using an image
as a background.

Here’s the “Bean Machine” area. This links to
a new area of Starbuzz Coffee where you can
order your coffee beans online. This link doesn’t
work just yet because you’re going to build the

Bean Machine in an upcoming chapter.

Notice that we’ve styled the

Here’s the footer. It doesn’t
links in an interesting way,
use a background image, just a
with dotted underlines...

background color.

you are here �

499
looking over the markup

A look at the markup

Now let’s take a look at the new Starbuzz markup. We’ve taken each of the logical sections and placed it into a <div> , each with its own id. Beyond the <div> s and <span> s, there’s really nothing here that you hadn’t already seen by about Chapter 5. So, take a quick look and get familiar with the structure, and then turn the page to check out the CSS style.

Here’s all the usual

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”

“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”> XHTML administravia.

<html xmlns=“http://www.w3.org/1999/xhtml” lang=“en” xml:lang=“en” > Followed by a <div> for

<head>
the header and a <div>

<meta http-equiv=“Content-Type” content=“text/html; charset=ISO-8859-1” /> for the main content area.

<title> Starbuzz Coffee</title>

<link type=“text/css” rel=“stylesheet” href=“starbuzz.css” />

</head>

<body>

<div id=“header”>

<img src=“images/header.gif” alt=“Starbuzz Coffee header image” />

</div>

<div id=”main”>

<h1> QUALITY COFFEE, QUALITY CAFFEINE</h1>

<p>

At Starbuzz Coffee, we are dedicated to filling all your caffeine needs through our quality coffees and teas. Sure, we want you to have a great cup of coffee and a great coffee experience as well, but we’re the only company that actively monitors and optimizes caffeine levels. So stop by and fill your cup, or order online with our new Bean Machine online order form, and get that quality Starbuzz coffee that you know will meet your caffeine standards.

</p>

<p>

And, did we mention <em> caffeine</em> ? We’ve just started funding the guys doing all the wonderful research at the <a href=“http://buzz.headfirstlabs.com”

title=“Read all about caffeine on the Buzz”> Caffeine Buzz</a> .

If you want the latest on coffee and other caffeine products, stop by and pay them a visit.

</p>

<h1> OUR STORY</h1>

<p>

“A man, a plan, a coffee bean”. Okay, that doesn’t make a palindrome, but it resulted in a damn good cup of coffee. Starbuzz’s CEO is that man, and you already know his plan: a Starbuzz on every corner.

</p>

<p>

In only a few years he’s executed that plan and today
you can enjoy Starbuzz just about anywhere. And, of course, the big news this year is that Starbuzz teamed up with Head First readers to create Starbuzz’s Web presence, which is growing rapidly and helping to meet the caffeine needs of a whole new set of customers.

</p>

<h1> STARBUZZ COFFEE BEVERAGES</h1>

<p>

We’ve got a variety of caffeinated beverages to choose

500

Chapter 12
layout and positioning

This is more of the main content
area continued over here.

from at Starbuzz, including our

<a href=“beverages.html#house” title=“House Blend”> House Blend</a>,

<a href=“beverages.html#mocha” title=“Mocha Cafe Latte”> Mocha Cafe Latte</a>,

<a href=“beverages.html#cappuccino” title=“Cappuccino”> Cappuccino</a>,

and a favorite of our customers,

<a href=“beverages.html#chai” title=“Chai Tea”> Chai Tea</a>.

</p>

<p>

We also offer a variety of coffee beans, whole or ground, for you to take home with you. Order your coffee today using our online

<a href=“form.html” title=“The Bean Machine”> Bean Machine</a> , and take the Starbuzz Coffee experience home.

</p>

</div>

<div id=“sidebar”>

<p class=“beanheading”>

<img src=“images/bag.gif” alt=“Bean Machine bag” />

<br />

Here’s the <div> for the Bean Machine.

ORDER ONLINE
with the

We’ve given it an id of “sidebar”. Hmm,

<a href=“form.html”> BEAN MACHINE</a> wonder what that could mean?

<br />

<span class=“slogan”>

FAST <br />

FRESH <br />

TO YOUR DOOR <br />

</span>

</p>

<p>

Why wait? You can order all our fine coffees right from the Internet with our new, automated Bean Machine. How does it work? Just click on the Bean Machine link, enter your order, and behind the scenes, your coffee is roasted, ground (if you want), packaged, and shipped to your door.

</p>

</div>

<div id=“footer”>

&copy; 2005, Starbuzz Coffee

<br />

All trademarks and registered trademarks appearing on
this site are the property of their respective owners.

</div>

And finally, we have the <div> that

makes up the footer of the page.

</body>

</html>
you are here �

501
beginning starbuzz style

And a look at the style

Let’s get a good look at the CSS that styles the new Starbuzz page. Step through the CSS rules carefully. While the new Starbuzz page may look a little advanced, you’ll see it’s all just simple CSS that you already know.

body {

First we just set up some
background-color: #b5a789;
basics in the body: a
font-family: Georgia, “Times New Roman”, Times, serif; background color, fonts,
font-size: small;
margin: 0px;
and we also set the

}

margin of the body to 0.

This makes sure there’s no

#header {
extra room around the
background-color: #675c47;
margin: 10px;
edges of the page.

height: 108px;

}

#main {
background: #efe5d0 url(images/background.gif) top left; font-size: 105%;
padding: 15px;
margin: 0px 10px 10px 10px;

}

Next we have a rule for
each logical section. In

#sidebar {
each, we’re tweaking the
background: #efe5d0 url(images/background.gif) bottom right; font-size: 105%;
font size, adding padding
padding: 15px;
and margins and also - in
margin: 0px 10px 10px 10px;
the case of main and the

}

sidebar - specifying a

#footer {
background image.

background-color: #675c47;
color: #efe5d0;
text-align: center;
padding: 15px;

Next we set up the fonts and
margin: 10px;
colors on the headings.

font-size: 90%;

}

h1 {
font-size: 120%;

And then some colors on the class
color: #954b4b;
called slogan, which is used in the

}

sidebar <div>. And likewise with

.slogan { color: #954b4b;}

the beanheading class, which is
used there as well.

.beanheading {
text-align: center;
line-height: 1.8em;

}

502

Chapter 12

layout and positioning
a:link {
color: #b76666;

And for the last two rules in the Starbuzz CSS we use
text-decoration: none;
the a:link and a:visited pseudo-classes to style the links.

border-bottom: thin dotted #b76666;

}a:visited {
color: #675c47;
text-decoration: none;

Notic
border-bottom: thin dotted #675c47;
e that we’re getting a nice dotted

}

underline effect on the links by using a
dotted bottom border instead of an
underline. This is a great example of using
the border prop

We’re setting the border-bott
erty on an inline element.

om
as a shortcut.

Let’s take Starbuzz to the next level

Here’s the goal: to turn Starbuzz Coffee into the site on
the right. To do that, we need to move the Bean Machine
sidebar over to the right so we’ve got a nice two-column
page. Well, you’ve done this once already with the lounge,
right? So, based on that, here’s what you need to do:

1

Give the element you’re going to float a unique
name using an id. That’s already done.

2

Make sure the element’s XHTML is just below
the element you want it to float under; in this
case, the Starbuzz header.

3

Set a width on the element.

4

Float the element to the left or the right. It looks
like you want to float it right.

Let’s get started. In a few simple steps, we should have the We’ve got a nice two-column look

Starbuzz CEO sending a few Chai Teas over on the house.

here, with discrete columns.

you are here �

503

moving the sidebar

Move the sidebar just below
the header

It’s a fact of life that when you float an element, you
need to move the XHTML for the element directly
below the element that you want it to float below. In this
case, the sidebar needs to come under the header. So,
go ahead and locate the sidebar <div> in your editor and move the entire <div> to just below the header

<div> . You’ll find the XHTML in the file “index.html”

in the “chapter12/starbuzz” folder. After you’ve done
that and saved, reload the page.

Now the sidebar should be on
top of the main content area.

Set the width of the sidebar
and float it

Let’s set the width of the sidebar to 280 pixels. And to float the sidebar, add a float property, like this:

We’re using an id selector to select the
element with the id “sidebar”, which we
know is the <div> for the sidebar.

#sidebar {
background: #efe5d0 url(images/background.gif) bottom right; font-size: 105%;
padding: 15px;
margin: 0px 10px 10px 10px;
width: 280px;
float: right;

We’re setting the width of the

}

content area to 280 pixels.

And then we’re floating the sidebar to the right. Remember, this moves the sidebar as far right as possible below the header, and it also removes the sidebar from the normal flow. Everything else below the sidebar in the XHTML is going to move up and wrap around it.

504

Chapter 12

layout and positioning

I have an idea. In the
future, why don’t we float the main
content to the left, rather than the
sidebar to the right. Since the main
content is already at the top, we
wouldn’t have to move things around,
and we get the same effect.

That’s actually a great idea, but
there are a couple of issues.

On paper this looks like a great idea. What
we do is set a width on the main content

<div> and float it to the left, and then let
the rest of the page flow around it. That
way we get to keep the ordering of the
page and we also get two columns.

The only problem is, this doesn’t result in a
very nice page. Here’s why: remember, you
have to set a width on the element that you
are going to float, and if you set a width
on the content area, then its width is going
to remain fixed while the rest of the page
resizes along with the width of the browser.

Typically, sidebars are designed to be
narrower than the main content area, and
often look terrible when they expand. So,
in most designs, you want the main content
area to expand, not the sidebar.

But we are going to look at a way to use
this idea that works great. So hang on to
this idea. We’ll also talk a little more about
why you’d even care what order your
sections are in.

you are here �

505

testing the float

Test driving Starbuzz

Make sure you add the new sidebar properties to the

“starbuzz.css” file in the “chapter12/starbuzz” folder, and then reload the Starbuzz page. Let’s see what we’ve got...

Hmm, this looks pretty good, but if you flip back three
pages you’ll see we’re not quite where we want to be.

The main content and the
sidebar are on the left
and the right, but they
don’t really look like two
columns yet.

Look at how the
background images of
the two sections just
run together. There’s
no separation between
the columns.

And the text wraps around and under the sidebar, which doesn’t make this look like two columns either. Hmm, that is actually how the lounge worked too - maybe we should have expected that.

506

Chapter 12

layout and positioning

Fixing the t wo-column problem

Are you sitting there waiting for us to come riding in on a white horse with the magic property that solves all this? Well, that’s not going to happen.

This is the point in CSS where page layout becomes more an art – or at least a set of techniques – than a set of properties that can solve every problem. So, what we’re going to do is solve this using a common technique that is widely used. It’s not perfect, as you’ll see, but in most cases it gives you good results. And after this, you’re going to see a few other ways to approach the same two-column problem. What’s important here is that you The first thing to
understand the techniques, and why they work, so you can apply them to remember is that the
your own problems, and even adapt them where necessary.

sidebar is floating on
the page. The main
content area extends
all the way under it.

So, what if we give the main
content area a right margin
that is at least as big as the
sidebar? Then its content will
extend almost to the sidebar,
but not all the way.

Then we’ll have separation between
the two, and since margins are
transparent and don’t show the
background image, the background
color of the page itself should show
through. And that’s what we’re
looking for (flip back a few pages
and you’ll see).

Let’s make the margin as
wide as the sidebar.

you are here �

507

using margins for two columns

Sharpen your pencil

What we want to do is set a right margin on the main content section so that it’s the same width as the sidebar. But how big is the sidebar? Well, we hope you aren’t already rusty since the last chapter. Here’s all the information you need to compute the width of the sidebar. Check your answer in the back of the chapter.

#sidebar {
background: #efe5d0 url(images/background.gif) bottom right; font-size: 105%;
padding: 15px;
margin: 0px 10px 10px 10px;
width: 280px;
float: right;

}

You’ll find everything you
need to compute the width
of the sidebar in this rule.

Setting the margin on the main section

The width of the sidebar is 330 pixels, and that includes 10 pixels of left margin on the sidebar, which will provide the separation we need between the two columns (what the publishing world calls a “gutter”). Add the 330 pixel right margin to the

#main rule in your “starbuzz.css” file, like we’ve done below:

#main {
background: #efe5d0 url(images/background.gif) top left; font-size: 105%;
padding: 15px;
margin: 10px;
margin: 0px 330px 10px 10px;

}

We’re changing the right margin to 330 pixels
to match the size of the sidebar.

508

Chapter 12

layout and positioning

Test drive

As usual, save your “starbuzz.css” file and then
reload “index.html”. You should now see a
nice gutter between the two columns. Let’s
think through how this is working one more
time. The sidebar is floating right, so it’s been
moved as far to the right as possible, and the
whole <div> has been removed from the
normal flow and is floating on top of the page.

Now the main content <div> is still taking
up the width of the browser (because that’s
what block elements do), but we’ve given it a
margin as wide as the sidebar to reduce the
width of the content area. The result is a nice
two column look. You know the box of the
main <div> still goes under the sidebar, but
we won’t tell anyone if you don’t.

By expanding the margin
of the main <div>, we’re
creating the illusion of a two
column layout, complete with
a gutter in between.

Uh oh, we have
another problem

As you were test driving the
page you might have noticed
a little problem. If you
resize the browser to a wide
position, the footer comes up
underneath the sidebar. Why?

Well, remember, the sidebar
is not in the flow, so the footer
pretty much ignores it, and
when the content area is too
short, the footer moves right up.

We could use the same margin
trick on the footer, but then the
footer would only be under the
content area, not the whole
page. So, what now?

We’ve got a problem. When you resize your browser to a
wide position, the footer and the sidebar start to overlap.

you are here �

509

a margin alternative

Wait a sec. Before you
get way into solving that
problem, I have to ask, why did we
have to go to all this trouble of using
a margin? Why don’t we just set the
width of the main area? Wouldn’t
that do the same thing?

This is another solution that
sounds good... until you try it.

The problem with setting a width on both the
content area and the sidebar is that this doesn’t
allow the page to expand and contract correctly
because both have fixed widths. Check the screen-
shots below that show how it works (or rather,
doesn’t work).

But this is good. You’re thinking in the right ways,
and a little later in the chapter we’re going to come
back to this idea when we talk about “liquid versus
fixed” layouts. There are ways to make your idea
work if we lock a few other things down first.

And when the browser window is made
small, the two start to overlap.

When the browser is wide,
the two totally separate.

510

Chapter 12
layout and positioning

Back to clearing up the overlap problem

Guess what, this time we are going to ride in on a
white horse with a solution, but don’t get used to it.

div id=“header”

The solution is called the clear property, and here’s how it works...

div id=“main”

div id=“sidebar”

Here’s what we’ve got now. The

“main” <div> is short enough that the
text
footer <div> is coming right up and
overlapping with the sidebar <div>.

div id=“footer”

This happens because the sidebar has been pulled out of the flow.

So, the browser just lays out the main and footer <div>s like it normally would, ignoring the sidebar (although remember that when the browser flows inline elements, it will respect the borders of the sidebar and wrap inline elements around it).

We can solve this problem with the CSS clear property. You can set this property on an element to request that as the element is being flowed onto the page, no floating content is allowed to be on the left, right, or both sides of the element. Let’s give it a try...

#footer {
background-color: #675c47;
color: #efe5d0;

Here we’re adding a property to
text-align: center;
the footer rule, which says that
padding: 15px;
no floating content is allowed on
margin: 10px;
the right of the footer.

font-size: 90%;
clear: right;

}

div id=“header”

Now when the browser places the
elements on the page, it looks to see if
div id=“main”

there is a floating element to the right
div id=“sidebar”

side of the footer, and if there is, it

Don’t even think
about putting a
text
moves the footer down until there is
floating element to the
nothing on its right. Now, no matter
right of me.

how wide you open the browser, the
footer will always be below the sidebar.

div id=“footer”

Now the footer is placed below
the sidebar so that there are no
floating elements to its right.

you are here �

511

more about columns and floats

Test drive

Go ahead and add the clear property to your

“starbuzz.css” file in the footer rule, and then

Now our footer problems are
reload “index.html”. You’ll see that when the
solved. The footer will always
screen is wide, the footer now stays below the
be below the sidebar, no matter
sidebar.

how narrow or wide the browser.

There are other improvements we could think
about making to this page, like having each
column come down to meet the footer. As
it is now, there is a gap either between the
main content and the footer (if the browser
window is set wide), or the sidebar and the
footer (if the browser is set to a normal width).

Unfortunately, it’s not easy to fix this, and
we’re not going to try to do that in this chapter.

Layout in CSS is an art, and no layout solution
is perfect. When done right, layout with CSS
gives you a better look for your Web page,
while still allowing the page to look reasonably
good in browsers that don’t have as much (or
any) support for CSS.

We will take a look at a few more ways to
layout your pages using CSS beyond using float.

There are many ways to do things in CSS, each
with their own strengths and weaknesses.

there are no

Dumb Questions

Q:

So why isn’t there just a two-

Q: Can I float to the center?

column property in CSS? Why is it so
format for structure and content that can
hard to get this stuff to work correctly?

be styled by CSS but should be viewable
on any device, even if the CSS isn’t used.

A: No, CSS only alows you to float an

A:

So, it’s real y no surprise that CSS isn’t the
element to the left or right. But if you think

Yes, we have a winner! You’ve
end-al -be-al of document presentation, and, about it, if you were to float to the center, asked the $64,000 question. But, more
if that’s what we wanted, we’d probably all
then the inline content under the floated
seriously, while it seems like CSS should
just be using Microsoft Word. But CSS does
element would have to be flowed around
have some way of specifying “give me two
give you some nice tools to create layouts
both sides of your element. While that might
columns, dammit!”, you have to keep in mind that are at ractive and usable, and does a be doable, it probably wouldn’t be very
the whole purpose of XHTML and CSS.

good job of graceful y degrading in less than readable or attractive.

Remember, XHTML is meant to be a
optimal viewing conditions.

512

Chapter 12

layout and positioning

Q:

margin won’t be col apsed with whatever is

Do margins col apse on floated
above it anymore. So you can easily end up

Q: Is it correct to think about floated
elements?

having dif erent margins on the sidebar and on
the main content if you don’t remember that
elements as elements that are ignored by
block elements, while inline elements know

A:

floated elements don’t collapse margins.

they are there?

No, they don’t, and it’s pret y easy to
see why. Unlike block elements that are flowed Q: Can I float an inline element?

on the page, floated elements are just, well,

A: Yes, that’s a good way of thinking
floating. In other words, the margins of floated
about it. Inline content nested inside a block
elements aren’t actual y touching the margins

A: Yes, you sure can. The best example element always flows around a floated of the elements in the normal flow, so they

– and a common one – is to float images.

element, observing the boundaries of the
can’t be collapsed.

Give it a try – float an image left or right in a
floated element, while block elements are

paragraph and you’l see your text flow around flowed onto the page as normal. The But this raises a good point, and identifies a
it. Don’t forget to add padding to give the
exception is when you set the clear property
common error in layouts. If you have a main
image a lit le room, and possibly a border. You on a block element, which causes a block content area and a sidebar, it is common to
can also float any other inline element you
element to move down until there are no
set a top margin on each. Then, if you float
like, but it’s not commonly done.

floating elements next to it on the right, left or
the sidebar, it still has a margin, and that
both sides, depending on the value of clear.

The only thing I don’t
like about this design is
that when I view the web page
on my PDA, it puts the sidebar
content above the main content,
so I have to scroll through it.

Right. That happens because of
the way we ordered the <div>s.

This is one of the disadvantages of the way we’ve
designed this page – because we need the sidebar to
be located just under the header and before the main
content, anyone using a browser with limited capabilities

(PDAs, mobile phones, screen readers, and so on) will
see the page in the order it is written, with the sidebar
first. However, most people would rather see your main
content before any kind of sidebar or navigation.

So, let’s look at another way of doing this, which goes
back to your idea of using float “left” on the main
content. While we’re exploring that, we’ll talk about
liquid versus frozen designs as well.

you are here �

513

the no css test

Look Ma, no CSS!

Exercise Want to know how your pages are going to look to your users under bad conditions (like on a browser that doesn’t support CSS)? Then open your “index.html” file and remove the <link> from the <head>, save, and reload the page in your browser.

Now you can see the real order things will be seen in (or
heard from a screen reader). Go ahead and give it a try. Just make sure you put it back when you’re done (after al , this is a chapter on CSS).

Here’s the Starbuzz page without

CSS. For the most part we’re in
good shape. It is still very readable,
although the Bean Machine does
come before the main content,
which probably isn’t what we want.

Righty tighty, lefty loosey

Let’s get the Starbuzz page switched over so that the main content is floating left. We’ll check out how that works, and then move on to make it really work. You’re going to see the mnemonic righty tighty, lefty loosey holds true in the CSS world too... well, for our sidebar, anyway. Here’s how we convert the page over... just a few simple steps.

514

Chapter 12
layout and positioning

Step One: start with the sidebar

We’re basically swapping the roles of the sidebar and the main content area. The content area is going to have a fixed width and float, while the sidebar is going to wrap around the content. We’re also going to use the same margin technique to keep the two visually separate. But before we start changing CSS, go to your “index.html” file and move the “sidebar” <div> down below the “main” <div> . After you’ve done that, here are the changes you need to make to the sidebar CSS rule:

#sidebar {
background: #efe5d0 url(images/background.gif) bottom right; font-size: 105%;

Because the sidebar is now going to flow
padding: 15px;
under the main content, we need to move the
margin: 0px 10px 10px 470px;
width: 280px;
large margin to the sidebar. The total width
float: right;
of the main content area is 470 pixels. (Go

}

ahead and compute that yourself in all that

We’re setting a fixed width on the main
free time you have. Compute it in the same
content <div>, so delete the sidebar width
way as you did for the sidebar. You should
property along with the float.

know that we’re going to set the width of
the main content area to 420 pixels.)

Step Two: take care of the main content

Now we need to float the main <div> . Here’s how to do it:

#main {
background: #efe5d0 url(images/background.gif) top left; font-size: 105%;

We’re changing the right margin from
padding: 15px;

330 pixels back to 10 pixels.

margin: 0px 10px 10px 10px;
width: 420px;

We need to set an explicit width because we’re going to
float: left;
float this element. Let’s use 420 pixels.

}

We’re going to float the main <div> to the left.

Step Three: take care of the footer

Now, we just need to adjust the footer to clear everything to the left, rather than the right.

#footer {
background-color: #675c47;
color: #efe5d0;
text-align: center;
padding: 15px;

Change the clear property to have
margin: 10px;
a value of left, rather than right.

font-size: 90%;

That way the footer will stay clear
clear: left;
of the main content area.

}

you are here �

515

contemplating a better solution

A quick test drive

We’ve already said there might be a few
problems with this method of floating
the content to the left. Do a quick test
drive before you move on just to see how
this is all working. Go ahead and make
the changes to your “starbuzz.css” file
and then reload “index.html” in your
browser. Get a good feel for how the page
performs when it is resized to narrow,
normal, and wide.

Actually, this looks pretty good, and we
have the <div>s in the right order now. But
it’s not great that the sidebar expands;
it looks a lot better fixed. Sidebars are
often used for navigation and they don’t
look very good when expanded.

When we float the sidebar <div> right,
then the design stays nice and tight,
allowing the content to expand, but if we
float the main content to the left, the
design feels too loose, allowing the sidebar
to expand.

brain
power

?

Design-wise, the first design worked better, while information-wise, the second works better (because of the placement of the <div>s). Is there a way we can have the best of both worlds: have the sidebar at a fixed width, but the main <div> still first in the XHTML?

What design tradeoffs could we make to get there?

516

Chapter 12

layout and positioning

Liquid and Frozen Designs

All the designs we’ve been playing with so far are called liquid layouts because they expand to fill whatever width we resize the browser to. These layouts are useful because, by expanding, they fill the space available and allow users to make good use of their screen space. Sometimes, however, it is more important to have your layout locked down so that when a user resizes the screen, your design still looks as it should. There are a couple of layouts that work like this, but let’s start with frozen layouts. Frozen layouts lock the elements down, frozen to the page, so they can’t move at all, and so we avoid a lot of issues that are caused by the window expanding. Let’s give a frozen layout a try.

Going from your current page to a frozen page only requires one addition to your XHTML, and one new rule in your CSS.

XHTML Changes

In your XHTML you’re going to add a new <div> element with the id

“allcontent”. Like its name suggests, this <div> is going to go around all the content in your page. So place the opening <div> tag before the header

<div> and the closing tag below the footer <div> .

Add a new <div> with the id of “allcontent”

<body>

<div id=”allcontent”>
around all the other elements in the <body>.

<div id=”header”>

... rest of the XHTML goes here ...

</div>

</div>

This <div> closes the footer <div>.

</body>

CSS Changes

Now we’re going to use this <div> to constrain the size of all the elements and content in the “allcontent” <div> to a fixed width of 800 pixels. Here’s the CSS rule to do that: We’re going to set the width of “allcontent” to 800 pixels. This will have the effect of constraining

#allcontent {
everything in it to fit within 800 pixels.

width: 800px;
padding-top: 5px;

While we’re at it, since this is the first time
padding-bottom: 5px;
we’re styling this <div>, let’s add some padding
background-color: #675c47;

}

and give it its own background color. You’ll see
this helps to tie the whole page together.

The outer “allcontent” <div> is always 800 pixels, even when the browser is resized, so we’ve effectively frozen the <div> to the page, along with everything inside it.

you are here �

517

frozen layouts

A frozen test drive

Go ahead and add this rule to the bottom of

“starbuzz.css”, and then reload “index.html”. Now
you can see why we call it a frozen layout. It doesn’t
move when the browser is resized.

Now the “allcontent” <div> is 800 pixels in width, no matter how you resize the browser. And, because all the other <div>s are inside “allcontent”, they will also fit into the 800 pixel space as well. So, the page is basically frozen to 800 pixels.

This certainly solves the problem of the sidebar
expanding and it looks pretty nice. It is a little
strange when the browser is very wide, though,
because of all the empty space on the right side.

But, we’re not done yet; we’ve got a
little room for improvement.

What’s the state bet ween liquid
and frozen? Jello, of course!

The frozen layout has some benefits, but it also just plain looks bad when you widen the browser. But we’ve got a fix,
and it’s a common design you’ll see on the Web. This design is between frozen and liquid, and it has a name to match:

Jello. Jello layouts lock down the width of the content area in the page, but center it in the browser. It’s actually easier to change the layout to a jello layout and let you play with it, than to explain how it behaves, so let’s just do it:

Rather than having fixed left and right

#allcontent {
margins on the “allcontent” <div>, we’re
width: 800px;
setting the margins to “auto”.

padding-top: 5px;
padding-bottom: 5px;
background-color: #675c47;
margin-left: auto;
margin-right: auto;

}

If you remember, when we talked about giving a content area a width of “auto”, the browser expanded the content area as much as it needed to. With “auto” margins, the browser figures out what the correct margins are, but also makes sure the left and right margins are the same, so that the content is centered.

518

Chapter 12

layout and positioning

Test driving with a tank of jello

Add the two margin properties to your “starbuzz.css” file, and then reload the page. Now play with the size of the browser. Pretty nice, huh?

Narrow.

Wide.

So if we want our content
in the correct order, we either
have to live with an expanding
sidebar or we have to use a jello
layout? Is there any other way to
do this?

With CSS, there are typically lots of ways to approach a layout, each with their own strengths and weaknesses. Actually, we’re just about to look at another common technique for creating a two-column layout that keeps the content in the correct order, and avoids some of the problems of the liquid layouts. But, as you’ll see, there are some tradeoffs.

With this new technique we’re not going to float elements at all. Instead we’re going to use a feature of CSS that allows you to precisely position elements on the page. It’s called absolute positioning. You can also use absolute positioning for some nice effects beyond just multi-column layouts, and we’ll look at an example of that, too.

To do all this, we’re going to step back to the original XHTML and CSS we started with in the beginning of this chapter. You can find a fresh copy of these files in the “chapter12/absolute” folder. Be sure and take another look at these files so you remember what they originally looked like. Recall that we’ve got a bunch of <div> s: one for the header, one for main, one for the footer, and also a sidebar. Also remember that in the original XHTML, the sidebar <div> is below the main content area, where we’d optimally like to have it.

you are here �

519

using absolute positioning

How absolute positioning works

Let’s start by getting an idea of what absolute
positioning does, and how it works. Here’s a little

The first thing we do is use the

CSS to position the sidebar <div> with absolute position property to specify that the
positioning. Don’t type this in just yet; right now we
element will be positioned absolutely.

just want you to get a feel for how this works:

#sidebar {
position: absolute;
top: 100px;

Next we set top and
right: 200px;
right properties.

What the CSS does
width: 280px;

Now let’s look at what this CSS does. When an

}

element is absolutely positioned, the first thing the

And we also give
browser does is remove it completely from the flow.

the <div> a width.

The browser then places the element in the position
indicated by the top and right properties (you can use bottom and left as well). In this case, the sidebar is going to be 100 pixels from the top of the
page, and 200 pixels from the right side of the page.

We’re also setting a width on the <div> , just like we did when it was floated.

The sidebar is
positioned 200
pixels from the
right of the page.

Because sidebar is now
absolutely positioned, it

And, the sidebar
div id=“header”

is removed from the flow
is positioned 100
and positioned according
pixels from the
div id=“sidebar”

to any top, left, right,
top of the page.

div id=“main”

or bottom properties
that are specified.

div id=“footer”

Because the sidebar is out of
the flow, the other elements
don’t even know it is there,
and they ignore it totally.

Elements that are in the flow don’t even wrap their
inline content around an absolutely positioned element.

They are totally oblivious to it being on the page.

520

Chapter 12

layout and positioning

Another example of absolute positioning

Let’s look at another example. Say we have another

Now we have a second <div>, p

<div>
ositioned
with the
absolutely, about 100 p
id “annoyingad”. We could position it like this:

ixels from the
left and 150 pixels from the top.

#annoyingad {
position: absolute;
top: 150px;
div id=“header”

left: 100px;
width: 400px;
div id=“sidebar”

}

div id=”main”

div id=“annoyingad”

The annoying ad is being positioned 100
pixels from the left, and 150 pixels
from the top. It’s also a bit wider than
the sidebar, at 400 pixels.

div id=“footer”

Just like with the sidebar, we’ve placed the annoying
ad <div> at a precise position on the page. Any elements underneath that are in the normal flow
of the page don’t have a clue about the absolutely
positioned elements layered overhead. This is a little
different from floating an element, because elements

Notice the annoyingad <div> is
that were in the flow adjusted their inline content
on top of the sidebar <div>.

to respect the boundaries of the floated element.

But absolutely positioned elements have no effect
whatsoever on the other elements.

The sidebar and annoyingad <div>s
are layered on the page, with the

Who’s on top?

annoyingad having a greater z-index
than the sidebar, so it’s on top.

Another interesting thing about absolutely
positioned elements is that you can layer them
on top of each other. But if you’ve got a few
absolutely positioned elements at the same
position in a page, how do you know the
layering? In other words, who’s on top?

div id=“header” div id=“sidebar”

Each positioned element has a property called a
div id=“annoyingad”

z-index that specifies its placement. You’ll see
div id=”main”

how to specify a z-index in just a few pages.

div id=“footer”

The header, main, and
footer <div>s are all
in the flow, and flat
on the page.

you are here �

521
more about the position property
there are no

Dumb Questions

Q: What is the position property Q: Are there position property Q: Do I have to use pixels for set to by default?

values other than static and
positioning?

absolute?

A: The default value for positioning

A: No – another common way to
is “static”. With static positioning

A: There are actualy four: static, position elements is using percentages.

the element is placed in the normal
absolute, fixed, and relative. You’ve

If you use percentages, the positions of
document flow and isn’t positioned by
already heard about static and absolute.

your elements may appear to change as
you – the browser decides where it

Fixed positioning places an element in
you change the width of your browser.

goes. You can use the float property to
a location that is relative to the browser

So, for example, if your browser is 800
take an element out of the flow, and you
window (rather than the page), so fixed
pixels wide, and your element’s left
can say it should float left or right, but
elements never move. You’l see an
position is set to 10%, then your element
the browser is stil ultimately deciding
example of fixed positioning in a few
wil be 80 pixels from the left of the
where it goes. Compare this to the
pages. Relative positioning takes an
browser window. But if your browser

“absolute” value for the position property. element and flows it on the page just is resized to 400 pixels wide, then the

With absolute positioning, you’re telling
like normal, but then offsets it before
width will be reduced to 10% of 400
the browser exactly where to position
displaying it on the page. Relative
pixels, or 40 pixels from the left of the
elements.

positioning is commonly used for more
browser window.

Q:

advanced positioning and special

Another common use for percentages is
ef ects. You’re going to see an example

Can I only position <div>s?

in specifying widths. If you don’t need
of that too.

specific widths for your elements or

A:

margins, then you can use percentages

You can absolutely position any

Q: Do I have to specify a width to make both your main content area element, block or inline. Just remember
for an absolutely positioned element
and your sidebars flexible in size. You’ll
that when an element is absolutely
just like the floated elements?

see this done a lot in two- and three-
positioned, it is removed from the normal
column layouts.

flow of the page.

A:

Q:

No, you don’t have to specify a

Q: Do I have to know how
width for absolutely positioned elements.

So, I can position an inline
to use z-indexes to use absolute

But if you don’t, by default, the block
element?

positioning?

element will take up the entire width
of the browser, minus any of set you

A:

specify from the left or right. This might

A:

Yes, you sure can. For instance,

No, z-indexes tend to be used
be exactly what you want, or it might not.

it’s common to position the <img>
most often for various advanced uses

So set the value of the width property if
element. You can position <em>s,
of CSS, especial y when Web page
you want to change this default behavior.

<span>s, and so on as well, but it isn’t
scripting is involved, so they’re a
common to do so.

little beyond the scope of this book.

But they are a part of how absolute
positioning works, so it’s good to know
about z-index (and in fact, you’l see a
case where knowing about z-index is
important in just a bit).

522

Chapter 12
layout and positioning

Using absolute positioning

We’re now going to create a two column Starbuzz page using techniques similar to those we used with the float version of the page; however, this time we’ll use absolute positioning. Here’s what we’re going to do:

1

First we’re going to make the sidebar <div> absolutely positioned. In fact, we’re going to position it in exactly the same place that we floated it to before.

2

Next, we’re going to give the main content another big margin so that the sidebar can sit on top of the margin space.

3

Finally, we’re going to give this a good testing and see how it compares to the float version.

Changing the Starbuzz CSS

Remember, we are going back
to the original versions of the

Our XHTML is all ready to go, and the sidebar
files, which you can find in the

<div> is right
where we want it (below the important main content). All we need

“chapter12/absolute” folder.

to do is make a few CSS changes and we’ll have a sidebar that is absolutely positioned. Open your “starbuzz.css” file and let’s make You can work out of the “absolute”

a few changes to the sidebar:

folder, or copy the files “index.html”

and “starbuzz.css” into the “starbuzz”

folder and work from there, like we did.

#sidebar {
background: #efe5d0 url(images/background.gif) bottom right; font-size: 105%;
padding: 15px;
margin: 0px 10px 10px 10px;
position: absolute;

Okay, now we’re going to specify that the sidebar is absolutely top: 128px;
positioned 128 pixels from the top, and 0 pixels from the right of the page. We also want the sidebar to have a width, so let’s right: 0px;
make it the same as the float version: 280 pixels.

width: 280px;

}

You’ll see where the “128”

0 pixels from the right
came from in a sec...

will make sure that the
sidebar sticks to the right
side of the browser.

you are here �

523

using margins with positioning

Now we just need to rework the main <div>

Actually, there’s not much reworking to be done. We’re just adding a margin like we did with the float version. So, change the right margin of the main <div> to be 330 pixels, like you did last time.

#main {
background: #efe5d0 url(images/background.gif) top left; font-size: 105%;
padding: 15px;
margin: 0px 330px 10px 10px;

}

We’re going to give the sidebar some space to be positioned over by giving the main <div> a big margin. This is really the same technique we used with the float. The only difference is the way the sidebar <div> is being placed over the margin.

Okay, all you need to do is make that change to your margin, and then save. But, before we take this for a test drive, let’s think about how this is going to work with the absolutely positioned sidebar.

We’re positioning the sidebar to be 128 pixels from
the top, and up against the right side of the page.

Keep in mind, the sidebar has 10 pixels of margin
on the right, so the background color will show
through that like before.

The main <div> is flowed

10 pixel top margin.

just below the header,
div id=“header”

108 pixels for the header. You can
so it will align with the
see this height set in the CSS.

top of the sidebar. Also,
it has a right margin
div id=“main”

div id=“sidebar”

10 pixel bottom margin.

that is the same size
as the sidebar, so all
text

The sidebar needs to be
its inline content will

128 pixels from the top
be to the left of the
because that’s exactly
sidebar. Remember that
how much room the
the flowed elements
header takes up, including
don’t know about the
div id=“footer”

margins.

absolutely positioned
elements at all, so
the inline content in
the flowed elements
doesn’t wrap around the

You might want to think about what happens to the
absolutely positioned
footer. Because flowed elements don’t know about
elements.

absolute elements, we can’t use “clear” anymore.

524

Chapter 12

layout and positioning

Time for the absolute test drive

Make sure you’ve saved the new CSS and then reload

“index.html” in your browser. Let’s check out the results:

As you resize the
browser, the sidebar

Wow, this looks amazingly
always sits 128 pixels
like the float version;
from the top, and sticks
however, you know that
to the right of the page.

the sidebar is being
positioned absolutely.

And the sidebar has a 10
pixel right margin, so it
has spacing between it and

The main content area has
the edge of the page.

a margin that is exactly
the width of the sidebar,
and the sidebar sits on top
of that space.

And we’ve still got a
nice gutter between
the two columns.

But we are now back to having a problem with the
footer. When the browser gets wide enough, the
absolutely positioned sidebar comes down over the top
of the footer. Unfortunately, we can’t fall back on the
clear property this time, because flowed elements
ignore the presence of absolutely positioned elements.

When the browser is wide, the
vertical space of the main
content area is reduced, and
the sidebar can come down over
the footer.

you are here �

525
overview of two column techiques

What can we do? Or, can’t you just tell me how
to do a t wo-column layout that doesn’t break?

Okay, you know that one of the big motivations behind CSS was to separate structure from style. Right? And CSS does a great job of allowing you to create XHTML documents that can be used in a lot of different browsers (even screen readers or text-only browsers) without having unnecessary style embedded into the XHTML. But this also means that CSS is not meant to be a full-blown page layout language. Rather, it gives you some interesting tools that you can use to arrange and position elements in XHTML documents. Depending on the environment the page is viewed in, your mileage may vary in terms of what the end result is. If you resize your browser to be ultra wide, well, then the layout may break.

So where does this leave you? In this chapter we’ve looked at several techniques for creating two-column layouts. None of them were perfect and, in fact, they all had various tradeoffs.

Let’s quickly review the various examples.

The Floating Layout

Ahh, how cute, remember your first two-column Starbuzz page? You used a float property along with a clear on the footer and life was good. The only problem is that this solution often results in putting your content in an order your users might not appreciate if they are using another kind of browser, like a screen reader that reads the content aloud to the user.

The Jello Layout

First we created a frozen layout by wrapping a fixed size <div> around all the content in the page, and then we made it jello by allowing the margins to expand with the “auto”

property value. This makes for a great looking layout, and lots of pages on the Web use this design. This also solved the problem of our content ordering. The disadvantage here is that the content doesn’t expand to fill the entire browser window (which many people don’t find to be a disadvantage at all).

The Absolute Layout

Finally, we were on a mission to have a liquid layout and yet have the content ordered like we wanted. So, we used absolute positioning and actually achieved our goal. But, there was a downside: since you can’t use the clear property with absolute elements, the footer creeps up under the sidebar when the browser is wide.

So are we done yet? Maybe. If one of these designs meets your needs, great, go with it. For instance, lots of people are very happy with jello layouts. But there is always more tweaking you can do to perfect your particular layout. For instance, take the absolute design. Can we fix the footer? Not really, but we can make a tradeoff. Your design might be fine if the footer only showed under the main content area. If that’s the case, then we can fix the footer problem. Let’s give that a quick try.

526

Chapter 12

layout and positioning

One tradeoff you can make to fix the footer

To try this solution, just give the footer the same right margin size as the main content area, like this:

#footer {
background-color: #675c47;
color: #efe5d0;
text-align: center;
padding: 15px;
margin: 10px 330px 10px 10px;
font-size: 90%;

}

If you save this and reload your page, you’ll see that the footer is now under the main content area only, and never creeps up under the sidebar. Is this optimal? No, but it’s also not bad. And, as we’ve said, doing CSS layout is a bit of an art. To do layout, you need to experiment, explore, and keep an eye on the layouts others are creating with CSS (you’ll find some references for good CSS hangouts at the end of the chapter).

This solution trades having the footer

So this is all great,
under just the main content for having a
but what am I supposed
footer under the entire page, to keep it
to do? Use a liquid or jello
from creeping up under the sidebar.

design? Use float or absolute
positioning?

In terms of whether you want your layout to be liquid or frozen or jello, that really is a matter of deciding what works best for your pages. For some pages, a fixed content area size with expandable margins works great, and in fact can be more readable on wide browsers. For other uses, you might want to use as much of the browser as you can. So, decide what works best for you.

Once you’ve decided, you still need to figure out which method you’re going to use to create your pages (float? absolute? some combination?). You’ve already learned the basics, so now it is time to start exploring, as there are many other approaches out there, and new ones being created every day. The techniques you’ve learned in this chapter are often used as the basis for more sophisticated designs.

You should know that, in general, using float is considered the most flexible solution for multi-column layouts. Just keep in mind, you may have to be careful in the order of your content, depending on the design.

you are here �

527

more absolute positioning

Holy beans! Starbuzz just won
the Roaster of the Year Award.

This is huge. Can we get it on the
page front and center? All our
customers need to see this. Top
priority, make it happen!

The award.

Well, we could just throw this as an image into any old
paragraph on the page, but the CEO really wants this to be
noticeable on the page. What if we could place the award
on the page like this?

Not only does that look great,
but it’s exactly what the

CEO wants. But how? Well,
you know all about absolute
positioning now, so why not
position the image on the
page using that? After all, by
using absolute positioning
you can place it anywhere on
the page you want, and since
it isn’t in the flow it won’t
affect any other element on
the page. Seems like an easy
addition to make to the page
without disrupting what’s
already there.

Let’s give it a try. Start by
adding a new <div> , just
below the header (the CEO
thinks this is pretty important, so it should be up high in the order of content). Here’s the <div>

The <div>

<div id=”award”>
contains the

<img src=”images/award.gif”

image of the
alt=”Roaster of the Year award” />
award.

</div>

528

Chapter 12

layout and positioning

Positioning the award

We want the award to sit just about in the middle of the page when the browser’s open to 800 pixels (the width of the image in the header, and a typical size for browser widths) and just overlapping the main content <div> .

So we’re going to use the top and left properties to position the award 30 pixels from the top, and 365 pixels from the left.

#award {

We’re using an absolute position for the
position: absolute;
award <div> that is 30 pixels from the
top: 30px;
top and 365 pixels from the left.

left: 365px;

}

Add this CSS to your “starbuzz.css” file, save, and reload the Web page.

You’ll see the award image appear like magic, right where we want it.

Make sure you resize the browser to see how the award displays.

A small glitch

On some browsers the sidebar will overlap and

Did you notice a small glitch when you were resizing the
occlude the awards image. Oh dear.

browser? Depending on your browser, you may have seen the
sidebar <div> overlap the awards image. What on earth is going on? Remember how each absolutely positioned element
has a z-index that describes the stacking behavior of the
elements? Some browsers will give the award element a lower z-index than the sidebar <div> by default. All you need to do to fix that is to specify the z-index for the award, and give it a number higher than the sidebar.

#award {
position: absolute;

Let’s give the award <div>
top: 30px;
a really high number to make
left: 365px;
sure it is always on top.

z-index: 99;

}

Go ahead and add the z-index property to your “starbuzz.css” file.

When you save and reload, you’ll see that now the award <div> is on top of the sidebar, and the overlap glitch is gone.

you are here �

529

discussing float and absolute positioning

Tonight’s talk: Float and Absolute discuss
who’s more appropriate for layout.

Float

Absolute

Absolute, have you noticed lots of people are
going with me to do their layouts?

Are you sure? I’m used on a lot of pages too,
you know.

Well, everyone knows I’m better for CSS layout.

I’m so much easier to use. Didn’t you see? All
you have to do is add one little float property to
your CSS in the right place, and bam! You’ve got
two columns.

Hmm, I seem to remember a width property
and a margin property to get things just right...

Details, details. My point is that, with me,
you don’t have to go around counting pixels
to figure out where your content’s going to
go – you can just float it and leave the rest
to me.

Now, wait a sec. We had to move the entire
sidebar to a different location in the XHTML
to get the float to work the first time. I don’t
call that “leaving the rest to you.” That’s a lot
of work. At least with me, it doesn’t matter
what order the content comes in; I’ll always do
the right thing.

Well, what about that footer issue? You’re always
going to overlap things in weird ways, aren’t
you? If readers aren’t careful, they’ll have big
chunks of their Web pages sitting right on top of
other content. At least I respect that handy clear
property.

Hey, you sit on top of elements too.

530

Chapter 12
layout and positioning

Float

Absolute

But the important part, the inline content,
flows around me, just like it should.

Sometimes people want to position elements
right on top of other elements, you know. And
with me, you can position elements anywhere
you want. None of this right and left crap like
with you. You don’t give people that many
options, really, if you think about it.

You’re missing the point. I’m more flexible and

I give people a great way to lay out their pages.

I’m sure I can do any layout you can.

Really? There’s no way you could have done
that cool thing with the award.

Hmmm...

Admit it! You’re actually not as flexible as I am.

Well, maybe I can’t do everything you can do,
but I think I’m a lot easier for people doing
basic layouts, which is mostly what people
want.

I dunno, I heard you’re kind of buggy in older
browsers. That would be frustrating for new

Web developers.

I used to have that reputation, but most
modern browsers are just fine with me now.

And, now that Web developers are figuring that
out, they’re going with me, like I said at the
beginning.

I don’t think you’ve seen the end of me; I’ve
got a lot of uses on Web pages.

I never said you didn’t. But check out all the
designs out there that use float.

Hey, don’t start thinking you’re perfect. You
might be good for Web layouts, but you’re not
exactly the state of art in graphic design.

Well, that’s not really the point, is it? Anyway,

I’ve got a float to clear, gotta run.

Clear this, Float.

you are here �

531

an absolute gotcha

One more thing you should know about
absolute positioning

So far, when you’ve used the left, right, top, and bottom properties to specify the position, these numbers have always been with respect to the edge of the page, right? Well, we need to refine that just a bit.

When you position an element, you’re specifying the position relative to the closest ancestor element that is also positioned. So, you’re probably saying, “What? I haven’t The “tv” <div> is
positioned anything except for the sidebar. How could there be an ancestor in my positioned relative

XHTML that is already positioned?” Believe it or not there is – the <html> element, to the sidebar <div>,
which the browser positions for you when it creates the page.

not to the page.

But, let’s take this one step further. Say you wanted to absolutely position another

<div> inside the sidebar.

Here’s a new <div> nested
inside the sidebar.

<div id=”sidebar”>

<div id=”tv”>
div id=“header”

<img src=”AsSeenOnTv.gif” alt=”As Seen on TV” /> div

</div>
id=“sidebar”

100 ixels
div id=“main”

p

100

<p class=”beanheading”>
div
pixels

... more XHTML here ...

id=“tv”

</p>

...

</div>
div id=“footer”

If we absolutely position the “tv” <div> , its closest positioned ancestor is the sidebar <div> . And so, the positioning will be relative to the edges of the
sidebar, not the page.

#tv {
position: absolute;
top: 100px;

If you’re positioning with respect to the <html>
left: 100px;
element, then the bottom property may not
width: 100px;
do what you’d expect. You’d think the “bottom”

}

would be the very bottom of the Web page
itself, but the <html> element actually defines
this as the bottom of the browser window. So,

Another thing to know... if you get caught in a
if you want to absolutely position an element
conversation about “closest ancestors that are
from the bottom of the page, rather than the browser
positioned” at your next cocktail party, just say
window, you need to place your element inside an element
the “nearest containing block that is positioned.”

that extends to the bottom of your page, and is positioned.

That’s the terminology the experts use.

One way to do this is to put your element into a relatively e’ll look at
positioned element at the bottom of the page. W
relative positioning later in the chapter.

532

Chapter 12

layout and positioning

Sharpen your pencil

Time to put all this knowledge about floating and positioning to a test!

Take a look at the Web page below. There are four elements with an id. Your job is to correctly match each of these elements with the CSS rules on the right, and fill in the correct id selector for each one.

Check your answers at the end of the chapter.

Fill in the selectors to
complete the CSS.

div id=“header”

div id=“navigation”

div id=“main”

img id=“photo”

p

_______________ {
margin-top: 140px;
margin-left: 20px;
width: 500px;

}

_______________ {
position: absolute;
top: 20px;
left: 550px;
width: 200px;

}

_______________ {
float: left;

}

_______________ {
position: absolute;
top: 20px;
left: 20px;
width: 500px;
height: 100px;

}

you are here �

533

we need fixed positioning

Hey, can we get a coupon on
the site and put it right in
customers’ faces so they can’t
miss it? I’d like to offer one free
coffee to everyone who clicks on
the coupon, for a limited time,
of course.

Just the words we’ve been
waiting for: “right in the
customer’s face”

Why? Because it’s going to give us the
opportunity to try a little fixed positioning.

What we’re going to do is put a coupon on
the page that always stays on the screen, even
if you scroll. Is this a great technique to make
your users happy? Probably not, but work
with us here... it is going to be a fun way to
play with fixed positioning.

534

Chapter 12

layout and positioning

How does fixed positioning work?

Compared to absolute positioning, fixed positioning is pretty Impress friends and coworkers by
straightforward. With fixed positioning, you specify the position of an referring to the browser window as
element just like you do with absolute positioning, but the position is the viewport. Try it, it works, and
an offset from the edge of the browser’s window rather than the page.

the W3C will nod approvingly.

The interesting effect this has is that once you’ve placed content with fixed positioning, it stays right where you put it, and doesn’t move, even if you scroll the page.

So, say you have a <div> with an id of “coupon”. You can position the <div> fixed to a spot 300 pixels from the top of the viewport, and 100 pixels from the left side, like this:

Here’s the id selector
for the coupon <div>.

We’re using fixed
positioning.

ixels

#coupon {

300 p
position: fixed;

100
pixels div id=“coupon”

top: 300px;
left: 100px;

}

Position the coupon 300 pixels
from the top, and 100 pixels
from the left. You can also use
right and bottom, just like with
absolute positioning.

Here’s where the element gets
positioned within the viewport.

Once you’ve got an element positioned, then comes the fun: scroll around... it doesn’t move. Resize the window... it doesn’t move. Pick up your monitor and shake it... it doesn’t move. Okay, just kidding on the last one. But, the point is, fixed position elements don’t move; they are there for good as long as the page is displayed.

Unfortunately, Internet Explorer

Now, we’re sure you’re already thinking of fun things to do with version 6 (and earlier) doesn’t
fixed positioning, but you’ve got a job to do. So let’s get that coupon support fixed positioning. So if
on the Starbuzz page.

you’re using Internet Explorer
you won’t be able to see the
coupon properly placed on the

Starbuzz Coffee Web page.

you are here �

535
adding a new div

Putting the coupon on the page

Now we’re going to get the Free Coffee Coupon on the page.

Let’s start by creating a <div> for the coupon to go into: Here’s the <div> with an id of “coupon”.

Inside we’ve got an image of the coupon, which you’ll
find in the “chapter12/starbuzz/images” folder.

<div id=”coupon”>

<a href=”freecoffee.html” title=”Click here to get your free coffee”>

<img src=”images/ticket.gif” alt=”Starbuzz coupon ticket” />

</a>

</div>

And we’ve wrapped the image in an <a> element so that users can click on the image to be taken to a page with a coupon they can print.

Go ahead and add this <div> at the bottom of your “index.html” file, just below the footer. Because we’re going to position it, the placement in the XHTML will only matter to browsers that don’t support positioning, and the coupon isn’t important enough to have at the top.

Now let’s write the CSS to position the coupon:

#coupon {
position: fixed;

We’re going to set the coupon to fixed positioning, 300
top: 300px;
pixels from the top of the viewport, and let’s put the
left: 0px;
left side right up against the edge of the viewport. So

}

we need to specify 0 pixels from the left.

#coupon img {
border: none;

We need to style the image and the links, too; otherwise,

}

we may have borders popping up on the image because it
is clickable. So, let’s set the border on the image to none,

#coupon a:link {
and do the same on both links and visited links.

border: none;

}

Remember that we have a rule in the CSS that says to turn off text-

#coupon a:visited {
decoration, and use a border to underline links, instead. Here, we’re border: none;
overriding that rule for the link in the coupon <div> and saying we

}

don’t want any border on the link. Go back and look at the original CSS
if you need to remind yourself of the other rules for the links.

536

Chapter 12

layout and positioning

Putting the coupon on the page

Add the new coupon rules to your “starbuzz.css” file,
save, and then reload the page. You may need to make
the browser smaller to be able to see that the coupon
stays put even when you scroll. Clicking on the coupon
should take you to the “freecoffee.html” page.

You know, this looks great, but it might just be even more
snazzy if the coupon was offset to the left, so it looks like it’s coming out of the side of the viewport. Now, we could get into our photo editing software and cut off the left
hand side of the image to create that effect. Or, we could just use a negative offset so that the left side of the image is positioned to the left of the edge of the viewport.

That’s right, you can do that.

Using a negative left property value

Specify a negative property value just like you do a positive one: just put a minus sign in front. Like this:

By specifying -90 pixels,
we’re telling the browser to

#coupon {
position the image 90 pixels
position: fixed;
to the left of the edge of
top: 300px;
the viewport.

left: -90px;

}

ixels

-90
pixels

300 p
div id=“coupon”

The browser will gladly position the
image to the left of the viewport
for you, and only the part of the
image that is still on the screen
will be viewable.

you are here �

537

test drive and comparison

A rather positive,
negative test drive

Make sure you’ve put in the negative left property
value, save, and reload the page. Doesn’t that look
slick? Congrats, you’ve just achieved your first CSS
special effect. Watch out George Lucas!

Just remember, using fixed
positioning to cover up your
content is not the most
user-friendly thing to do,
but it is FUN.

Can you believe how good this
site looks? I mean, look at where
it started compared to now. Okay,
but we’ve stil got our work cut
out for us. We stil need to build
the Bean Machine, so see you in a
couple of chapters.

WOW! What a difference!

538

Chapter 12

layout and positioning

Getting relative

We want to take the Starbuzz

Coffee bag and move it about

This is it, the last type of positioning: relative positioning. Truth 100 pixels to the right.

be told, it’s also the loneliest of the positions because you just won’t find a lot of people using it in their designs. But, new designs come along every day, so when you see relative
positioning, you’ll want to know how it works and what it does.

Unlike absolute and fixed positioning, an element that is
relatively positioned is still part of the flow of the page, but at the last moment, just before the element is displayed, the browser offsets its position. Let’s see how this works on the coffee bag in the Starbuzz Page. We’re going to take the coffee bag and offset it to the side, so those coffee beans that spilled out of the bag look like they’re spilling out of the page, too.

Now we could absolutely position the coffee bag, but if we did, we’d have to find a way for the space it’s taking up on the page to get reserved, since absolute positioning takes the document completely out of the flow.

That’s where relative positioning comes in. We can keep the element in the flow, have its space reserved, and then offset where it actually gets displayed. Let’s try it.

Here’s a new rule that selects the

Notice that images are
image. We’re using a descendant
inline elements, but that’s
selector here to select only images
okay. You can use any of
inside the beanheading.

the positioning techniques,
or even a float, on inline
elements too.

.beanheading img {
position: relative;
left: 120px;

With absolute p

}

ositioning, the
coffee bag moves, but since it is no
longer in the flow, the rest of the

Then we specify a position of relative,

So here we’re specifying that the
page moves up underneath.

and whatever offsets we want on the
image should be displayed 120
image. The offset is from the position
pixels from the left of where it
where it is placed in the flow.

sits in the flow of the document.

You can use right, top, and bottom
as well, when specifying offsets.

Add this rule to your CSS and then save and reload.

you are here �

539

playing with relative positioning

The test drive

After reloading the Starbuzz page, you should see the
coffee bag over to the right part of the sidebar. What
is interesting is that part of the image is actually
extending beyond the sidebar into the margin and off the edge of the page. How does that work? Well, as
you’ve seen, the browser first flows a relative element
onto the page, and only then does it offset where it
is displayed. So the element still takes up the same
spot on the page, it’s just drawn in a different location.

Relative is a little like static positioning, but with a
dash of absolute thrown in. But, unlike absolute,
relative positioning is specified just as an offset from
the element’s real location, not in absolute coordinates
from the nearest containing block.

So, does this improve the page? We’re not sure, but
it was fun. (You might want to remove the relative positioning before you show it to the CEO.)

Couldn’t we have done this
with padding or margins
somehow?

Not really.

No matter how you tweaked the padding
and margins you still can’t get an image
to be positioned outside of the box it’s
in. And why try to do it the hard way?

We achieved a better effect with two lines
of CSS. You can use relative positioning
to display an element well beyond the
element’s box in the flow, which you just
can’t do with padding or margins.

540

Chapter 12

layout and positioning

To three-columns and beyond...

While we’ve spent this chapter looking at two-column layouts, the real goal was to learn about the float and clear properties, along with the various forms of positioning that CSS offers. Now that you’ve got the basics down, you’re in a good position to think about three-column layouts, or any other layout you might desire. So, that’s it, the chapter’s over.

But, wait! Before we finish it off, let’s just think through how a three-column layout might work (and if you want to give it a try, just look in the “chapter12/threecolumn” folder).

And this <div> is

This <div> is
floated right.

floated left.

The content area
now has left and
right margins that
sit under the two

And the footer has
floated <div>s.

its clear property
set to “both”.

This design is built using techniques that you already understand. To explore beyond what you’ve done here, it really does help to see how others have used CSS to create interesting designs, and we encourage you to get out there and look around. Check out some of our favorite online resources for CSS design at: http://headfirstlabs.com/books/hfhtml/chapter12/cssdesign.html
you are here �

541

review of float and positioning

BULLET POINTS

n

Browsers place elements in a page using flow.

page. This has the same advantages as the
frozen layout, but is often more attractive.

n

Block elements flow from the top down, with a
linebreak between elements. By default, each n There are four values the position property block element takes up the entire width of the
can be set to: static, absolute, fixed, and
browser window.

relative.

n

Inline elements flow inside a block element
n

Static positioning is the default, and places an
from the top left to the bottom right. If more
element in the normal flow of the page.

than one line is needed, the browser creates
a new line, and expands the containing
n

Absolute positioning lets you place elements
block element vertically to contain the inline
anywhere in the page. By default, absolutely
elements.

positioned elements are placed relative to the
sides of the page.

n

The top and bottom adjacent margins of
two block elements in the normal page flow
n

If an absolutely positioned element is nested
collapse to the size of the larger margin, or to
within another positioned element, then its
the size of one margin if they are the same
position is relative to the containing element
size.

that is positioned.

n

The properties top, right, bottom, and left are

n

Floated elements are taken out of the normal
flow and placed to the left or right.

used to position elements for absolute, fixed,
and relative positioning.

n

Floated elements sit on top of block elements
and don’t affect their flow. However, the inline
n

Absolutely positioned elements can be layered
content respects the boundaries of a floated
on top of one another using the z-index
element and flows around it.

property. A larger z-index value indicates it
is higher in the stack (closer to you on the

n

The clear property is used to specify that no
screen).

floated elements can be on the left or right (or
both) of a block element. A block element with n Fixed position elements are always positioned clear set will move down until it is free of the
relative to the browser window and do not
block element on its side.

move when the page is scrolled. Other
content in the page scrolls underneath these

n

A floated element must have a specific width
elements.

set to a value other than auto.

n

Relatively positioned elements are first flowed

n

A liquid layout is one in which the content of
into the page as normal, and then offset by
the page expands to fit the page when you
the specified amount, leaving empty the space
expand the browser window.

where they would normally sit.

n

A frozen layout is one in which the width of
n

When using relative positioning, left, right, top,
the content is fixed and it doesn’t expand
and bottom refer to the amount of offset from
or shrink with the browser window. This has
the element’s position in the normal flow.

the advantage of providing more control over
your design, but at the cost of not using the
n

The same design can often be achieved using
browser width as efficiently.

floating elements or absolutely positioned
elements.

n

A jello layout is one in which the content
width is fixed, but the margins expand and
n

Float provides a flexible solution for multi-
shrink with the browser window. A jello layout
column layouts and allows elements to clear
usually places the content in the center of the
floated elements from their sides, something
that can’t be done with absolute positioning.

542

Chapter 12

layout and positioning

XHTMLcross

This has been a turbo-charged chapter, with lots to learn. Help it all sink in by doing this crossword. All the answers come from the chapter.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

Across

Down

5. State between liquid and frozen.

1. Another name for the browser window.

6. Type of positioning that is relative to the

2. Method browser uses to position static elements
viewport.

on the page.

7. When you place two inline elements next to each

3. Property that describes the layering behavior of
other, their margins don't ________.

positioned elements.

12. In general _____ is a better technique for

4. Property used to fix footer overlap problems.

column layouts because you can use clear.

8. With this positioning, you specify the position

13. Inline elements are flowed from the top
relative to the edges of the containing block.

______.

9. Block elements are flowed top to ______.

15. Special inline elements that get grouped

10. A positioning type that keeps elements in the
together into boxes as the page is laid out.

flow.

16. Absolute positioning is relative to the

11. When boxes are placed on top of each other,
positioned _____ block.

these collapse.

17. This kind of margin was used on the coupon for

12. Removes element from the flow, and sets it to
a special effect.

one side.

18. Usually used to identify an element that is

14. Inline content flows around ______ elements.

going to be positioned.

you are here �

543

exercise solutions
p

Exercise

Solutions
h1

BE the
p

Open your “lounge.html”

file and locate all the
block elements. Flow
p
each one on to the page
below. Just concentrate
on the block elements
nested directly inside the
p
body element. You can
also ignore the “float”

property in your CSS

Each block element
p
because you still don’t know what
in your “lounge.

html” file is flowed
from top to bottom,
p
with a linebreak in
between.

h2
p

These three elements
have nested block
elements in them.

div
ul
h2
p

We didn’t ask you
h3
div
to, but if you
p
went the extra
mile, here’s how
p
div
they get flowed.

h3
p
p
h3
p
p

544

Chapter 12

layout and positioning

Move the elixirs <div> back to its original place below the music recommendations, then save and reload the page. Where does the Exercise element get floated now? You should have seen the elixirs below the music Solutions recommendations.

The <div> is floated
to the right, just
below the music
recommendations, and
the remainder of the

XHTML is floated
around it (which is just
the footer).

Sharpen your pencil

Solution

What we want to do is set a right margin on the main content section so that it’s the same width as the sidebar. But how big is the sidebar? Well, we hope you aren’t already rusty since the last chapter. Here’s all the information you need to compute the width of the sidebar. And here’s the solution.

#sidebar {
background: #efe5d0 url(images/background.gif) bottom right; font-size: 105%;
padding: 15px;
margin: 0px 10px 10px 10px;
width: 280px;
float: right;

}

15 + 15 + 280 + 0 + 0 + 10 + 10 = 330
ea
left padding
right padding
content ar
left border
right border
right margin
left margin
you are here �

545

exercise solutions

Sharpen your pencil

Solution

Time to put all this knowledge about floating and positioning to a test!

Take a look at the Web page below. There are four elements with an id. Your job is to correctly match each of those elements with the CSS rules on the right, and fill in the correct id selector for each one.

Here’s the solution. Did you get them all correct?

Fill in the selectors to
div id=“header”

div id=“navigation”

complete the CSS.

div id=“main”

img id=“photo”

p

_______________ {

#main
margin-top: 140px;
margin-left: 20px;
width: 500px;

}

_______________ {

#navigation
position: absolute;
top: 20px;
left: 550px;
width: 200px;

}

_______________ {

#photo
float: left;

}

_______________ {

#header
position: absolute;
top: 20px;
left: 20px;
width: 500px;
height: 100px;

}

546

Chapter 12

layout and positioning

Solution

1

2

3

4

V

F

Z

C

I

L

-

L

5

6

J E

L

L O

F

I X E D

W

W

N

A

P

D

R

7

8

C O L

L A

P

S

E

9

10

11

B

R

B

X

R

M

12

13

F

L O A T

S

L

E

F

T

A

14

L

T

O

F

L

R

15

O

T E X T

L

L

A

G

16

A

O

U

C O N T A

I N I N G

T

M

T

A

I

N

17

N E

G A T

I

V E

S

E

E

18

I D

Across

Down

5. State between liquid and frozen. [jello]

1. Another name for the browser window.

6. Type of positioning that is relative to the

[viewport]

viewport. [fixed]

2. Method browser uses to position static elements

7. When you place two inline elements next to each
on the page. [flow]

other, their margins don't ________. [collapse]

3. Property that describes the layering behavior of

12. In general _____ is a better technique for
positioned elements. [z-index]

column layouts because you can use clear. [float]

4. Property used to fix footer overlap problems.

13. Inline elements are flowed from the top

[clear]

______. [left]

8. With this positioning, you specify the position

15. Special inline elements that get grouped
relative to the edges of the containing block.

together into boxes as the page is laid out. [text]

[absolute]

16. Absolute positioning is relative to the

9. Block elements are flowed top to ______.

positioned _____ block. [containing]

[bottom]

17. This kind of margin was used on the coupon for

10. A positioning type that keeps elements in the
a special effect. [negative]

flow. [relative]

18. Usually used to identify an element that is

11. When boxes are placed on top of each other,
going to be positioned. [id]

these collapse. [margins]

12. Removes element from the flow, and sets it to
one side. [float]

14. Inline content flows around ______ elements.

[floated]

you are here �

547

13 tables and more lists

Getting Tabular

If it walks like a table and talks like a table... There comes a time in life when we have to deal with the dreaded tabular data. Whether you need to create a page representing your company’s inventory over the last year or a catalog of your Beanie Babies collection (don’t worry, we won’t tell), you know you need to do it in XHTML; but how? Well, have we got a deal for you: order now and in a single chapter we’ll reveal the secrets that will allow you to put your very own data right inside XHTML tables. But there’s more: with every order we’ll throw in our exclusive guide to styling XHTML tables. And, if you act now, as a special bonus, we’ll throw in our guide to styling XHTML lists. Don’t hesitate, call now!

this is a new chapter

549

something new from tony

Hey guys, I just created this
little table of the cities in my journal.

I was going to put it on the Web site, but

I couldn’t find a good way to do it with
headings or blockquotes or paragraphs.

Can you help?

City

Date

Temperature Altitude Population Diner Rating Walla Walla, WA

June 15 75 1,204 ft 29, 686 4/5

Magic City, ID June 25 74 5,312 ft 50 3/5

Bountiful, UT July 10 91 4,226 ft 41, 173 4/5

Last Chance, CO July 23 102 4,780 ft 265 3/5

Consequenc

T
es, NM Augus
ruth or
t 9 93 4,242 ft 7, 289 5/5

Why, AZ August 18 104 860 ft 480 3/5

550

Chapter 13

tables and more lists

How do you make tables with XHTML?

Tony’s right; you really haven’t seen a good way of using XHTML to represent his table, at least not yet. While you might think there’s a way to use CSS and

<div> s to create tables, XHTML has a <table> element to take care of all your tabular needs. Before we dive into the <table> element, let’s first get an idea of what goes into a table:

And this row

We have columns...

has headings.

Diner

City

Date

Temp

Altitude

Population

Rating

And we

Walla Walla, WA

June 15th

75º

1,204 ft

29,686

4/5
have rows...

Magic City, ID

June 25th

74º

5,312 ft

50

3/5

Bountiful, UT

July 10th

91º

4,.226 ft

41,173

4/5

Last Chance, CO

July 23rd

102º

4,780 ft

265

3/5

Truth or

August 9th

93º

4,242 ft

7,289

5/5

Consequences,

NM

Why, AZ

August 18th

104º

860 ft

480

3/5

We call each piece of data a cell,
or sometimes just table data.

brain
power

?

If they put you in charge of XHTML, how would you design one or more elements that could be used to specify a table, including headings, rows, columns, and the actual table data?

you are here �

551
an xhtml table

How to create a table using XHTML

Before we pull out Tony’s site and start making changes, let’s get the table working like we want it in a separate XHTML file. We’ve started the table and already entered the headings and the first two rows of the table into an XHTML
file called “table.html” in the “chapter13/journal/” folder. Check it out:

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”

“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>

<html xmlns=“http://www.w3.org/1999/xhtml” lang=”en” xml:lang=”en”>

<head>

<meta http-equiv=“content-type” content=“text/html; charset=ISO-8859-1” />

<style type=“text/css”>

Just a small bit of CSS so we
td, th {border: 1px solid black;}

can see the structure of the

</style>
table in the browser. Don’t

<title> Testing Tony’s Travels</title> worry about this for now.

</head>

<body>

We use a <table> tag to start the table.

<table>

<tr>

Here’s the first row, which we start with a <tr>.

<th> City</th>

<th> Date</th>

Each <th> element is a table heading for a column.

<th> Temperature</th>

Notice that the table headings are listed one

<th> Altitude</th>
after each other. While these look like they

<th> Population</th>
might make up a column in the HTML, we are

Each <tr>

<th> Diner Rating</th>
actually defining the entire table headings row.

element forms </tr>

Look back at Tony’s list to see how his headings
a table row.

<tr>
map to these.

<td> Walla Walla, WA</td>

Here’s the start of the second row, which is

<td> June 15th</td>
for the city Walla Walla.

<td> 75</td>

<td> 1,204 ft</td>

Each <td> element holds one cell of the

<td> 29,686</td>
table, and each cell makes a separate column.

<td> 4/5</td>

</tr>

All these <td>s make up one row.

<tr>

<td> Magic City, ID</td>

<td> June 25th</td>

<td> 74</td>

And here’s the third

<td> 5,312 ft</td>
row. Again, the <td>

<td> 50</td>
elements each hold one

<td> 3/5</td>
piece of table data.

</tr>

</table>

</body>

</html>

552

Chapter 13

tables and more lists

What the browser creates

Let’s take a look at how the browser displays this XHTML table. We’ll warn you now: this isn’t going to be the best-looking table, but it will look like a table. We’ll worry about how it looks shortly; for now let’s make sure you’ve got the basics down.

Here’s how the browser
displays the table XHTML.

We’ve got three rows total,
including the headings.

Each <td> is in
its own cell.

And six columns, just
what we expected.

And each <th> is in a cell
as well. It looks like the
browser displays headings
in bold by default.

First type in the “Testing Tony’s Travels” XHTML from the previous page. Typing this in, while tedious, wil help get the structure of the <table>, <tr>, <th>, and Exercise

<td> tags in your head. When you finish, give it a quick test, and then add the remaining items from Tony’s table. Test that too.

you are here �

553

tables up close

Tables dissected

You’ve seen four elements used to create
a single table: <table>, <tr>, <th> and <td>.

Let’s take a closer look at each one to see
exactly what role it plays in the table.

The <table> tag is the tag that

The <th> element contains one cell in the heading
starts the whole thing off. When
of your table. It must be inside a table row.

you want a table, start here.

The </tr> tag ends

<th>Date</th>
a row of the table.

<table>

Diner

<tr>

City

Date

Temp

Altitude

Population

</tr>

Rating

<tr>

Walla Walla, WA

June 15th

75º

1,204 ft

29,686

4/5

</tr>

<tr>

Magic City, ID

June 25th

74º

5,312 ft

50

3/5

</tr>

<tr>

Bountiful, UT

July 10th

91º

4,226 ft

41,173

4/5

</tr>

<tr>

Last Chance, CO

July 23rd

102º

4,780 ft

265

3/5

</tr>

<tr>

Truth or

August 9th

93º

4,242 ft

7,289

5/5

</tr>

Consequences,

NM

<tr>

Why, AZ

August 18th

104º

860 ft

480

3/5

</tr>

Each <tr> element
specifies a table row.

</table>

So, all the table

<td>August 9th</td>
data that goes in a
row is nested inside
the <tr> element.

The </table> tag
ends the table.

The <td> element contains one data cell in
your table. It must be inside a table row.

554

Chapter 13
tables and more lists
there are no

Dumb Questions

Q:

Tables give you a way to

Why isn’t there a table

Q: My friend showed me a
column element? That seems pretty cool trick where he did al his page important.

layout right within a table. He didn’t
specify tabular data in
even have to use CSS!

A:

your HTML.

The designers of XHTML
decided to let you specify tables by

A: Go straight to CSS jail. Do
row, rather than by column. But notice not pass go; do not collect $200.

that by specifying each row’s <td>

Tables consist of data

Using tables for layout was commonly
elements, you are implicitly specifying done in the HTML era before CSS, each column anyway.

cells within rows.

when, frankly, there was no bet er way

Q:

to do complex layouts. However, it is

Columns are implicitly

What happens if I have
a poor way to do your layouts today.

a row that doesn’t have enough

Using tables for layout is notoriously
defined within the rows.

elements? In other words, I’ve got
hard to get right and difficult to
less things than the number of
maintain. Tell your friend that his
columns in the table?

technique is old school, and he needs
to get up to speed with the right way

The number of columns

A:

to do layout: CSS with XHTML.

The easiest way to deal with
in your table wil be the
that is to just leave the content of the

Q: Isn’t a table al about
data cel empty; in other words, you
presentation? What happened to
number of data cel s you
write <td></td>. If you leave out the
presentation versus structure?

data cell, then the table won’t line up
have in a row.

properly, so all the data cells have to
be there, even if they are empty.

A: Not really. With tables you are

Q:

specifying the relationships between

What if I want my table
truly tabular data. We’l use CSS to

In general, tables are
headings to be down the left side of alter the presentation of the table.

the table, instead of across the top;
not meant to be used for
can I do that?

presentation; that’s the

A: Yes, you certainly can. You
job of CSS.

just need to put your table heading
elements in each row instead of all
in the first row. If your <th> element
is the first item in each row, then the
first column will consist of all table
headings.

you are here �

555

testing you on tables

BE the Browser

On the left, you’ll find the XHTML
for a table. Your job is to play
like you’re the browser displaying
the table. After you’ve done the

<table><tr><th>Artist</th>
exercise, look at the end of

<th>Album</th></tr><tr>

<td>Enigma</td><td>Le Roi Est Mort,
the chapter to see if

Vive Le Roi!</td></tr> <tr><td>LTJ
you got it right.

Bukem</td>

<td>Progression Sessions 6</td>

</tr><tr>

<td>Timo Maas</td>

<td>Pictures</td></tr></table>

Here’s just the
table XHTML..

Argh! Someone needs to learn
how to format their XHTML.

Draw the table here.

556

Chapter 13
tables and more lists

Adding a caption and a summary

There are a couple of things you can do right off the bat to improve your tables, like adding a caption and a summary.

<table summary=” This table holds data about the The summary doesn’t
cities I visited on my travels. I’ve included the date
appear in the Web page

I was in each city, the temperature when I was there,
display. This is purely
and altitude and population of each city. I’ve also
for accessibility, and
included a rating of the diners where I had lunch, on a
acts as a bit of text
scale from 1 to 5. ”>
a screen reader may

<caption>
read aloud to a user to

The cities I visited on my
describe the table.

Segway’n USA travels

</caption>

<tr>

The caption, on the other hand, is displayed

<th> City</th>
in the browser. By default, most browsers

<th> Date</th>
display this above the table.

<th> Temperature</th>

<th> Altitude</th>

<th> Population</th>

<th> Diner Rating</th>

</tr>

If you don’t like the default location

<tr>
of the caption, you can use CSS to
reposition it (we’ll give that a try in a

<td>Walla Walla, WA</td>
sec), although some browsers don’t fully

<td> June 15th</td>
support repositioning the caption yet.

<td> 75</td>

<td> 1,204 ft</td>

<td> 29,686</td>

<td> 4/5</td>

</tr>

<tr>

<td> Magic City, ID</td>

<td> June 25th</td>

<td> 74</td>

<td> 5,312 ft</td>

<td> 50</td>

<td> 3/5</td>

</tr>

.

The rest of the table

.

rows go here.

.

</table>
you are here �

557

checking out the unstyled table

Test drive... and start thinking about style

Add the summary and caption to your table. Save and reload.

The caption is a

You won’t see the summary; it’s primarily
t the top of
the table. It’ll probabl
for screen readers to read aloud to the
y look
better on the bott
visually impaired to help provide more
om.

information about the table data.

We really need to add some padding

And a splash of orange to
to the table data cells, to make
match Tony’s site could really
them easier to read.

pull the whole thing together.

And the border lines are really “heavy” visually.

We could use much “lighter” borders in the
table cells, although it would be nice to have a
dark border around the whole table.

558

Chapter 13
tables and more lists

Before we start styling, let’s get the table
into Tony’s page

Before we start adding style to Tony’s new table, we should really get the table into his main page. Remember that Tony’s main page already has set a font-family, font-size, and a lot of other styles that our table is going to inherit. So without putting the table into his page we won’t really know what the table looks like.

Start by opening the “journal.html” in the “chapter13/journal” folder, locate the August 20th entry, and make the following changes. When you’ve finished, move on to the next page before reloading.

<h2>August 20, 2005</h2>

<p>

<img src=”images/segway2.jpg” alt=”Me and my Segway in New Mexico” />

</p>

<p>

Well, I made it 1200 miles already, and I passed through some interesting places on the way:

</p>

<ol>

<li>Walla Walla, WA</li>

This is the old list of

<li>Magic City, ID</li>
cities. Delete this

<li>Bountiful, UT</li>
because we’re replacing

<li>Last Chance, CO</li>
it with the table.

<li>Truth or Consequences, NM</li>

<li>Why, AZ</li>

</ol>

<table summary=”This table holds data about the cities I visited on my travels. I’ve included the date I was in each city, the temperature when I was there, and altitude and population of each city. I’ve also included a rating of the diners where I had lunch, on a scale from 1 to 5.”>

<caption>The cities I visited on my Segway’n USA travels</caption>

<tr>

<th>City</th>

<th>Date</th>

The new table goes here. Copying and pasting it from the

<th>Temperature</th>
previous file is the easiest way to get it here.

<th>Altitude</th>

<th>Population</th>

<th>Diner Rating</th>

</tr>

.

.

.

</table>
you are here �

559
tables and style

Now let’s style the table

Now we need to copy the table styles into “journal.css”. But, since we’re going to change them anyway, let’s just add new style instead. Add the new styles highlighted below at the bottom of the style sheet file.

body {
font-family: Verdana, Geneva, Arial, sans-serif;
font-size: small;

}

h1, h2 {
font-weight: normal;
color: #cc6600;

This is all the style that’s
border-bottom: thin dotted #888888;
currently in Tony’s Web page.

}

We added all this in Chapter 9.

h1 {
font-size: 170%;

We’re going to add the new style

}

for the tables below it.

h2 {
font-size: 130%;

}

blockquote {
font-style: italic;

}

First, we’ll style the table. We’re going to add a margin on table {
the left and right, and a thin, black border to the table.

margin-left: 20px;

And, we’re going to move that caption
margin-right: 20px;
to the bottom of the table.

border: thin solid black;
caption-side: bottom;

}

td, th {
border: thin dotted gray;

Let’s also change the border on the table data cells to be a much lighter, dotted border in gray.

padding: 5px;

}

And let’s add some padding to the data cells so there’s some space between the data content and the border.

caption {
font-style: italic;
padding-top: 8px;

This rule styles the caption. We’re changing the

}

font-style to italic and adding some top padding.

560

Chapter 13

tables and more lists

Taking the styled tables for a test drive

That’s a lot of changes at once. Make sure you save them, and you should validate as well. Then load “journal.html” into your browser.

The table looks quite
different now that you’ve
styled it. We’re also
inheriting a few styles that
were already in Tony’s journal.

All the fonts are now sans-serif
and a smaller size. We picked
that up from the previous styles
already in the file.

Now we’ve got a dark border
and dotted lines.

And we’ve got some margin on
the table and some padding in
each table cell.

Those dotted lines are looking
really busy and distracting
though. It doesn’t help that they
are duplicated between each pair
of table cells.

Remember, in browsers that don’t support the caption-side
property, the caption will still be at the top of the table.

you are here �

561

cells and the box model

Table cells look like they
just use the box model too...

they’ve got padding and a border.

Do they also have a margin?

Table cells do have padding and a border – just
like you’ve seen in the box model – but they
are a little different when it comes to margins.

The box model is a good way to think about table cells, but they do differ when it comes to margins. Let’s take a look at one of the cells in Tony’s table:

Here’s the content.

And here’s
the padding.

And here’s the border.

We call the space in between
the cells border-spacing.

So instead of a margin, we have a border-spacing property, which is defined over the entire table. In other words, you can’t set the “margin” of an individual table cell; rather, you set a common spacing around all cells.

562

Chapter 13

tables and more lists

Sharpen your pencil The double doted lines are giving Tony’s table a busy and distracting look. It would be much bet er, and wouldn’t detract from the table, if we could just have one border around each table cel . Can you think of a way to do that with styling given what you’ve just learned? Give it a try and check your answer in the back of the chapter.

Q: So border spacing is defined for Q: Wel, is there any way to have Q: The border-spacing doesn’t seem the entire table, while a margin can be
different border spacing on the vertical
to work in my browser.

set for an individual element?

than I have on the horizontal? That
seems useful.

A:

A: Are you using Internet Explorer?

Right. Table cel s don’t have

We’re sorry to report that IE version 6
margins; what they have is spacing around

A: You sure can. You can specify your doesn’t support border-spacing. And, we’re their borders, and this spacing is set for the
border spacing like this:

sorry we didn’t tel you sooner. But, hey,
entire table. You can’t control the border
border-spacing: 10px 30px;
you’re not going to forget that now, are you?

spacing of each table cel separately.

That sets ten pixels of horizontal border
space and thirty pixels of vertical border
space.

you are here �

563

dealing with table borders

Getting those borders to collaspe

There is another way to solve the border dilemma, besides the border-spacing property. You can use a CSS property called border-collapse to collapse the borders so that there is no border spacing at all. When you do this, your browser will ignore any border spacing you have set on the table. It will also combine two borders that are right next to each other into one border. This

“collapses” two borders into one.

Here’s how you can set the border-collapse property. Follow along and make this change in your “journal.css” file:

table {
margin-left: 20px;
margin-right: 20px;
border: thin solid black;
caption-side: bottom;

Add a border-collapse property
border-collapse: collapse;
and set its value to “collapse”.

}

Save the file and reload; then check out the
changes in the border.

Now you just have one single border
around all the table cells. Just what
we wanted, and don’t you agree the
table looks much cleaner now?

564

Chapter 13

tables and more lists

Sharpen your pencil

You’re becoming quite the pro at XHTML and CSS, so we don’t mind giving you a lit le more to play with in these exercises. How about this: we’d like to spruce this table up even a lit le more, starting with some text alignment issues. Let’s say we want the date, temperature, and diner rating to be center-aligned. And how about right alignment on the altitude and population? How would you do that?

Here’s a hint: create two classes, one for center-aligned and one for right-aligned. Then just use the text-align property in each. Final y, add the appropriate class to the correct <td> elements.

This may sound tough, but take it step by step; you already know everything you need to finish this one. And, of course, you can find the answer in the back of the chapter, but give yourself the time to solve it before you peek.

These are all centered.

And these are right aligned.

you are here �

565

coloring cells

How about some color?

You know Tony loves his signature color and there’s no
reason not to add some color to his table; not only will it look great, but we can actually improve the readability of the
table by adding some color. Just like for any other element, all you need to do is set the background-color property on a table cell to change its color (notice how everything
you’ve learned about XHTML and CSS is starting to come
together!). Here’s how you do that:

th {
background-color: #cc6600;

}

Add this new rule to your “journal.css” file and reload.

Here’s what you’ll see:

How about some color in the
table rows?

So far the color is looking pretty nice. So let’s take it to the next level. A common way to color tables is to give rows an alternating color, which allows you to more easily see each row without getting confused about which column goes
with which row. Check it out:

Difficult to do in CSS? Nope. Here’s how you can
do this. First define a new class; let’s call it “cellcolor”:

.cellcolor {
background-color: #fcba7a;

}

Now all you need to do is add this class attribute to each
row you’d like to color. So in this case, you find the <tr> opening tags for Magic City, Last Chance, and Why, and
add class=”cellcolor” to each one.

566

Chapter 13

tables and more lists

Your turn. Add the class “cel color” to your CSS in “journal.css”, and then, in your XHTML, add class=”cel color” to each of the <tr> Exercise
opening tags needed to make the rows alternating colors. Check your answers before moving on.

Did we mention that Tony made an

Tess
interesting discovery in Truth or

Consequences, New Mexico?

It’s fair to say Tony found something interesting
about Truth or Consequences, New Mexico; in
fact, he found her so interesting that after going to Arizona, he turned around and came right back.

We’re glad for Tony, but he’s really given us a
conundrum with the table. While we could just
add a new row for Truth or Consequences, we’d
really like to do it in a more elegant way. What are
we talking about? Turn the page to find out.

you are here �

567

using table spans

City

Date

Temperature Altitude Population Diner Rating Walla Walla, WA

June 15 75 1,204 ft 29, 686 4/5

Magic City, ID June 25 74 5,312 ft 50 3/5

Bountiful, UT July 10 91 4,226 ft 41, 173 4/5

Last Chance, CO July 23 102 4,780 ft 265 3/5

August 9 93

5/5

Truth or

Consequences, NM

4,242 ft 7, 289

August 27 98

4/5

Why, AZ August 18 104 860 ft 480 3/5

Another look at Tony’s table

Based on his return trip to New Mexico, Tony’s added a new entry for August 27th, just below the original Truth or Consequences entry. He’s also reused a couple of cells where the information didn’t change (a great technique for reducing the amount of information in a table). You can see that when he added the new row, all he needed to do was list the things that were different the second time around (the date, the temperature, and that he revisited the diner).

Diner

City

Date

Temp

Altitude

Population

Rating

Walla Walla, WA

June 15th

75º

1,204 ft

29,686

4/5

Magic City, ID

June 25th

74º

5,312 ft

50

3/5

Here are both

Bountiful, UT

July 10th

91º

4,226 ft

41,173

4/5

Tony’s visits

Last Chance, CO

July 23rd

102º

4,780 ft

265

3/5
to Truth or

Consequences.

Truth or

August 9th

93º

4,242 ft

7,289

5/5

Consequences,

NM

August 27th

98º

4/5

Why, AZ

August 18th

104º

860 ft

480

3/5

These table data cells

But where does this leave you with XHTML? It seems like you’d have to add a span TWO rows now.

entirely new row and just duplicate the city, altitude and population, right? Well, not so fast. We have the technology... using XHTML tables, you can have cells span more than one row (or more than one column). Let’s see how this works...

568

Chapter 13
tables and more lists

How to tell cells to span more than one row

What does it mean for a cell to span more than one row? Let’s look at the entries for Truth or Consequences, NM in Tony’s table again. The data cells for city, altitude, and population span two rows, not one, while the date, temp, and diner rating span one row, which is the normal, default behavior for data cells.

Diner

City

Date

Temp

Altitude

Population

Rating

Walla Walla, WA

June 15th

75º

1,204 ft

29,686

4/5

Magic City, ID

June 25th

74º

5,312 ft

50

3/5

Bountiful, UT

July 10th

91º

4,226 ft

41,173

4/5

Last Chance, CO

July 23rd

102º

4,780 ft

265

3/5

Truth or

August 9th

93º

4,242 ft

7,289

5/5

Consequences,

NM

August 27th

98º

4/5

Why, AZ

August 18th

104º

860 ft

480

3/5

While the date, temp,

These cells span two rows.

and diner rating cells
take up just one.

So, how do you do that in XHTML? It’s easier than you might think: you use the rowspan attribute to specify how many rows a table data cell should take up, and then remove the corresponding table data elements from the other rows that the cell spans over. Have a look – it’s easier to see than describe: Here are the two table

<tr>

<td rowspan=”2”>Truth or Consequences, NM</td> rows that have the New

<td class=”center”>August 9th</td>

Mexico data.

<td class=”center”>93</td>

<td rowspan=”2” class=”right”>4,242 ft</td> For the data cells that don’t

<td rowspan=”2” class=”right”>7,289</td> change on the second visi

<td class=”center”>5/5</td>
t (city,

</tr>

The city is not
altitude, and population) we add

<tr>
needed because
a rowspan attribute indicating
of the rowspan.

the table data spans t

wo rows.

<td class=”center”>August 27th</td>

<td class=”center”>98</td>

Then in the second row we

Same with
specify just the columns we need

altitude and

(date, temp, and a new rating).

<td class=”center”>4/5</td>
population.

</tr>
you are here �

569

testing your table knowledge

Just to make sure you’ve got this down, draw an arrow
from each <td> element to its corresponding cel in the table. Check your answers before moving on.

<tr>

<td rowspan=”2”>Truth or Consequences, NM</td>

<td class=”center”>August 9th</td>

<td class=”center”>93</td>

<td rowspan=”2” class=”right”>4,242 ft</td>

<td rowspan=”2” class=”right”>7,289</td>

<td class=”center”>5/5</td>

</tr>

<tr>

<td class=”center”>August 27th</td>

<td class=”center”>98</td>

<td class=”center”>4/5</td>

Diner

</tr>

City

Date

Temp

Altitude

Population

Rating

Walla Walla, WA

June 15th

75º

1,204 ft

29,686

4/5

Magic City, ID

June 25th

74º

5,312 ft

50

3/5

Bountiful, UT

July 10th

91º

4,226 ft

41,173

4/5

Last Chance, CO

July 23rd

102º

4,780 ft

265

3/5

Truth or

August 9th

93º

4,242 ft

7,289

5/5

Consequences,

NM

August 27th

98º

4/5

Why, AZ

August 18th

104º

860 ft

480

3/5

570

Chapter 13

tables and more lists

The new and improved table

Make the changes to the table
in “journal.html” and give it a test
run. Take a look at the table. Think
about exactly what you’re doing to
the table: you’re using XHTML to
specify that certain cells should take
up more than one row, and to do
that, you’re removing the <td> s
they’re displacing.

Now we’ve got a great-looking
table that doesn’t have any
redundant information in it.

Q: You said you can have table data Q: Can I have a colspan and Q: Do you realy think these
span columns too?

rowspan in the same <td>?

rowspans look better?

A: You sure can. Just add a colspan A: You sure can. Just make sure A: Wel they certainly reduce the
at ribute to your <td> element and specify
you adjust the other <td>s in the table to
amount of information in the table, which is
the number of columns. Unlike the rowspan,
account for both the row and column spans.

usual y a good thing. And, if you look at a
when you span columns, you remove table

In other words, you’l need to remove the
few tables out there in the real world you’ll
data elements that are in the same row
corresponding number of <td>s from the
find that rowspans and colspans are quite

(since you are spanning columns, not rows).

same row, and from the column.

common, so it’s great to be able to do them
in XHTML. But if you liked the table bet er
before, feel free to change your XHTML and
go back to the previous version.

you are here �

571

we need a nested table

Four out of five
stars? I know my diners
and that was a solid five
star rating! You better
change that in the table.

Trouble in paradise?

It looks like we’ve got a disagreement on the diner rating for August 27th, and while we could ask Tony and Tess to come to a consensus, why should we? We’ve got tables and we should be able to get another rating in there. But how? We don’t really want to add yet another entry just for Tess’ review. Hmmm... why don’t we do it like this?

Diner

City

Date

Temp

Altitude

Population

Rating

Walla Walla, WA

June 15th

75º

1,204 ft

29,686

4/5

Magic City, ID

June 25th

74º

5,312 ft

50

3/5

Bountiful, UT

July 10th

91º

4,226 ft

41,173

4/5

Last Chance, CO

July 23rd

102º

4,780 ft

265

3/5

Truth or

August 9th

93º

4,242 ft

7,289

5/5

Consequences,

NM

August 27th

98º

Tess

5/5

Tony

4/5

Why, AZ

August 18th

104º

860 ft

480

3/5

Why not put both their ratings
in the table? That way we get
more accurate information.

572

Chapter 13

tables and more lists

Hold on. . that looks like
a table within a table.

That’s because it is. But, nested tables in

XHTML are straightforward. All you need
to do is put another <table> element
inside a <td> . How do you do that? You
create a simple table to represent both

Tony’s and Tess’ ratings together, and when
you have that working, put it inside the
table cell that now holds Tony’s 4/5 rating.

Let’s give it a try...

<tr>

<td rowspan=”2”>Truth or Consequences, NM</td>

<td class=”center”>August 9th</td>

<td class=”center”>93</td>

<td rowspan=”2” class=”right”>4,242 ft</td>

<td rowspan=”2” class=”right”>7,289</td>

<td class=”center”>5/5</td>

</tr>

<tr>

<td class=”center”>August 27th</td>

<td class=”center”>98</td>

<td>

4/5

<table>

First delete the old rating

<tr>
that represented Tony’s rating...

<th>Tess</th>

<td>5/5</td>

</tr>

<tr>

... and put a table in its place. This table

<th>Tony</th>
holds two diner ratings: one for Tess and

<td>4/5</td>
one for Tony. We’re using table headings for

</tr>
their names, and data cells for their ratings.

</table>

</td>

</tr>
you are here �

573

testing and improvements

Test driving the nested table

Go ahead and type in the new table. Tables are easy to mistype, so make sure you validate and then reload your page. You
should see the new, nested table.

Wow, looking nice.

Only that background
really is a bit much
for a nested table.

Let’s keep the names
bold, but take off
the background color.

574

Chapter 13

tables and more lists
brain

Barbell

It’s time to fall back on all that training you’ve done. What you need to do is change the table heading background color for just Tony and Tess, and do it without changing the background of the main table headings. How? You need to find a selector that selects only the nested table headings.

We want to change the background color of
the nested table headers to white.

{
background-color: white;

Determine the
selector to select

}

only the nested
table heading
elements.

Stop! Don’t turn
the page until you
do this exercise.

you are here �

575

how to override nested styles

Overriding the CSS for the nested
table headings

You can target just the <th> elements in the nested table using a descendant selector. Add a new rule to your CSS that uses the “table table th” selector to change the background color of Q: I used a class to solve the
the nested table headers to white:

Brain Barbel . I created a class cal ed

“nestedtable” and assigned each table
table table th {
heading to it. Then I created a rule like
background-color: white;
this:

}

Now save the changes to your “journal.css” file and reload.

.nestedtable {
background-color: white;

}

Is that an okay solution too?

A: There are lots of diferent ways to
solve problems using CSS, and certainly
your solution is an ef ective and perfectly
valid way to use CSS. We’l just point out
that by using the descendant selector
instead, we didn’t have to make any
changes to our XHTML. What if Tony and

Tess keep adding reviews for diners?

Then for every review, you’d have to
make sure and add the class to each <th>.

With our solution, the styling happens
automatically.

brain
power

?

You want Tony and Tess to
have different background
colors on their table rows;
say, blue and pink. Can
you think of several ways
to do that?

Now the <th> in the

But notice it still has the bold
nested table has a
font weight since we didn’t
white background.

override that property.

576

Chapter 13

tables and more lists

Giving Tony’s site the final polish

Tony’s page is really looking nice, but there’s one more area we haven’t spent any time styling yet: the list that contains the set of items he was preparing for his trip. You’ll find this list in his June 2nd entry; check it out below:

.

We’re looking at just the XHTML

.

snippet from the June 2nd entry.

.

<h2> June 2, 2005</h2>

<p>

<img src=”images/segway1.jpg”

alt=”The first day of the trip” />

</p>

Here’s the bottom of Tony’s journal,

<p>

“journal.html”. Remember his packing

My first day of the trip! I can’t
list in his first journal entry?

believe I finally got everything
packed and ready to go. Because

I’m on a Segway, I wasn’t able
to bring a whole lot with me:

</p>

<ul>

<li> cellphone</li>

<li> iPod</li>

<li> digital camera</li>

<li> a protein bar</li>

</ul>

<p>

Just the essentials. As Lao Tzu
would have said, <q> A journey of
a thousand miles begins with
one Segway. </q>

</p>

</body>

</html>

Here’s what the list looks like now.

you are here �

577

back to styling lists

Giving the list some style

You’re probably figuring out that once you know the basic CSS font, text, color, and other properties, you can style just about anything. The same is true for lists; in fact, there are only a couple of properties that are specific to lists. The main list property is called list-style-type and it allows you to control the bullets (or “markers”, as they are called) used in your lists. Here are a few ways you can do that:

Here we’re setting the style on the <li> element. You can also set it on the <ul> element, and it will be inherited by the <li> elements.

li {

Disc is the default
list-style-type: disc; marker type.

}

li {
list-style-type: circle;

}

The circle property value gives
you a simple circle marker.

li {
list-style-type: square;

}

And square gives you a
square marker.

li {
list-style-type: none;

}

A value of none
removes the marker
altogether.

578

Chapter 13

tables and more lists

What if you want a custom marker?

Do you really think Tony would want anything less than his
own custom marker? Well, luckily CSS has a property called
list-style-image that lets you set an image to be the marker for a list. Let’s give it a try on Tony’s list:

Here’s the list-style-image property,
which we’re setting to a URL.

The image “backpack.gif” is a
li {

small version of this backpack.

list-style-image: url(images/backpack.gif);
padding-top: 5px;

Seems fitting doesn’t it? And
margin-left: 20px;
in Tony’s signature color, too.

}

We’re adding some margin to add
space on the left of the list items,
and also a little top padding to give
each list item a bit of headroom.

And, the final test drive...

This is it: your last change to Tony’s
site. Add the rule for the list item to your

CSS and then reload.

Here’s the list with the marker
replaced with an image and some
extra margin and padding spacing.

you are here �

579

some finer points about styling lists
there are no

Dumb Questions

Q: What about ordered lists? What Q: How can I control the text wrap on Q: Are you sure that’s right? That can I do to change their style?

lists? In other words, how can I control
seems backwards.

whether text wraps underneath the

A:

marker or just underneath the text?

You style ordered and unordered

A: Yes, and here’s what inside and
lists in the same way. Of course, an ordered
outside really mean: if you set your line-
list has a sequence of numbers or let ers

A: There’s a property called list-style- style-position to “inside” then the marker is for markers, not bul ets. Using CSS you can
position. If you set this property to “inside”

inside your list item and so text wil wrap
control whether an ordered lists’ markers
then your text wil wrap under the marker.

under it. If you set it to “outside”, then the
are decimal numbers, roman numerals,

If you set it to “outside” then it wil wrap just
marker is outside your list item and so text
or alphabetic let ers (like a, b, c) with the
under the text above it.

will just wrap under itself. And, by “inside
list-style-type property. Common values are
your item” we mean inside the border of the
decimal, upper-alpha, lower-alpha, upper-
list item’s box.

roman, and lower-roman. Consult a CSS
reference for more options (there are many).

Wow, who would have
known we could take my site
this far when we started?

We’re going to get Tess a Segway of
her own so she can go with me on the
rest of my Segway’n USA trip. See
ya somewhere... and we’ll BOTH be
updating the Web page. Thanks
for everything!

580

Chapter 13

tables and more lists

BULLET POINTS

n

XHTML tables are used to structure tabular

n

You can change the alignment of the data in
data.

your table cells with the text-align and vertical-
align CSS properties.

n

Use the HTML table elements, <table>, <tr>,

<th>, and <td> together to create a table.

n

You can add color to your tables with the
background-color property. Background color

n

The <table> element defines and surrounds
the entire table.

can be added to the entire table, to each row,
or to a single data cell.

n

Tables are defined in rows, using the <tr>
element.

n

If you have no data for a data cell, put no
content into the <td> element. You need to
use a <td>...</td> element to maintain the

n

Each row contains one or more data cells,
defined with the <td> element.

alignment of the table, however.

n

If your data cell needs to span multiple rows or

n

Use the <th> element for data cells that are
row or column headings.

columns, you can use the rowspan or colspan
attributes of the <td> element.

n

Tables are laid out in a grid. Each row
corresponds to a <tr>...</tr> row in your
n

You can nest tables within tables by placing

HTML, and each column corresponds to the
the <table> element and all its content inside

<td>...</td> content within the rows.

a data cell.

n

Tables should be used for tabular data, not for

n

You can provide additional information about
your tables with the table summary attribute,
laying out your pages. Use CSS positioning
and the <caption> element.

to create multi-column page layouts as we
described in Chapter 12.

n

Table data cells can have padding, borders,
and border spacing, which is the space
n

Lists can be styled with CSS just like
between cells.

any other element. There are a few CSS
properties specific to lists, such as list-style-

n

Just like you can control the padding, borders,
type and list-style-image.

and margins of elements, you can control the
padding, borders, and border spacing of table

n
list-style-type allows you to change the type of
cells with CSS.

the marker used in your list.

n
list-style-image allows you to specify an image

n

The border-collapse property is a special CSS
property for tables that allows you to combine
for your list marker.

cell borders into one border for a cleaner look.

you are here �

581

some left brain action

XHTMLcross

That crossword looks a bit like a table, doesn’t it? Give your left brain a workout and solve this crossword. All the words are from this chapter.

582

Chapter 13

tables and more lists

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”

“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” lang=”en” xml:lang=”en”>

<head>

<meta http-equiv=“Content-Type” content=” text/html; charset=ISO-8859-1” /> Exercise

<style type=”text/css”>
td, th {border: 1px solid black;}

Solutions

</style>

<title> Testing Tony’s Table</title>

</head>

First type in the

<body>

“Testing Tony’s Table”

<table>

XHTML. Typing this

<tr>

<th> City</th>
in, while tedious,

<th> Date</th>
will help get the

<th> Temperature</th>
structure of the

<th> Altitude</th>

<th> Population</th>

<table>, <tr>, <th>,

<th> Diner Rating</th>
and <td> elements in

</tr>
your head. When you

<tr>

<td>Walla Walla, WA</td>
finish, give it a quick

<td> June 15th</td>
test, and then add

<td> 75</td>
the remaining items

<td> 1,204 ft</td>

<td> 29,686</td>
from Tony’s table.

<td> 4/5</td>

Test that too.

</tr>

<tr>

<td> Magic City, ID</td>

<td> June 25th</td>

<td> 74</td>

<td> 5,312 ft</td>

<td> 50</td>

<td> 3/5</td>

</tr>

<tr>

<td>Bountiful, UT</td>

<td>July 10th</td>

<td>91</td>

<td>4,226 ft</td>

<td>41,173</td>

<td>4/5</td>

</tr>

<tr>

<td>Last Chance, CO</td>

<td>July 23rd</td>

<td>102</td>

<td>4,780 ft</td>

<td>265</td>

<td>3/5</td>

</tr>

<tr>

<td>Truth or Consequences, NM</td>

<td>August 9th</td>
you are here �

583

exercise solutions

<td>93</td>

<td>4,242 ft</td>

<td>7,289</td>

<td>5/5</td>

</tr>

Exercise

<tr>

<td>Why, AZ</td>

Solutions

<td>August 18th</td>

<td>104</td>

<td>860 ft</td>

<td>480</td>

<td>3/5</td>

</tr>

</table>

</body>

</html>

584

Chapter 13

tables and more lists

<td>93</td>

<td>4,242 ft</td>

BE the Browser

<td>7,289</td>

<td>5/5</td>

On the left, you’ll find the

</tr>

<tr>

XHTML for a table. Your

<td>Why, AZ</td>
job is to play like you’re

<td>August 18th</td>

<td>104</td>
the browser displaying the

<td>860 ft</td>

<table>
table. Here’s the solution.

<td>480</td>

<td>3/5</td>

<tr>

</tr>

<th>Artist</th>

</table>

<th>Album</th>

</body>

</html>

</tr>

<tr>

<td>Enigma</td>

<td>Le Roi Est Mort, Vive Le Roi!</td>

</tr>

<tr>

<td>LTJ Bukem</td>

<td>Progression Sessions 6</td>

</tr>

<tr>

<td>Timo Maas</td>

<td>Pictures</td>

</tr>

</table>
you are here �

585

exercise solutions

Sharpen your pencil

The double dot ed lines are giving Tony’s table a busy and distracting look.

It would be much bet er, and wouldn’t detract from the table, if we could Solution just have one border around each table cel. Can you think of a way to do that with styling given that you’ve just learned? You can set the border-spacing property to 0 to remove the space between the borders.

We could use border-spacing to set
spacing to 0; then the two lines
would be right next to each other.

table {
margin-left: 20px;
margin-right: 20px;
border: thin solid black;
caption-side: bottom;
border-spacing: 0px;

}

Better, but we have still t wo lines and
they’re right up against each other, so we
have a double thick dotted border. We’d
rather it just be ONE border bet ween the
cells. Wouldn’t we?

586

Chapter 13

tables and more lists

Sharpen your pencil

.center {

Here are the two classes,

Solution
text-align: center;
one for center and one

}

for right alignment.

.right {
text-align: right;

}

<table summary=”This table holds data about the cities I visited on my travels. I’ve included the date I was in each city, the temperature when I was there, and altitude and population of each city. I’ve also included a rating of the diners where I had lunch, on a scale from 1 to 5.”>

<caption>The cities I visited on my Segway’n USA travels</caption>

<tr>

<th>City</th>

<th>Date</th>

<th>Temperature</th>

<th>Altitude</th>

<th>Population</th>

<th>Diner Rating</th>

</tr>

<tr>

<td>Walla Walla, WA</td>

<td class=”center”>June 15th</td>

<td class=”center”>75</td>

And here you just add

<td class=”right”>1,204 ft</td>

<td class=”right”>29,686</td>
each <td> to the

<td class=”center”>4/5</td>
appropriate class!

</tr>

<tr>

<td>Magic City, ID</td>

<td class=”center”>June 25th</td>

<td class=”center”>74</td>

<td class=”right”>5,312 ft</td>

<td class=”right”>50</td>

<td class=”center”>3/5</td>

</tr>

.

.

.

</table>

To create alternating colors in the Magic City, Last Chance, and Why table rows, you just add the class=”cel color” at ribute to the Exercise <tr> opening tag in these rows, like this:

Solution

<tr class=”cellcolor”>

<td>Magic City, ID</td>

...

</tr>
you are here �

587

exercise solutions

Exercise

Solutions

Just to make sure you’ve got this down, draw an arrow
from each <td> element to its corresponding cel in the table. Here are the answers.

<tr>

<td rowspan=”2”>Truth or Consequences, NM</td>

<td class=”center”>August 9th</td>

<td class=”center”>93</td>

<td rowspan=”2” class=”right”>4,242 ft</td>

<td rowspan=”2” class=”right”>7,289</td>

<td class=”center”>5/5</td>

</tr>

<tr>

<td class=”center”>August 27th</td>

<td class=”center”>98</td>

<td class=”center”>4/5</td>

Diner

</tr>

City

Date

Temp

Altitude

Population

Rating

Walla Walla, WA

June 15th

75º

1,204 ft

29,686

4/5

Magic City, ID

June 25th

74º

5,312 ft

50

3/5

Bountiful, UT

July 10th

91º

4,226 ft

41,173

4/5

Last Chance, CO

July 23rd

102º

4,780 ft

265

3/5

Truth or

August 9th

93º

4,242 ft

7,289

5/5

Consequences,

NM

August 27th

98º

4/5

Why, AZ

August 18th

104º

860 ft

480

3/5

588

Chapter 13

tables and more lists

Exercise

Solutions
brain

Barbell

It’s time to fall back on all that training you’ve done. What you need to do is change the table heading background color just for Tony and Tess, and do it without changing the background of the main table headings. How? You need to find a selector that selects only the nested table headings.

We can use a
descendant selector to
select just the nested
table header. Here’s
how you can do that: (1) Start by selecting
the outer table...

(2) Then select the
inner table...

(3) Then select the
table heading.

(1)

(2)

(3)

{
table table th
background-color: white;

}

you are here �

589

exercise solutions

Exercise

Solutions

1S U M M A R Y

P

2

3

4

5

A

H

L

M

B

6

7

N E S

T E D

I

C

A

O

8

S

A

S

A

R

W

R

D

T

P

G

R

D

9 L I S T - S T Y L E - I M A G E

N

S

I

N

P

R

G

T

O

S

P

-

S

Y

N

I

S

L

N

P

10

11

R

E

L

G

A

12

B O R D E

R

-

C O L

L A

P

S

E

C

W

T

Y

I

13

14

L

I S

T

-

S

T Y

L

E

-

P

O S

I

T

I O N

P

U

O

G

15

16

M A R

K

E

R

D A T A

P

Across

Down

1. Provides a longer description used for screen

1. What a data cell does when it uses more than one
readers. [summary]

row or column. [spans]

6. One table inside another is called _________.

2. <th> is for these. [headings]

[nested]

3. Use this property to change your list marker.

9. Use this property to use an image instead of a

[list-style-type]

built-in marker in your lists. [list-style-image]

4. Table cells have padding and borders, but no

12. Used to merge borders. [border-collapse]

_____. [margins]

13. Used to control whether the marker is inside or

5. Area between borders. [border-spacing]

outside the list items border. [list-style-position]

7. Adds a short description that is displayed with

15. We call bullets a type of list _____. [marker]

the table. [caption]

16. <td> is for these. [data]

8. list-item-position can be used to control the
behavior of text ____. [wrapping]

10. You specify HTML tables by ____, not columns.

[rows]

11. Don't use tables for this. [layout]

590

Chapter 13

14. Default position of the caption. [top]

14 xhtml formsGetting Interactive

Yeah, just got your form.

We’re checking it with the
server now, and then we’ll
get a response right back
to you.

So far all your Web communication has been one way:

from your page to your visitors. Golly, wouldn’t it be nice if your visitors could talk back? That’s where XHTML forms come in: once you enable your pages with forms (along with a little help from a Web server), your pages are going to be able to gather customer feedback, take an online order, get the next move in an online game, or collect the votes in a “hot or not” contest. In this chapter you’re going to meet a whole team of XHTML elements that work together to create Web forms.

You’ll also learn a bit about what goes on behind the scenes in the server to support forms, and we’ll even talk about keeping those forms stylish (a controversial topic; read on and see why).

this is a new chapter

591

browsers and forms

How forms work

If you use the Web at all, then you know what a form is. But you might not have really thought about what they have to do with XHTML. A form is basically a Web page with input fields that allows you to enter information. When the form is submitted, that information is packaged up and sent off to a Web server to be processed by a Web application. When the processing is done, what do you get? Another Web page, of course, as a response. Let’s take a closer look at how this works: The Web server receives the f

The browser packages up all the
data, and then passes i
orm
data in the form and sends it
t of

Web applica
f to a

You visit a Web page with
tion to be proc
over to the Web server.

essed.

an XHTML form, fill out
the form, and submit it.

firstname=buck
lastname=bonz
item=java

1
number=2

Web

Application

Web Server

Browser

The Web application processes the data in the
form and creates a brand new XHTML page as a
response, which it hands back to the Web server.

2

<html>

<head>

Web

<title>

Your Order has

Processed

Application

</title>

<head>

<body>

<p>Thanks for your
it will be shipping
soon!

</p>

</body>

</head>

Web Server

Browser

And the browser gets the

The response is an

The Web server sends the
response and displays it.

XHTML Web page.

Web application’s response
back to the browser.

592

Chapter 14

xhtml forms

How forms work
in the browser

To a browser, a form is just a bit of XHTML in a
page. You’ll see that you can easily create forms in
your pages by adding a few new elements. Here’s how
a form works from the browser’s perspective:

The browser loads the page

The browser loads the XHTML for a page

like it always does, and when it encounters
form elements, it creates controls on the page
that allow you to input various kinds of data. A
control is just something like a button or a text
input box or a drop down menu – basically
something that allows you to input data.

You enter data

You use the controls to enter data. Depending
on the type of control, this happens in
different ways. You can type a single line of
text into a text control, or you might click one
option of many in a checkbox control. We’ll
look at the different kinds of controls shortly.

You submit the form

You submit the form by clicking on a submit
button control. That’s the browser’s cue that it
needs to package up all the data and send that
data off to the server.

The server responds

Once the server has the form data, it passes
it off to the appropriate Web application
for processing. This processing results in a
brand new XHTML page that is returned to
the browser, and since it’s just XHTML, the
browser displays it for you.

you are here �

593

how to write a form

What you write in XHTML

There’s no deep mystery to creating forms with XHTML. In fact, in this chapter you’re going to meet a whole new set of XHTML elements that all work together to create forms. The best way to get a feel for forms is to look at a little XHTML and then to give it a try. Check out this form:

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”

“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>

<html>

This stuff is all old

<head>
hat for you now.

<meta http-equiv=“Content-Type”

content=“text/html; charset=ISO-8859-1” />

<title>Enter the Contest</title>

</head>

Here’s the form.

<body>

<form action=“http://www.headfirstlabs.com/contest.php” method=“POST”>

<p>

A

Just type in your name (and click Submit) to

We’ve got the <form>
enter the contest: <br />
element itself.

First name: <input type=“text” name=“firstname” value=“

B

” /> <br />

Last name: <input type=“text” name=“lastname” value=“”

C

/> <br />

<input type=“submit” />

D

And a bunch of elements

</p>
nested inside it.

</form>

</body>

</html>

Relax For now just take a good
look at the form and
what’s in it; we’ll be
going into all the details
throughout the chapter.

594

Chapter 14

xhtml forms

What the browser creates

Big surprise; to create a form you use a <form> element. Now, just about any block level element can go inside the <form> element, but there’s a whole new set of elements that are made especially for forms. Each of these form elements provides a different way for you to enter information: text boxes, checkboxes, menus of options, and more. We’ll examine all these elements, but first take another look back at the XHTML on the previous page and see how the elements and content inside the

<form> element are displayed in the page below: Here’s just normal
paragraph text in a form.

A

And here are two text

B
controls for entering a

C
first and last name. In

D

XHTML you use the <input>
element to create these.

And here’s the
submit button.

(Your button might
say “Submit Query”

instead.)

You’ll find the contest form in your “chapter14/contest” folder. Open it, take another look around, then load it in your browser and enter the contest.

Exercise
you are here �

595

the form element

How the form element works

The method attribute

Let’s take a closer look at the <form> element – not only does it hold determines how the form
all the elements that make up the form, but it also tells the browser data will be sent to the
where to send your form data when you submit the form (and the server. We’re going to
method the browser should use to send it).

use the most common
one: POST. Later in the
chapter we’ll talk about

The action attribute

...and the name of
other ways to send data,

Here’s the opening tag.

holds the URL of the
the Web application
and why you might or

Everything in the form

Web server...

that will process the
might not use POST.

goes inside.

form data.

<form action=”http://www.headfirstlabs.com/contest.php” method=”POST”>

Everything inside your form goes here.

And the closing tag

</form>
ends the form.

Hey “www.headfirstlabs.com”,
my user just clicked a button

Bring it on.

to submit a form. I’ve got some

We’re ready!

form data I’m sending you via

POST. It’s addressed to the

“contest.php” application.

contest.php

Browser
www.headfirstlabs.com

596

Chapter 14

xhtml forms

Okay, so I have an

XHTML form - that seems
like the easy part. But where
do I get a Web application, or
how do I make one?

Good question. Creating Web
applications is a whole topic unto itself
and far beyond what we cover in this book.

Well, we tried to cover them, but the book
ended up weighing more than you do (not
good). So, anyway...

To create Web applications you need
to know a scripting or programming
language, and one that is supported by
your hosting company. Most hosting
companies support languages like PHP,

Perl, Python, and Java, and if you’re
interested, you’ll definitely want to pick
up a book specifically for creating Web
applications. Also, check with your hosting
company; they sometimes provide simple
scripts to their customers, which takes the
work out of developing Web applications
yourself.

As for this chapter, we’ve already
developed all the Web applications you’ll
need. All you’ll need to do is put the URL
of these applications in the action
attribute of your <form> element.

you are here �

597

overview of form elements

What can go in a form?

You can put just about any block element into a form, but that’s not what we really care about right now; we’re interested in the form elements that create controls in the browser. Here’s a quick rundown of all the commonly used form elements. We’re going to start with the <input> form element, which plays a lot of roles in the form’s world.

text input

The text <input> element is
for entering one line of text.

Optional attributes let you set a
maximum number of characters

An <input> element with a type
and the width of this control.

attribute of “text” creates a one line
control in the browser page.

Most form elements require a name
that is used by the Web application.

Use the type attribute to

We’ll see how this works in a bit.

indicate you want a “text” input.

The <input>
element is an

<input

Notice that
type=“text” name=“fullname” /> empty element,
both of these
so you end it
use the same
with a “ />”

XHTML
element, but
with different
values in their
type attribute.

submit input

The button is labelled

The submit <input> element creates

“Submit” (or “Submit
a button that allows you to submit a

Query”) by default,
form. When you click this button, the
although you can
browser sends the form to the Web
change that (we’ll
application for processing.

show you how later).

For a submit button, specify “submit”

<input type=“submit” />
as the <input> element’s type.

598

Chapter 14

xhtml forms
radio input

The radio <input> element creates a
single control with several buttons,

The radio control
only one of which can be selected
allows only one of a set
at any time. These are like old time
of choices.

car radio buttons; you “push” one in,
and the rest “pop out”.

All the radio buttons

Use a radio <input>
associated with a given

...but each choic
for each choice.

set of choices must
e has
have the same name...

a different value.

<input type=“radio” name=“hotornot” value=“hot” /> Same here,

<input type=“radio” name=“hotornot” value=“not” /> we’re still using
the <input>
element, just
with different
type values.

checkbox input

A checkbox <input> element
creates a checkbox control that can
be either checked or unchecked.

Unlike radio buttons, a

You can use multiple checkboxes
checkbox allows zero or
together, and if you do, you can
more of a set of choices.

check as many or few as you like.

Like radio,
you use one

Related checkboxes also share
checkbox
a common name.

Each checkbox has a

<input> element
different value.

for each choice.

<input type=“checkbox” name=“spice” value=“salt” />

<input type=“checkbox” name=“spice” value=“pepper” />

<input type=“checkbox” name=“spice” value=“garlic” />
you are here �

599

more form elements

What can go in a form? (Part II)

Okay, not every form element is an <input> element. There are a few others, like

<select> for menus and <textarea> for typing in more than one line of text.

So, why don’t you get familiar with these as well before moving on? Oh, and by the way, once you do that, you’ll know 90% of the form elements (and 99% of the form elements that are commonly used).

textarea

The <textarea> element
creates a multi-line text area
that you can type into. If you
type more text than will fit
into the text area, then a scroll
rows
bar appears on the right side.

cols

The <textarea>
element is not an

Use the name
empty element,
attribute t
so it has both
o
give the element

The cols attribute tells the
opening and
a unique name.

browser how many characters
closing tags.

wide to make the text area.

<textarea name=“comments” rows=“10” cols=“48”></textarea> The rows attribute tells the
browser how many characters

Any text that goes between the
tall to make the text area.

opening and closing tags becomes
the initial text in the browser’s
text area control.

600

Chapter 14

xhtml forms
select

The <select> element creates a menu
control in the Web page. The menu
provides a way to choose between a set

The select element creates
of choices. The <select> element works in
a menu that looks like
combination with the <option> element
this (although the look
below to create a menu.

will vary depending on the
browser you’re using).

The <select> element goes
around all the menu options to
group them int

Just like the other form elements,
o one menu.

give the select element a unique
name using the name attribute.

<select name=“characters”>

<option value=“Buckaroo”>Buckaroo Banzai</option>

<option value=“Tommy”>Perfect Tommy</option>

<option value=“Penny”>Penny Priddy</option>

<option value=“Jersey”>New Jersey</option>

<option value=“John”>John Parker</option>

</select>
option

After clicking on the

The <option> element works with
menu, the menu items
the <select> element to create a
drop down.

menu. Use an <option> element for
each menu item.

The content of the

<select name=“characters”>

<option> element is used

<option value=“Buckaroo”>Buckaroo Banzai</option> for the menu items’

<option value=“Tommy”>Perfect Tommy</option> description. Each menu

<option value=“Penny”>Penny Priddy</option> option also includes a

<option value=“Jersey”>New Jersey</option> value representing the

<option value=“John”>John Parker</option> menu item.

</select>
you are here �

601

the bean machine

The Starbuzz Coffee Web
site is kicking butt. We’ve got
a new concept called the “Bean

Machine”, which is an online
form to order our coffees. Can
you make it happen?

A drop-down menu
of coffees.

A choice
of whole

House Blend
or ground
coffee (you

Starbuz

Shade Grown Bolivia Supremo
z
can choose
zz

C

Organic Guatemala
only one).

u
o
b r

Kenya
a t S e e f

Gift wrap
or include
a catalog

(choose
zero, one,

Here’s
or both).

what
the form

Ship to
should
address
consisting
look like.

of five
text boxes.

A box for
customer
comments.

And a

Order Now
submit
button.

602

Chapter 14

xhtml forms

Markup Magnets

Your job is to take the form element magnets and lay them on top of the corresponding controls in the sketch. You won’t need all the magnets below to complete the job; some will be left over. Check your answer in the back of the chapter before moving on.

House Blend

<input type="text" ... />

<input type="text" ... />

Shade Grown Bolivia Supremo

<input type="text" ... />

<input type="text" ... />

<input type="text" ... />

<input type="text" ... />

Organic Guatemala

Kenya

<input type="checkbox" ... />

<input type="checkbox" ... />

<input type="checkbox" ... />

<input type="radio" ... />

<input type="radio" ... />

<input type="radio" ... />

<textarea>...</textarea>

<textarea>...</textarea>

<select>...</select>

<select>...</select>

<select>...</select>

<option>...</option>

<option>...</option>

<option>...</option>

<option>...</option>

Order Now

<input type="submit" ... />

<input type="submit" ... />
you are here �

603
creating the form

Getting ready to build the Bean Machine form

Before we start building that form, take a look inside the “chapter14/starbuzz”

folder and you’ll find the file “form.html”. Open it and have a look around. All this file has in it are the XHTML basics:

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”

“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>

<html xmlns=“http://www.w3.org/1999/xhtml” lang=“en” xml:lang=“en” >

<head >

<meta http-equiv=“Content-Type” content=“text/html; charset=ISO-8859-1” />

<title> The Starbuzz Bean Machine</title>

</head>

<body>

<h1> The Starbuzz Bean Machine</h1>

<h2> Fill out the form below and click submit to order</h2> All we’ve got so far is a
heading identifying the page,

The form is
along with instructions.

</body>
going to go here.

</html>

For now, we’re going to build these
forms without all the style we’ve been
using on the Starbuzz site. That
way we can concentrate on the form

XHTML. We’ll add the style in later.

Figuring out what goes in the form element

It’s time to add your very first <form> element. The first thing you have to know when creating a <form> element is the URL of the Web application that is going to process your form data. We’ve already taken care of that for you; you’ll find the Web application that processes Starbuzz orders here:

http://www.starbuzzcoffee.com/processorder.php

This URL points to the
starbuzzcoffee W

...and to the processorder.php Web
eb site...

application that’s on the server
there. This application already
knows how to take orders from the
form we’re going to build.

604

Chapter 14
xhtml forms

Adding the form element

Once you know the URL of the Web application that will process your form, all you need to do is plug it into the action attribute of your <form> element, like this (follow along and type the changes into your XHTML):

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”

“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>

<html xmlns=“http://www.w3.org/1999/xhtml” lang=“en” xml:lang=“en” >

<head>

<meta http-equiv=“Content-Type” content=“text/html; charset=ISO-8859-1” />

<title> The Starbuzz Bean Machine</title>

</head>

<body>

<h1> The Starbuzz Bean Machine</h1>

<h2> Fill out the form below and click submit to order</h2>

<form action=”http://www.starbuzzcoffee.com/processorder.php” method=”POST”> Here’s the
form element.

The action attribute contains the

And remember we’re using the

</form>

URL of the Web application.

“POST” method to deliver
the form data to the server.

</body>

Go ahead and add the

More on this later.

</html>
form closing tag too.

So far so good, but an empty <form> element isn’t going to get you very far.

Looking back at the sketch of the form, there’s a lot there to add, but we’re going to start simple and get the “Ship to:” part of the form done first, which consists of a bunch of text inputs. You already know a little about text inputs, but let’s take a closer look. Here’s what the text inputs for the Starbuzz form look like:

<input type=”text” name=”name” />

We’ve got one

We use the <input>
text input for
element for a few

<input type=”text” name=”address” />
each input area in
different controls.

<input type=”text” name=”city” />
the form: Name,

The type attribute
determines wha

<input type=”text” name=”state” />

Address, City,
t kind

State, and Zip.

of control it is.

<input type=”text” name=”zip” />

Here the type is “text” because this The name attribute acts as an identifier for the is going to be a text input control.

data the user types in. Notice how each one is set to
a different value. Let’s see how this works...

you are here �

605

form element names

How form element names work

Here’s the thing to know about the name attribute: it acts as the glue between your form and the Web application that processes it. Here’s how this works: Each input control in your form has a
name attribute

When you type the elements for a form into your

XHTML file, you give them unique names. You saw this
with the text inputs:

Notice here we’ve got an element whose
name is “name” (which is perfectly fine).

<input type=”text” name=”name” />

<input type=”text” name=”address” />

Each <input> element

<input type=”text” name=”city” />
gets its own name.

<input type=”text” name=”state” />

<input type=”text” name=”zip” />

What you enter into

When you submit a form, the browser
the form.

packages up all the data using the
unique names:

Say you type your name, address, city, state, and zip
into the form and click submit. The browser takes
each of these pieces of data and labels them with your
unique name attribute values. The browser then sends
the names and values to the server. Like this:

The unique
names for each
name = Buckaroo Banzai
form element.

address = Banzai Institute
city = Los Angeles
state = CA
zip = 90050

Each unique
processorder.php
name gets a
value from the
data you type
into the form.

www.starbuzzcoffee.com

What the browser packages
up for the server.

The Web application needs the form data to
be labelled so it can tell what is what.

606

Chapter 14
xhtml forms
there are no

Dumb Questions

Q:

What’s the difference between a
browser takes al the names along with

Q: Didn’t you say that the name for
text <input> and a <textarea>?

their values and sends them to the server.

For instance, when you type the zip code
each form element needs to be unique?

But the radio <input> elements al have

A:

“90050” into a text <input> element with the
the same name.

You want to use a text <input> for
name “zip”, the browser sends “zip = 90050”

entering text that is just a single line, like
to the server when the form is submit ed.

a name or zip code, and a <textarea> for

A: Right. Radio butons come as a set.

longer, multi-line text.

Q: How does the Web application Think about it: if you push one buton in, the Q:

rest pop out. So, for the browser to know

know the names I’m going to use in my
the radio but ons belong together, you use

Can I make the submit button say
form? In other words, how do I pick the
the same name. Say you have a set of radio
something other than “Submit”?

names for my form elements?

but ons named “color” with values of “red”,

A:

A:

“green”, and “blue”. They’re al colors, and
only one color can be selected at a time, so

Yes, just put a value at ribute in the

Good question. It real y works
a single name for the set makes sense.

element and give it a value like “Order Now”. the other way around: you have to know You can also use the value attribute of text
what form names your Web application

Q:

input to give that input some default text.

is expecting and write your form to match

it. If you’re using a Web application that

What about checkboxes? Do they

Q:

work like radio buttons?

someone else wrote, they’ll have to tell

Is there a limit to how much
you what names to use, or provide that
text I can type into a text <input> or a
information in the documentation for the

A: Yes; the only diference is that you

<textarea>?

application. A good place to start is to ask
your hosting company for help.

are al owed to select more than one choice

A:

with a checkbox.

Browsers do place a limit on the

Q:

When the browser sends the form data to
amount of text you can type into either a

Why doesn’t the <option>
the server, it combines all the checkbox
text <input> or a <textarea>; however, it’s
element have a name attribute? Every
values into one value and sends them
usually way more than you’d ever need to
other form element does.

along with the checkbox name. So, say
type. If you’d like to limit how much your
you had “spice” checkboxes for “salt”,
users can type into a text <input>, you can

A:

“pepper”, and “garlic”, and you checked them
use the maxlength at ribute and set it to a

Good catch. Al <option> elements
all; then the server would send “spice =
specific number of characters. For example,
are actual y part of the menu that is created
salt&pepper&garlic” to the server.

maxlength=”100” would limit users to typing
by the <select> element. So, we only real y
at most 100 characters. However, for a
need one name for the entire menu, and

Q: Geez, do I realy need to know

<textarea>, there is no way with XHTML to
that is already specified in the <select>
al this stuff about how data gets to the
limit how much your users can type.

element. In other words, <option> elements
don’t need a name at ribute because the
server?

Q:

<select> has already specified the name for

I stil don’t get how the names get the entire menu. Keep in mind that when A:

matched up with the form data.

the form is submitted, only the value of the

Al you need to know is the names
currently selected option is sent along with
and types of the form elements your Web

A:

this name to the server.

application is expecting. Beyond that,

Okay, you know each form element
knowing how it al works sometimes helps,
has a unique name, and you also know
but, no, you don’t need to know all the gory-
that the element has a corresponding value.

behind-the-scenes details of what is being

When you click the submit but on the
sent to the server.

you are here �

607
adding input elements

Back to getting those <input> elements into your XHTML

Now we’ve got to get those <input> elements inside the form.

Check out the additions below, and then make the changes in your “form.html”.

Here’s JUST the form
snippet from “form.html”.

We’re going to

You can only nest block elements

Hey, we’ve got to save a
start by putting
directly inside a form.

few trees here!

everything inside
a <p> element.

<form action=”http://www.starbuzzcoffee.com/processorder.php” method=”POST”>

<p> Ship to: <br />

Here are all

Name: <input type=”text” name=”name” /> <br /> the <input>

Address: <input type=”text” name=”address” /> <br /> elements: one
for each text

City: <input type=”text” name=”city” /> <br /> input in the

“Ship to” section

State: <input type=”text” name=”state” /> <br /> of the form.

Zip: <input type=”text” name=”zip” /> <br />

</p>

<p>

<input type=”submit” value=”Order Now” />

</p>

</form>

And you should also know that <input> is an

We’ve added a label for each
inline element, so if you want some linebreaks
input so the user knows what
between the <input> elements, you have to
goes in the text input.

add <br />s. That’s also why you need to
nest them all inside a paragraph.

Finally, don’t forget that users need a submit button to
submit the form. So add a submit button by inserting an

<input> at the bottom with a type of “submit”. Also add a value of “Order Now”, which will change the text of the
button from “Submit” to “Order Now”.

After you’ve made all these changes, save your “form.html” file and let’s give this a whirl.

Don’t forget to validate your

XHTML. Forms elements need
validation too!

608

Chapter 14

xhtml forms

A form-al test drive

You don’t think we’d give you a toy example

Reload the page, fill in the text inputs, and submit the form.

that doesn’t really work, do you? Seriously,

When you do that, the browser will package up the data
starbuzzcoffee.com is all ready to take your
and send it to the URL in the action attribute, which is at form submission. Go for it!

www.starbuzzcoffee.com.

Notice the change in the

URL of your address bar

Here’s the f
after y
orm.

ou submit the form

(you’ll see the URL in the
action attribute in the
address bar).

Here’s the Web application’s
response. It looks like the
application got what we
submitted, but we haven’t given

And here’s the response
it everything it needs.

after submitting the form.

Adding some more input elements to your form

It looks like the Web application isn’t going to let us get very far without telling it the beans we want, as well as the bean type (ground or whole). Let’s add the bean selection first by adding a <select> element to the form. Remember that the

<select> element contains a list of options, each of which becomes a choice in a drop-down menu. Also, associated with each choice is a value; when the form is submitted, the value of the chosen menu option is sent to the server. Turn the page and let’s add the <select> element.

you are here �

609

using a select

Adding the <select> element

<form action=”http://www.starbuzzcoffee.com/processorder.php” method=”POST”>

<p> Choose your beans:

Here’s our brand new

<select> element. It gets a

<select name=”beans”>
unique name too.

<option value=”House Blend”> House Blend</option>

<option value=”Bolivia”> Shade Grown Bolivia Supremo</option>

<option value=”Guatemala”> Organic Guatemala</option>

<option value=”Kenya”> Kenya</option>

</select>

Inside we put each <option> element, one per choice of coffee.

</p>

<p>Ship to: <br />

Name: <input type=”text” name=”name” /> <br />

Address: <input type=”text” name=”address” /> <br /> City: <input type=”text” name=”city” /> <br />

State: <input type=”text” name=”state” /> <br /> Zip: <input type=”text” name=”zip” /> <br />

</p>

<p>

<input type=”submit” value=”Order Now” />

</p>

</form>

HTML Up Close

Let’s take a closer look at the <option> element.

The content of the
element is used as the label

Each option has a value.

in the drop down menu.

<option value=”House Blend”> House Blend</option> When the browser packages up
the names and values of the form

In this case, the browser would send the server
elements, it uses the name of the
beans = “House Blend”.

<select> element along with the value
of the chosen option.

610

Chapter 14

xhtml forms

Test driving the <select> element

Let’s give the <select> element a spin now. Reload your page and you should have a nice new menu waiting on you. Choose your favorite coffee, fill in the rest of the form, and submit your order.

Here’s the form, complete
with a <select>. Notice all
the options are there.

We still haven’t given the

Web application everything
it needs, but it’s getting
everything in the form so far.

Here’s the result of
the <select> choice.

Here are all the
text inputs.

you are here �

611
providing choices
brain
power

?

Change the <select> element name attribute to “thembeans”. Reload the form and resubmit your order. How does this affect the results you get back from the Web application?

Make sure you change the name back to “beans” when you’re done with this exercise.

Give the customer a choice of whole or ground beans

The customer needs to be able to choose whole or ground beans for their order. For those, we’re going to use radio buttons. Radio buttons are like the buttons on old car radios – you can push only one in at a time. The way they work in XHTML is that you create one <input> of type “radio” for each button; so, in this case you There are two
need two buttons: one for whole beans and one for ground. Here’s radio buttons here:

what that looks like:

one for whole beans,
and one for ground.

<p>Type: <br />

<input type=”radio” name=”beantype” value=”whole” /> Whole bean <br />

<input type=”radio” name=”beantype” value=”ground” /> Ground

</p>

Notice that we

We’re using the <input>

Here’s the unique name. And here’s the value that will be
often label radio
element for this, with its

All radio buttons in the sent to the Web application. Only buttons on the
type set to “radio”.

same group share the one of these will be sent (the
same name.

one that is selected when the
right-hand side of
form is submitted).

the element.

612

Chapter 14

xhtml forms

Punching the radio buttons

Take the radio button XHTML on the previous page and insert it into your XHTML just below the paragraph containing the <select> element. Make sure you reload the page, and then submit it again.

Depending on your browser,
you may have noticed that
no radio button was pressed
when you reloaded the page.

Wow! Starbuzz took our order, and
we’re not even done with it yet. We’ve
still got to add the gift options and
an area for customer comments.

How could the order work without all
the elements being in the form? Well, it
all depends on how the Web application is
programmed. In this case, it is programmed
to process the order even if the gift
wrap and catalog options and the customer
comments are not submitted with the rest
of the form data. The only way you can
know if a Web application requires certain
form elements is to talk to the person who
developed it, or to read the documentation.

you are here �

613

adding checkboxes

Hey, 80% of our customers
order “ground” beans. Can you

Exercise
make it so the ground bean type
is already selected when the
user loads the page?

If you add an attribute called checked with a value of “checked”

into your radio input element, then that element will be selected by default when the form is displayed by the browser. Add the checked attribute to the ground” radio <input> element and give the page a test. You’ll find the solution in the back of this chapter.

Completing the form

You’re almost there. You’ve just got two sections
to add to the form: the “Extras” section with
the two checkboxes and the customer comment

House Blend
section. Since you’re getting the hang of forms,

Starbuzz

Shade Grown Bolivia
we’re going to speed up a bit and add them both

C

Supremo
uzz b
o
r

Organic Guatemala
at the same time.

a t S e e f

Kenya

The extras section consists of two
checkboxes, one for gift wrap and
another to include a catalog.

It looks like the “include catalog”

option should be checked by default.

The customer comment
section is just a

<textarea>.

Order Now

614

Chapter 14

xhtml forms

Adding the checkboxes and text area

You know the drill: look over the new XHTML and add
it to your “form.html”.

<form action=”http://www.starbuzzcoffee.com/processorder.php” method=”POST”>

<p> Choose your beans:

<select name=”beans”>

<option value=”House Blend”>House Blend</option>

<option value=”Bolivia”>Shade Grown Bolivia Supremo</option>

<option value=”Guatemala”>Organic Guatemala</option>

<option value=”Kenya”>Kenya</option>

</select>

Here we’ve added a checkbox for each

...but have

</p>
option. Notice that these share the
different values.

same name, “extras[]”...

<p>Type: <br />

<input type=”radio” name=”beantype” value=”whole” /> Whole bean <br />

<input type=”radio” name=”beantype” value=”ground” checked=”checked” /> Ground

</p>

<p>Extras: <br />

<input type=”checkbox” name=”extras[]” value=”giftwrap” /> Gift wrap <br />

<input type=”checkbox” name=”extras[]” value=”catalog” checked=”checked” /> Include

catalog with order

</p>

We’re using the checked Like the radio
attribute to specify that

<p>Ship to: <br />
buttons, we’ve

Name: <input type=”text” name=”name” /> <br />
the catalog option should put these

Address: <input type=”text” name=”address” /> <br /> be checked by default. labels to the

City: <input type=”text” name=”city” /> <br />

You can add a checked right of the

State: <input type=”text” name=”state” /> <br /> attribute to more than

Zip: <input type=”text” name=”zip” /> <br />
checkboxes.

one checkbox.

<p>Customer Comments: <br />

<textarea name=”comments” rows=”10” cols=”48”></textarea>

</p>

<p>

<input type=”submit” value=”Order Now” />

</p>

Here’s the

We’ve specified that we want it to be 10

</form>
text area.

characters high and 48 characters wide.

you are here �

615

successful submission

The final test drive

Save your changes, reload, and check out the new form.

Don’t you think it’s looking quite nice?

Here’s what you get when you
submit. The Web application has

Here’s our brand new
received all the form data on
checkboxes, with the catalog
the page and has incorporated it
checkbox already checked.

into the response page. See if you
can locate all the form data you
submitted.

And a nice new
text aera as well.

Be sure and try out all
the various combinations of
sending this form (with gift
wrap, without, with a catalog,
without, different coffees, and
so on) and see how it all works.

616

Chapter 14

xhtml forms

Stop right there. Do you
think I didn’t see the way you
slipped in that element name of

“extras[]”? What’s with those
square brackets! You have to
explain that.

Believe it or not, “extras[]”

is a perfectly valid name
for a form element.

But even if it’s valid, it doesn’t exactly look
normal, does it? Here’s the deal: from the
perspective of XHTML, this is a normal
form element name; it doesn’t have any effect
on the browser at all if it has square brackets
in the name.

So why did we use them? It turns out that the
scripting language that the processorder.php

Web application is written in likes a little hint
that a form variable may have multiple values
in it. The way you give it this hint is to add

“[ ]” on the end of the name.

So, from the perspective of learning XHTML,
you can pretty much forget about all this, but
you might just tuck this into the back of your
mind in case you ever write a form that uses a

PHP Web application in the future.

you are here �

617

match the form names

BE the Browser

Below, you’ll find an XHTML form, and on the right the data a user entered into the form. Your job is to play like you’re the browser and match each form element name with the values the user entered. After you’ve done the exercise, look at the end of the chapter to see if you matched up the form names with the values correctly.

<form action=”http://www.chooseyourmini.com/choice.php” method=”POST”>

<p>Your information: <br />

Name: <input type=”text” name=”name” /> <br />

Zip: <input type=”text” name=”zip” /> <br />

</p>

<p>Which model do you want? <br />

<select name=”model”>

<option value=”cooper”> Mini Cooper</option>

<option value=”cooperS”> Mini Cooper S</option>

<option value=”convertible”> Mini Cooper Convertible</option>

</select>

</p>

<p>Which color do you want? <br />

<input type=”radio” name=”color” value=”chilired” /> Chili Red <br />

<input type=”radio” name=”color” value=”hyperblue” /> Hyper Blue

</p>

<p>Which options do you want? <br />

<input type=”checkbox” name=”caroptions[]” value=”stripes” /> Racing Stripes

<br />

<input type=”checkbox” name=”caroptions[]” value=”sportseats” /> Sport Seats

</p>

<p>

<input type=”submit” value=”Order Now” />

</p>

Here’s the form.

</form>

618

Chapter 14

xhtml forms

And here’s the form filled out.

Match each piece of form data
with its form name and put your
answers here.

name = _

“B_u_
ck_a_
ro___
o Ba _
nz_a_
i” _______
zip = ___________________
model = _________________
color = _________________
caroptions[] = __________

Extra credit...

you are here �

619

form methods: get and post

Now that we’ve got the form
finished, can we talk about the method
the browser uses to send this data to the
server? We’ve been using “POST”, but
you said there are other methods, too.

There are two primary methods
the browser uses: POST and GET.

POST and GET accomplish the same thing – getting your form data from the browser to a server – but
in two different ways. POST packages up your form
variables and sends them behind the scenes to your
server, while GET also packages up your form variables, but appends them on the end of the URL before it
sends a request to the server.

With POST all the form data is sent as part of
the request and is invisible to the user.

firstname=buck
lastname=bonz
item=java
number=2

POST

Web

The user just

Application
sees the Web
application’s URL
http://www.headfirstlabs.com/contest.php
in her browser
address bar.

With GET, the form data is added to the URL

The request doesn’t
itself, so the user sees the form data.

have any of the form
data in it.

Notice the form
data added on
to the end of

GET
the URL. This
is what the

Web

Application
user sees in the
address bar.

http://www.headfirstlabs.com/contest.php?firstname=buckaroo&lastname=banzai 620

Chapter 14

xhtml forms

Watching GET in action

Just change the method

There’s no better way to understand GET than to see it in action.

from “POST” to “GET”.

Open up your “form.html” file and make the following small change:

<form action=”http://www.starbuzzcoffee.com/processorder.php” method=”GET”> Save and reload the page; then fill out the form and submit it. You should see something like this:

You’ll see this URL
in your browser.

http://www.starbuzzcoffee.com/processorder.php?beans=Kenya&beantype=gro und&extras%5B%5D=catalog&name=Buckaroo+Banzai&address=Banzai+Instit ute&city=Los+Angeles&state=CA&zip=90050&comments=Great+coffee Notice that the browser encodes

Now you can see every
various characters, like spac
form element name
es. The

Web application will aut
and their values right
omatically
decode these when i
here in the URL.

t receives them.

there are no

Dumb Questions

Q:

On the other hand, if you have a Web

Q:

application that processes orders, then you

So why would I use POST over
wouldn’t want users to be able to bookmark

Why is it called “GET” if we’re

GET, or vice versa?

the page. (Otherwise, every time they
sending something to the server?

A:

returned to the bookmark, the order would

A:

There’s a couple of big differences
be resubmitted.)

Good question. What’s the main
that really matter. If you want users to be

A situation when you’d never want to use
job of a browser? To get Web pages from a
able to bookmark pages that are the result
a GET is when the data in your form is
server. And, when you are using GET, the
of submitting a form, then you have to use
private, like a credit card or a password.

browser is just going about getting a Web

GET, because there is no way to bookmark

Because the URL is in plain view, the private
page in the normal way it always does,
a page that has been returned as a result of
information is easily found by others if they
except that, in the case of a form, it has
a POST. When would you want to do that?

look through your browser history or if the
appended some more data to the end of the

Say you have a Web application that returns GET somehow gets bookmarked.

URL. Other than that, the browser just acts
a list of search results; you might want users Finally, if you use a <textarea>, you should like it’s a normal request.

to be able to bookmark those results so they use POST, because you’re probably sending can see them again without having to fill out

With POST, on the other hand, the browser
a lot of data. GET requests have a limit of
a form.

256 characters; POST has no limit on the
http://www.headfirstlabs.com/contest.php?firstname=buckaroo&lastname=banzai actually creates a little data package and
sends it to the server.

size of the data package you send.

you are here �

621

test yourself, get and post

Sharpen your pencil

GET or POST

For each description, circle either GET or POST
depending on which method would be more
appropriate. If you think it could be either, circle
both. But be prepared to defend your answers...

GET POST

A form for typing in a username and password.

GET POST

A form for ordering CDs.

GET POST

A form for looking up current events.

GET POST

A form to post book reviews.

GET POST

A form for retrieving benefits by your government ID number.

GET POST

A form to send customer feedback.

622

Chapter 14

xhtml forms

I’ve been meaning to say, great
job on the Bean Machine! This is really
going to boost our coffee bean sales. All
you need to do is give this a little style
and we’re ready to launch it for our
customers.

brain
power

?

Given everything you
know about XHTML
and CSS, how would
you approach styling
this form?

you are here �

623

tabular versus presentation

Tonight’s talk: Table and CSS spar
over how to lay out forms.

Table

CSS

Hey CSS, what’s happening?

What on earth are you doing in this chapter,

Table?

What do you mean? I dropped by to help get
these forms in shape. They’re looking a bit... well,
ragged, if you ask me.

I agree the forms need some fixing up in the
looks department, but that’s my job. You’re for
tabular data, remember?

Yes, and some people consider form
elements to be tabular data, you know.

Besides, I’m much better at making forms
look good than you are.

Says who?

Says me. I get forms looking nice and neat, with
the labels and form elements all aligned properly.

I can position things too, you know. These
readers have read the chapter on positioning;
they know how to get things “all aligned
properly” using CSS. Anyway, even if you
can align the form elements properly, you
certainly can’t do things like add color and
padding and change the font family.

Well, I agree I can’t add those little extra touches
like you can, but that stuff doesn’t really matter
anyway. That’s just the icing on the cake. The real
trick to making forms user-friendly is getting the
labels and elements presented in a way that makes
sense, so there’s no confusion about what goes with
what. Users don’t really care about all that other
stuff.

624

Chapter 14
xhtml forms

Table

CSS

Dude, you have no idea what you’re talking
about. Forms should match the look and
feel of the rest of the Web site. Users will be
confused if they go to fill out a form and it
doesn’t look like part of the site.

I guess. But when it comes to laying out a table
properly, I’m the way to go. The last time I saw
someone trying to lay out a form using CSS, there
were <div>s and <span>s all over the place; it was a mess. And all that positioning and messing with
margins to get the widths just right... it gave me a
headache just looking at it all.

Well, what about all your <tr>s and <td>s
littering up the XHTML? That’s no different.

At least with my table rows and data cells, it’s easier
to figure out what’s going to end up where; with
your positioning tricks, I never know where stuff is
going to end up.

You obviously haven’t read Chapter 12. And

I just don’t buy that form elements are tabular
data... they’re XHTML elements, not data.

But the users are entering data into the form
controls, aren’t they? A form is used for gathering
data from the person using the form. How is that
not tabular data?

Hmm... I suppose I can sort of see that... but it
just seems so wrong to use a table to do layout.

Layout is presentation, and presentation is my job.

Well, I say if I can do a job better than you, then,
hey, use me to do it. I’m happy to oblige.

Better than me? Whoa now, that’s going too
far...

Tell you what, why don’t we just let the readers
decide?

you are here �

625

deciding how to style forms

To Table or Not to Table? That’s the question...

You’re going to find people on both sides of this issue. Should you use CSS to layout your forms? Or tables? The harsh reality is that laying out forms with CSS is difficult. And, if you’d like to bend space and time to lay out your forms with CSS, we’ll gladly get out of your way and look on in admiration. However, many forms are tabular in their layout, so why not use tables to do the layout of your forms and let CSS do the styling? That way, we get the best of both worlds.

Let’s start with the layout...

We’ll start by getting the form into a table. Check out the sketch below and you’ll see the form fits pretty nicely in a table, and even better, it looks like a form rather than a ragged collection of input elements. Also notice that we’ve used a nested table in the “Ship to:” section.

Here’s the sketch of the table.

It’s a simple table, with two
columns and six rows - one row
for each main section of the form.

We’ve thrown all the input

The labels for
elements into the right-hand
each form
column.

element go
in the left
column.

Notice that we’ve grouped each
set of checkboxes and radio
buttons into one table data cell.

The Ship to: section has five text

<input> elements, so we’ve grouped
them into a nested table. The

The cell on
nested table has the same basic
the left of
layout as the main table: two
the submit
columns and five rows, with one
button is
row for each label / element pair.

empty. There’s
no label to
put here.

626

Chapter 14

xhtml forms

Getting the form elements

Ready Bake
into a table

XHTML

Now that you know how to organize the form elements in a table, you need to put your XHTML table writing skills to the test. So get typing!

Just kidding. We wouldn’t make you type all this... after all, this chapter is really about forms, not tables. We already typed this in for you; it’s in the file “styledform.html”

Here’s the <form> element;
in the “chapter14/starbuzz” folder. Even though it looks complicated, it’s really not we don’t need to put this
that bad. We’ve added a few annotations below to point out the main parts.

part into the table.

<form action=”http://www.starbuzzcoffee.com/processorder.php” method=”POST”> Here’s where the table begins.

<table>

Each of the main table

<tr>
rows has two data cells: a

<th>Choose your beans:</th>

<th> for the label, and a

<td>

<select name=”beans”>

<td> for the form element.

<option value=”House Blend”>House Blend</option>

<option value=”Bolivia”>Shade Grown Bolivia Supremo</option>

<option value=”Guatemala”>Organic Guatemala</option>

<option value=”Kenya”>Kenya</option>

</select>

</td>

</tr>

Each section of the form goes

<tr>
into a separate row.

<th>Type:</th>

<td>

<input type=”radio” name=”beantype” value=”whole” /> Whole bean

<br />

<input type=”radio” name=”beantype” value=”ground” checked=”checked” /> Ground

</td>

</tr>

For the bean selection menu, the “beantype” radio

<tr>
buttons, and the “extras” checkbox, we put all the

<th>Extras:</th>
form elements for each menu in one data cell.

<td>

<input type=”checkbox” name=”extras[]” value=”giftwrap” /> Gift wrap

<br />

<input type=”checkbox” name=”extras[]” value=”catalog” checked=”checked” /> Include catalog with order

</td>

</tr>
you are here �

627
the xhtml, continued

<tr>

But for the shipping data, we are creating a nested table - a

<th>Ship to:</th>
table in a data cell. We did this so we could align the labels on

<td>

<table>
each text <input> in the “Ship to” part of the form properly.

<tr>

<td>Name:</td>

<td>

<input type=”text” name=”name” value=”” />

</td>

</tr>

<tr>

<td>Address:</td>

<td>

<input type=”text” name=”address” value=”” />

</td>

</tr>

<tr>

<td>City:</td>

<td>

<input type=”text” name=”city” value=”” />

</td>

</tr>

<tr>

<td>State:</td>

<td>

<input type=”text” name=”state” value=”” />

</td>

</tr>

<tr>

<td>Zip:</td>

<td>

<input type=”text” name=”zip” value=”” />

</td>

</tr>

</table>

Here’s the end of the nested

</td>
table for the shipping data.

</tr>

<tr>

<th>Customer Comments:</th>

<td>

<textarea name=”comments” rows=”10” cols=”48”></textarea>

</td>

</tr>

And here are the rows in the
main table with the <textarea>

<tr>
and submit <input> elements.

<th></th>

<td><input type=”submit” value=”Order Now” /></td>

</tr>

</table>

</form>

628

Chapter 14

xhtml forms

Test driving a very tabular form

Open “styledform.html” in your browser and take a look at the Starbuzz Bean Machine form in table format. It looks better, doesn’t it? All the labels and form elements are aligned, and it looks more professional.

Now, we can use CSS to make it look even better, by tweaking some things here and there. Let’s take a look at what you might want to change.

We’ll do some basic styling that you’re well
familiar with by now, like changing the
font, and adding a background color.

A border around the
table would look nice.

We can align all these
labels to the right

Notice how
so they line up nicely
the rows are a
against the form
little too close
elements.

together? We
can add space
between the cells
in the rows so

We can also align the
the form is easier
labels and the form
to read.

elements vertically
so they both align
to the top of the
data cells.

Finally, we’ll add just
a bit of space on the
left side of the body.

you are here �

629

styling the form

Styling the form and the table with CSS

We just need to add a few styling rules to the XHTML, and we’ll be done.

Because this form is part of the Starbuzz site, we’re going to reuse the style in the Ready Bake

“starbuzz.css” style sheet, and create a new style sheet, “styledform.css”, to add new style rules for the Bean Machine form. All of this CSS should be familiar to CSS
you now. We’re not using any rules unique to tables or forms; it’s all just the same stuff you’ve been using in the last few chapters.

You’ll find this CSS in the file “styledform.css” in the folder “chapter14/starbuzz”.

We’re going to rely on the Starbuzz CSS for some of our style, but we’re changing the body font to a sans-serif font, adding the Starbuzz background image, and adding a margin to the body.

T
body {
hese font properties
background: #efe5d0 url(images/background.gif) top left; will be inherited by all
font-family: Verdana, Helvetica, Arial, sans-serif;
the elements on the page,
margin: 20px;
including the text in the

}

table and the form.

table {

We’re adding a border around the table,
border: thin dotted #7e7e7e;
and some padding between the table
padding: 10px;
content and the border.

}

th {

The form labels are in the table headings. We want to align text-align: right;
these to the top and right so they align nicely with the
vertical-align: top;
form elements in the right column. We’re also adding a bit
padding-right: 10px;
of padding to give them a little bit more space.

padding-top: 2px;

}

The content of the data cells is already aligned
td {
to the left by default, which is what we want,
vertical-align: top;
but we have to align them vertically too, to
padding-bottom: 15px;
match the table headings. We’re adding a bit of

}

padding here too, to add space between the rows.

table table {
border: none;

These two rules override some of the other properties we set padding: 0px;
in the rules for table and td above. Why? Because we don’t

}

want the nested table to have a border, and we want the
spacing to be tighter, so we’re removing the padding. We also table table td {
need to align the form labels in the nested data cells to the text-align: right;
right (those aren’t in table headings, like the others are, so padding-bottom: 0px;
they’re not aligned with the th rule above).

}

630

Chapter 14

xhtml forms

The final test drive

You’re going to add two <link> elements to the <head> of your XHTML in “styledform.html”, linking in the Starbuzz style If you want to stretch your
sheet from Chapter 12, “starbuzz.css”, and your new style sheet, XHTML and CSS skills a bit, see if

“styledform.css”. Make sure you get the order correct: link the you can add the Starbuzz header

“starbuzz.css” file first, then the “styledform.css”. Once you’ve got the and footer to the Bean Machine
two style sheets linked, save and reload your page. You should see the page and make the Bean Machine
snazzy, styled version of the Starbuzz Bean Machine in your browser.

look really nice with those elements.

Wow, what a difference a little style makes!

The bean machine form now matches
the rest of the Starbuzz site.

The labels are
aligned with the
top of the form
elements, and
they’re aligned

Notice that the
to the right as
nested table
well. This alignment
doesn’t have a
makes it easier to
border, and the
see which labels
spacing is tighter;
belong with which
that’s because
controls.

of those rules
that override the
properties set for

T
the main table.

he space between
the rows makes a
big difference and
makes the form
much easier to read.

you are here �

631

other form elements

What more could possibly go into a form?

We’ve covered just about everything you’ll regularly use in your forms, but there’s a few more elements you might want to consider adding to your form répertoire; so, we’re including them here just in case you want to take your own form studies even further.

Fieldsets and legends

When your forms start getting large, it can be helpful to visually group elements together. While you might use <div> s and CSS to do this, XHTML also provides a <fieldset> element that can be used to group together common elements. <fieldset> makes use of a second element, called <legend> . Here’s how they work together: The <fieldset> element surrounds a

The <legend> provides a
set of input elements.

label for the group.

Here’s how the fieldset

<fieldset>
and legend look in one

<legend>Condiments</legend>
browser. You’ll find

<input type=”checkbox” name=”spice” value=”salt” /> that browsers display

Salt <br />
them differently.

<input type=”checkbox” name=”spice” value=”pepper” /> Pepper <br />

<input type=”checkbox” name=”spice” value=”garlic” /> Garlic

</fieldset>

Labels

So far you’ve been labeling your form elements with simple text, but XHTML also provides a <label> element. This element provides further information about the structure of your page, allows you to style your labels using CSS more easily, and can even help screen Labels don’t look
readers for the visually impaired correctly identify form elements.

different from just
plain text, by default.

However, they can make

To use a <label> element, first add an
a big difference when it
id attribute to your form element.

comes to accessibility.

<input type=”radio” name=”hotornot” value=”hot” id=”hot” />

<label for=”hot”>hot</label>

You can use a <label>

<input type=”radio” name=”hotornot” value=”not” id=”not” /> element with any

<label for=”not”>not</label>

Then add a <label> and set its “for”

form element.

attribute to the corresponding id.

632

Chapter 14

xhtml forms

Passwords

The password <input> element works just like the text

<input> element, except that the text you type is masked. This is useful for forms that require you to type in a password, a secret code, or other sensitive information that you may not want other people to see as you type. Keep in mind, however, that the form data is not sent from the browser to the Web application in a secure way, unless you make it secure. For more on security, contact your hosting company.

The password <input> element works
exactly like the text <input> element,

<input type=”password” name=”secret” />
except the text you type is masked.

File input

Here’s a whole new input element we haven’t talked about. If you need to send an entire file to a Web application, you’ll once again use the <input> element, but this time set its type to

“file”. When you do that, the <input> element creates a control Here’s what the file input
that allows you to select a file and – when the form is submitted element looks like in a couple

– the contents of the file are sent with the rest of your form data of different browser
to the server. Remember, your Web application will need to s.

be expecting a file upload, and also note that you must use the POST method to use this element.

To create a file input element, just set the

<input type=”file” name=”doc” />
type of the <input> element to “file”.

Multiple selection

This isn’t a new element, but a new way to use an element you With multiple
already know. If you add the attribute
selection, y
multiple with a value
ou
of “multiple” to your
can choose mor

<select> element, you turn your single
e
choice menu into a multiple choice menu. Instead of a pop-than one option
down menu, you’ll get a multiple choice menu that shows all at a time.

the options on the screen (with a scrollbar if there are a lot of them); you can choose more than one by holding down the Ctrl (Windows) or Command (Mac) key as you select.

Just add the attribute

<select name=”characters” multiple=”multiple”>
multiple with a value of

<option value=”Buckaroo”>Buckaroo Banzai</option>

<option value=”Tommy”>Perfect Tommy</option>

“multiple” to turn a single

<option value=”Penny Priddy”>Penny</option> selection menu into a multiple

<option value=”New Jersey”>Jersey</option> selection menu.

<option value=”John Parker”>John</option>

</select>
you are here �

633

review of forms

BULLET POINTS

n

The <form> element defines the form, and all
n

A <textarea> element creates a multi-line text
form input elements are nested inside it.

input area.

n

The action attribute contains the URL of the
n

A <select> element creates a menu, which

Web Application.

contains one or more <option> elements.

<option> elements define the items in the

n

The method attribute contains the method of
sending the form data: either POST or GET.

menu.

n

If you put text into the content of a <textarea>

n

A POST packages form data and sends it as
part of the request.

element, it will become the default text in a
text area control on the Web page.

n

A GET packages form data and appends it to
the URL.

n

The value attribute in the text <input> element
can be used to give a single-line text input an
initial value.

n

Use POST when the form data should be
private, or when it is large, such as when a

<textarea> or file <input> element is used.

n

Setting the value attribute on a submit button
changes the text of the button.

n

Use GET for requests that might be
bookmarked.

n

When a Web form is submitted, the form data
values are paired with their corresponding
names, and all names and values are sent to

n

The <input> element can act as many different
input controls on the Web page, depending on
the server.

the value of its “type” attribute.

n

Tables are often used to layout forms, given
that forms have a tabular structure. Once laid

n

A type of “text” creates a single line text input.

out, CSS should be used to style forms to

n

A type of “submit” creates a submit button.

provide the presentation, including color, font
styles, etc.

n

A type of “radio” creates one radio button. All
radio buttons with the same name make up a
n

XHTML allows form elements to be organized
group of mutually exclusive buttons.

with the <fieldset> element.

n

A type of “checkbox” creates one checkbox
n

The <label> element can be used to attach
control. You can create a set of choices by
labels to form elements in a way that aids
giving multiple checkboxes the same name.

accessibility.

634

Chapter 14

xhtml forms

Markup Magnets Solution

Your job is to take the form element magnets and lay them
on top of the corresponding controls in the sketch. You won’t need all the magnets below to complete the job; some will
be left over. Here’s the solution.

<select>...</select>

House Blend

<option>...</option>

Shade Grown Bolivia Supremo<option>...</option> Organic Guatemala

<option>...</option>

<input type="radio" ... />

Kenya

<option>...</option>

<input type="radio" ... />

<input type="checkbox" ... />

<input type="checkbox" ... />

<input type="text" ... />

<input type="text" ... />

<input type="text" ... />

<input type="text" ... />

<input type="text" ... />

<textarea>...</textarea>

We didn’t
need these.

Submit

<input type="submit" ... />

<select>...</select>

<select>...</select>

<textarea>...</textarea>

<input type="radio" ... />

<input type="submit" ... />

<input type="checkbox" ... />

<input type="checkbox" ... />

<input type="text" ... />

<input type="text" ... />

<input type="text" ... />
you are here �

635

exercise solutions
name = _

“ _

Bu _
c _
ka _r_
o __
o Ba _
n _
za _i” _______

Exercise

Solutions
zip = _“____

90050 _

” _____________
model = _“_
co _
n _
ve _
r _
ti _
bl _
e” _________
color = _“c_h_
ili _
re_d_

” ___________
caroptions[] = _“_
st _
ri _
p _
es _

” ____

GET or POST

Sharpen your pencil

For each description, circle either GET or POST

Solution
depending on which method would be more
appropriate. If you think it could be either circle
both. But be prepard to defend your answers...

GET POST

A form for typing in a username and password.

GET POST

A form for ordering CDs.

GET POST

A form for looking up current events.

GET POST

A form to post book reviews.

GET POST

A form for retrieving benefits by your government ID number.

GET POST

A form to send customer feedback.

636

Chapter 14

xhtml forms

Hey, 80% of our customers
order “ground” beans. Can you
make it so the ground bean type

Exercise
is already selected when the

Solutions
user loads the page?

If you add an attribute checked with a value of “checked” into your radio input element, then that element will be selected by default when the form is displayed by the browser. Add the checked attribute to the “ground” radio input element and give the page a test. Here’s the solution.

Here’s just the form
section of “form.html”.

<form action=”http://www.starbuzzcoffee.com/processorder.php” method=”POST”>

<p> Choose your beans:

<select name=”beans”>

<option value=”House Blend”>House Blend</option>

<option value=”Bolivia”>Shade Grown Bolivia Supremo</option>

<option value=”Guatemala”>Organic Guatemala</option>

<option value=”Kenya”>Kenya</option>

And here’s the new attribute

</select>
that selects the “Ground”

</p>
radio button.

<p>Type: <br />

<input type=”radio” name=”beantype” value=”whole” /> Whole bean <br />

<input type=”radio” name=”beantype” value=”ground” checked=”checked” /> Ground

</p>

<p>Ship to: <br />

Name: <input type=”text” name=”name” /> <br />

Address: <input type=”text” name=”address” /> <br /> City: <input type=”text” name=”city” /> <br />

State: <input type=”text” name=”state” /> <br /> Zip: <input type=”text” name=”zip” /> <br />

<input type=”submit” value=”Order Now” />

</p>

</form>
you are here �

637

the end

Wouldn’t it be dreamy if
this were the end of the book?

If there were no bullet points
or puzzles or XHTML listings or
anything else? But that’s probably
just a fantasy...

Congratulations!

You made it to the end.

Of course, there’s still an appendix.

And the index.

And the colophon.

And then there’s the Web site...

There’s no escape, really.

638

Chapter 14

Appendix: leftovers

The Top Ten Topics

(we didn’t cover)

We covered a lot of ground, and you’re almost finished
with this book. We’ll miss you, but before we let you go, we wouldn’t feel right about sending you out into the world without a little more preparation. We can’t possibly fit everything you’ll need to know into this relatively small chapter.

Actually, we did originally include everything you need to know about XHTML and CSS (not already covered by the other chapters), by reducing the type point size to .00004. It all fit, but nobody could read it. So, we threw most of it away, and kept the best bits for this Top Ten appendix.

This really is the end of the book. Except for the index, of course (a must-read!).

this is a new chapter

639
specialized selectors

#1 More Selectors

While you’ve already learned the most common selectors, here are a few more you might want to know about...

Pseudo-elements

You know all about pseudo-classes, and pseudo-elements are similar. Pseudo-elements can be used to select parts of an element that you can’t conveniently wrap in a <div> or a <span> or select in other ways. For example, the first-letter pseudo-element can be used to select the first letter of the text in a block element, allowing you to create effects like initial caps and drop caps. There’s one other pseudo-element called first-line, which you can use to select the first line of a paragraph. Here’s how you’d use both to select the first letter and line of a <p> element: Pseudo-elements use the same
p:first-letter {
syntax as pseudo-cl

font-size: 3em;
asses.

}

p:first-line {

Here we’re making the first

font-style: italic;
letter of the paragraph large,

}

and the first line italics.

Attribute selectors

Attribute selectors are not currently well supported in current browsers; however, they could be more widely supported in the future. Attribute selectors are exactly what they sound like: selectors that allow you to select elements based on attribute values. You use them like this:

This selector selects all
images that have a width
attribute in their XHTML.

img[width] { border: black thin solid; }

img[height=”300”] { border: red thin solid; }

This selector selects all images
image[alt~=”flowers”] { border: #ccc thin solid; }

that have a height attribute
with a value of 300.

This selector selects all images
that have an alt attribute that
includes the word “flowers”.

640

Appendix
leftovers

Selecting by Siblings

You can also select elements based on their preceding sibling. For example, say you want to select only paragraphs that have an <h1> element preceding them, then you’d use this selector: Write the preceding element, a “+”

sign, and then the sibling element.

h1+p {

This selector selects all paragraphs that
font-style: italic;
come immediately after an <h1> element.

}

Combining Selectors

You’ve already seen examples of how selectors can be combined in this book. For instance, you can take a class selector and use it as part of a descendant selector, like this:

.blueberry p { color: purple; }

Here we’re selecting all paragraphs
that are descendants of an element
in the blueberry class.

There’s a pattern here that you can use to construct quite complex selectors. Let’s step through how this pattern works:

(1) Start by defining the context for the element you want to select, like this: Here we’re using a descendant selector
div#greentea > blockquote
where a <div> with an id “greentea” must
be the parent of the <blockquote>.

(2) Then supply the element you want to select:

Next we add the <p> element as the element
div#greentea > blockquote p
we want to select in the context of the

<blockquote>. The <p> element must be a
context
descendant of <blockquote>, which must be a
element
child of a <div> with an id of “greentea”.

(3) Then specify any pseudo-classes or pseudo-elements:

div#greentea > blockquote p:first-line { font-style: italic; }

context
element

Then we add a pseudo-element, first-line, to
select only the first line of the paragraph.

That’s a quite complex selector! Feel
free to construct your own selectors
using this same method.

you are here �

641
splitting your pages

#2 Frames

HTML allows you to divide a Web page into a set of frames, where each frame is capable of displaying one embedded Web page. You may have noticed pages with frames that allow you to visit a third party page while leaving the header and navigation of the original site intact. These days frames are, for the most part, considered “old school” because they cause navigation and usability problems, and they are not recommended by the W3C. However, you will still find them in use in some situations.

To create a set of frames in a page, use the <frameset> and <frame> elements: Creates a set of frames as three rows,
where the first frame takes up 30%

You can also specify framesets as columns
of the browser, the last part takes
up 20%, and the middle part takes up
of frames, or as rows and columns.

the remaining space.

For each frame we use a

<frameset rows=”30%, *, 20%”>

<frame> element. Each frame

<frame name=”header” src=”header.html” />
specifies a name for the

<frame name=”content” src=”content.html” />
frame and the sourc

<frame name=”footer” src=”footer.html” />
e HTML

</frameset>
file that goes in the frame.

You can also target individual names with your <a> elements by specifying the frame’s name in the target of the link, like this:

<a href=”newpage.html” target=”content”> new content</a> .

There is also a related element called an <iframe> that is widely supported in newer browsers.

The inline element <iframe> allows you to place a frame anywhere within a page. Here’s how you use <iframe> :

Creates an inline

<iframe name=”inlinecontent” src=”newcontent.html”

frame for the page
width=”500” height=”200” />

“newcontent.html”.

Finally, you should know that to use frames you’ll need to use a DOCTYPE in the page that contains the frameset. The frameset DOCTYPEs are considered to be transitional, so you can’t have frames and be strict. For HTML 4.01 use:

<!DOCTYPE html PUBLIC “-//W3C//DTD HTML 4.01 Frameset//EN”

“http://www.w3.org/TR/html4/frameset.dtd”> and for XHTML 1.0 use:

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Frameset//EN”

“http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd”> 642

Appendix
leftovers

#3 Multimedia & Flash

Browsers can play sounds and display videos or even interactive content like Flash applications in a Web page. HTML supports these types of media through an element called <object> that is responsible for embedding external content into your Web page (your page will also need the help of a plugin viewer that knows how to display the content).

We should mention the <object> element and a close cousin – the <embed> element – have never fully recovered from the browser wars, so using them is somewhat more complicated than it should be. If you’d like to include multimedia in your own pages, we encourage you to visit the Web site of the author of your media type and make sure you use their recommended settings.

While embedding multimedia is more complicated than it needs to be, don’t let that scare you off

– given how much you know about HTML, it won’t take you long to get your sounds, animations, and movies into your pages.

Here’s a simple example of embedding a Quicktime movie using an <object> element: Here’s the object opening tag. As you can see, it requires a lot of specialized tags and attributes to specify the
correct viewer to embed in the page.

<object classid=”clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B”

codebase=”http://www.apple.com/qtactivex/qtplugin.cab”

height=”200”

width=”300”>

You can nest object elements to

<param name=”src” value=”buckaroo.mov”>
provide a set of choices. If the

<param name=”autoplay” value=”true”>
browser can’t support the outer

<param name=”controller” value=”true”>

<object>, it tries the <embed>.

<embed height=”200”

width=”300”

src=”buckaroo.mov”

pluginspage=”http://www.apple.com/quicktime/download/”

type=”video/quicktime”

controller=”true”

autoplay=”true”>Sorry your browser does not support this movie type</embed>

</object>

The legacy <embed>
element is nested for
support of old browsers.

Embedding multimedia content into your pages can help to create a compelling and more immersive experience for your users, but specifying <object> elements can be a tricky business, so make sure you consult the viewer manufacturer’s documentation on how to embed their viewers into your pages.

you are here �

643
web tools

#4 Tools for Creating Web Pages

Now that you know XHTML and CSS you’re in a good position to decide if tools like Dreamweaver, GoLive, and FrontPage are for you. All these applications attempt to provide what-you-see-is-what-you-get (WYSIWYG) tools for creating Web pages. We’re sure you know enough about XHTML and browser support to know that this goal, while worthwhile, also comes up short from time to time. But, that said, these tools also provide some very handy features, even if you’re writing a lot of the XHTML yourself:

<script type=”text/javascript”>

n

A “code” window for entering XHTML and CSS with syntax
function validBid(form) {
checking to catch common mistakes and suggest common names
if (form.bid.value > 0) return true; and attributes as you type.

else return false;

}

n

A preview and publish functionality that allows you to test pages

</script>
before making them “live” on the Web.

n

A site manager that allows you to organize your site, and also keeps your local changes in synch with your Web site on the server.

Note that this usually takes care of all the FTP work for you.

These tools are also not without their downsides:

n

Often these tools lag behind standards in terms of support, so to keep your XHTML and CSS current – you’ll need to
write the XHTML yourself.

n

Often these tools don’t enforce strict standards, and may
allow you to get sloppy with your XHTML and CSS, so
don’t forget to validate (some tools help you validate as well).

Keep in mind you can use a combination of simple editors along with these more sophisticated tools; one solution doesn’t have to fit all your needs. So use a page creation tool when it makes sense.

Some tools to consider:

n

Macromedia Dreamweaver

n

Adobe GoLive

n

Microsoft FrontPage

n

GNU Emacs (open source)

644

Appendix
leftovers

#5 Client-side Scripting

HTML pages don’t have to be passive documents; they can also have content that is executable.

Executable content gives your pages behavior. You create executable content by writing programs or scripts using a scripting language. While there are a quite a few scripting languages that work with browsers, JavaScript is the reigning king. Here’s a little taste of what it means to put executable content into your pages.

Here’s a new HTML element,

<script type=”text/javascript”>

<script>, which allows you to write
function validBid(form) {
code right inside of HTML. Notice
if (form.bid.value > 0) return true; we’ve set the type to JavaScript.

else return false;

}

And here’s a bit of JavaScript script

</script>
that checks a user’s bid to make sure
it’s not zero dollars or less.

Then in XHTML, you can create a form that uses this script to check the bid before the form is submitted. If the bid is more than zero, the form gets submitted.

<form onsubmit=”return validBid(this);” method=”post” action=”contest.php”> Here’s a new attribute in the form
called onsubmit that invokes a script
when the submit button is pressed.

What else can scripting do?

As you see above, form input validation is a common and useful task that is often done with JavaScript (and the types of validation you can do go far beyond this example). But that’s just the beginning of what you can do with JavaScript. JavaScript actually has access to the entire document tree of elements (the same element tree you worked with in Chapter 3) and can programatically change values and elements in the tree. What does that mean? It means you can have a script change various aspects of your Web page based on a user’s actions. Here are a few things you might do with JavaScript:

n

Create an interactive game, like a crossword puzzle.

n

Dynamically change images as the user passes their
mouse over the image.

n

Set local information in the user’s browser so you can
remember them next time they visit.

n

Let users choose between different stylings of a page.

n

Display a random quote from a set of quotes.

n

Display the number of shopping days before Christmas.

you are here �

645

generating pages

#6 Server-side Scripting

Many Web pages aren’t created by hand, but are generated by Web applications running on a server. For example, think about an online order system where a server is generating pages as you step through the order process. Or, an online forum, where there’s a server generating pages based on forum messages that are stored in a database somewhere. We used a Web application to process the form you created in Chapter 14 for the Starbuzz Bean Machine.

Many hosting companies will let you create your own Web applications by writing server-side scripts and programs. Here’s a few things server-side scripting will allow you to do: n

Build an online store complete with products, a shopping cart, and an order system.

n

Personalize your pages for each user based on their preferences.

n

Deliver up to date news, events, and information.

n

Allow users to search your site directly.

n

Allow your users to help build the content of your site.

To create Web applications, you’ll need to know a server-side scripting or programming language. There are a lot of competing languages for Web development and you’re likely to get differing opinions on which language is best depending on who you ask. In fact, Web languages are a little like automobiles: you can drive anything from a Yugo to a Hummer, and each has its own strengths and weaknesses (cost, ease of use, size, economy, and so on).

Web languages are constantly evolving; PHP, Python, Perl, Ruby on Rails, and JavaServer Pages (JSPs) are all commonly used. If you’re new to programming, PHP may be the easiest language to start with, and there are millions of PHP-driven Web pages, so you’d be in good company. If you have some programming experience, you may want to try JSPs. If you’re more aligned with the Microsoft technologies, then you’ll want to look at VB.NET and ASP.NET as a server-side solution.

Here are a few books that can get you started:

A Brain-Friendly Guide

Head First

A Brain-Friendly Guide

2nd

Edition

New Mock Exam

PHP & MySQL

Head First Included

Serv

P
let
assing the Sun Certified W s & JSP
eb Component Developer Exam

TM

Load all the key
syntax directly

Test yourself
into your brain
with more than

200 realistic
exam questions

Updated to cover

Discover the secrets
the latest version of
behind dynamic,
the SCWCD exam
database-driven sites
for J2EE 1.4

Avoid

Hook up your
embarrassing

PHP and

Avoid deadly
mishaps with

MySQL code
traps & gotchas
web forms
on the 1.4 exam

Use c:out to get your
message to the world

Flex your scripting
knowledge with dozens
of exercises

Fool around
in the Custom

Learn how Ted improved his

Lynn Beighley & Michael Morrison

Tag Library
appeal with dynamic attributes

Bryan Basham, Kathy Sierra & Bert Bates

646

Appendix
leftovers

#7 Tuning for Search Engines

Many users will find your site through search engines (like Google and Yahoo!). In some cases you may not want your site to be listed in the search engine rankings, and you can use XHTML to request that they not be listed. But, in other cases, you’ll want to do everything you can to tune your site so it appears high in the rankings when particular terms are searched for. Here are some general tips for improving the search engine results for your pages. But keep in mind that every search engine works differently and each considers different factors when deciding the order of its rankings.

Improving your rankings

Search engines use a combination of the words and phrases in your pages in their search rankings.

To improve your rankings and help search engines determine what your page is about, start with two

<meta> tags in your <head> element: one to list keywords and the other to provide a description of your content. A keyword is a simple word or two that describes your site, like “coffee” or “travel journal”.

<meta name=”description” content=”This would be your description of what is on your page. Your most important keyword phrases should appear in this description.” />

<meta name=”keywords” content=”keyword phrase 1, keyword phrase 2, keyword phrase 3, etc.” />

Many search engines treat the words in your headings and the alt and title attributes with more weight than the rest of your text, so be sure to write concise and meaningful text in these elements and attributes.

Finally, many search engines factor in the number of links to your site from other sites; the more sites that link to you, the more important your site must be. So, anything you can do to encourage others to link to your site can improve your search engine rankings.

How do I keep my site from being listed?

You can request that search engines ignore your pages, but there is no guarantee that all of them will.

The only way to truly prevent others from finding your site is to make it private (discuss that with your hosting company). But if you want to request that your site not be listed, which works with most of the major search engines, just put a <meta> tag in the head of your XHTML, like this:

<meta name=”robots” content=”noindex,nofollow” />

This meta tag tells search engines
to ignore this page, and any other
pages on the same site that this
page happens to link to.

you are here �

647
better printing with css

#8 More about Style Sheets for Printing

As you saw in Chapter 10, you can use the media attribute of the <link> element to specify an alternative media type. If you specify a value of “print” in the media attribute of a style sheet, then that style sheet is used when your page is printed.

Here’s how you use the <link> element to do that:

<link rel=”stylesheet” type=”text/css” media=”print” href=”forprint.css” /> The media attribute on the link

Here’s the link to the print
element tells the browser that it
stylesheet. This won’t be used
should use this style sheet when it
when your Web page is viewed on
prints the Web page.

a monitor; it will only be used
when you use the browser to
print your Web page.

Then, as you’ve already seen, when a user visits your page and selects the browser’s print function, the browser applies the “forprint.css” style sheet before the page is printed. This allows you to style your pages so they are more appropriate for the printed page. Here are a few considerations to keep in mind when developing styles for print:

n

Change your background color to white for areas of printed text to make the text easier to read on the printed page.

n

You can specify font sizes in points rather than pixels, percentages, or ems in your print style sheet. Points are designed specifically for printed text. A typical point size for most fonts is 12pt.

n

While sans-serif fonts are easier to read on the screen, serif fonts are considered easier to read on the printed page. You can use your print style sheet to change the font-family too.

n

If you have navigation menus, sidebars, or other content around the main content of the page, you can hide those elements for the printed version of the page if they are not essential for understanding the main content. This can be done by setting the display property on any element to “none”.

n

If you have positioned elements in your Web page, you may want to consider removing the positioning properties so your page prints the content in a top-down manner that makes the most sense when reading the content.

n

If you have set specific widths for elements in your Web page, you might have to change those to flexible widths using margins or other methods. If your Web page has a specific width, then it may not fit properly on the printed page.

The key to making good print style sheets is to look at the primary content of the page, and make sure that this content prints clearly, fits on the printed page, and is easy to read. The best way to know if your Web page will look good when it’s printed out is to test your print style sheet by printing the page.

648

Appendix
leftovers

#9 Pages for Mobile Devices

Do you want your Web pages to be usable on mobile devices, like cell phones and personal digital assistants (PDAs)? If you do, then you need to keep some things in mind when creating your pages. While mobile devices are getting more sophisticated, their support for XHTML
and CSS still varies widely among the various devices. Some support CSS, some don’t; some display XHTML really well, others make a mess of it. The best thing you can do is anticipate potential problems and plan for the future when support will be better.

First, remember that you can write a “handheld” specific style sheet by using the media attribute of the <link> element.

<link rel=”stylesheet” type=”text/css” media=”handheld” href=”formobile.css” /> Unfortunately, support for the “handheld” style sheet media type is still limited, so To create a style
even if you’ve got a handheld style sheet link in your Web page, that doesn’t mean sheet for mobile
the browser on your phone will actually use it. So, you need to keep some general devices, use the media
design techniques in mind so your Web page looks good on both computer attribute with a
monitors and small devices:

value of “handheld”.

n

Remember that many mobile services still charge by the amount of data transmitted to the device. This is a good reason to write simple, correct XHTML and use CSS to style your Web pages.

n

Keep navigation simple and obvious. That means you should use text links and avoid special scripting effects that require a mouse and keyboard to use.

n

Scale down your page as much as you can. If you have a handheld style sheet, use it to reduce your font sizes, margins and padding as much as possible.

n

Keep in mind that your multi-column layouts will often be ignored on small devices, so pay careful attention to the ordering of elements in your XHTML.

n

Many mobile devices lack support for frames and pop-up windows, so avoid these.

n

Finally, the best solution is always to test your Web pages on as many devices as you can to know how they truly perform on small devices.

And while support may currently be limited, if you get in the habit now of writing alternative style sheets for the “handheld” media type, you’ll be well prepared for the future when there’s more support for them.

you are here �

649
better looking blogs

#10 Blogs

Weblogs – or “blogs” as they are commonly known – are like personal Web pages, except they are written in journal style, like Tony’s Web journal. Many people who create blogs use online services that take care of the details of managing the blog entries. These services also provide pre-made templates that allow you to pick from a variety of looks for your blog.

They offer different background colors, font styles, and even background images you can use.

But they also allow you to customize your blog template and create your own unique look for your blog, with, you guessed it – XHTML and CSS.

Here’s a snippet of XHTML and CSS from the blog template of a popular online blogging service, Blogger.com. As you can see, they’re using all the same elements and properties you’ve learned about in this book. And they’re even on top of the new standards: their templates use XHTML 1.0 Strict, so it’s a good thing you’ve learned how to write strict XHTML, right? Let’s take a closer look...

This blogging service uses XHTML 1.0

Strict, so here’s the DOCTYPE and

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Strict//EN”

<html> attributes you’ve seen before.

“http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en” lang=”en”> These <$...$>s are template variables; they are filled in with

<head>
the name of your blog and other content when you create

<title><$BlogPageTitle$></title>
your blog, and whenever you add a new post. You should
leave these variables like they are, as they’re needed to

<$BlogMetaData$>
correctly display your blog content.

<style type=”text/css”>

Here’s the top of the style sheet that gives your blog its look.

body {
margin: 0px;

This template is removing the margins and padding from the
padding: 0px;
body, giving the text a default color, putting an image in the text-align: center;
background of the page, and setting font properties.

color: #554;
background: #689C54 url(http://www.blogblog.com/dots_dark/bg_minidots.gif) top center repeat; font-family: “Lucida Grande”, lucida, helvetica, sans-serif; font-size: small;

}

There are lots more style rules here. Each style

.

rule controls things like the font used f

.

or your
blog entries, the headings, the color

.

s,... in other
words, a

</style>
ll the same stuff you’re used to styling now.

</head>

<body>

.

The XHTML contains all the parts you need for

.

your blog: headings, entries, dates, etc. Each

.

</body>
content area will also have a <$...$> variable for

</html>
plugging in the content from your post.

650

Appendix
h
g

Index g

Symbols
new window 157–159
rendering in browser 49–50
state 468–470

!important 477
strict HTML 4.01 254

#d2b48c (color in hex code) 32
target attribute 158–159

&amp; entity 114, 272
title attribute 149

& character 114, 272

(see also linking)

alt attribute 176, 237

&gt; entity 114
images 255

&lt; entity 114
anchors 151–155

.. (dot dot) notation 64, 65
finding 153

/* and */ 315
name 154

:8000 port 147
anti-aliasing 213

<!-- and --> (see comments)

ASP 646

< character 114
attributes 51–52

> character 114

Attributes Exposed 53

[ ] (square brackets) 617
order 155

{ } braces 331
required 255
selectors 640

A
supported 52

Attributes Exposed 53
absolute layout 526
versus floating layout 530–531

B
absolute paths 138–139
versus relative paths 139
background-color property 289, 367–368, 399
absolute positioning 519–526, 532, 542
tables 566
accessibility
background-image property 404–408, 447
alt attribute 176, 255
background-position property 406, 407
forms 632, 634
background-repeat property 406, 407, 447
linking 149, 161
background property 459
scaling fonts using pixels 355
backups 127
table summaries 557
backwards compatibility of XHTML with HTML 276
action attribute 596, 597

Behind the Scenes

<a> element 47–49
browsers and images 167–168
destination anchors 151–155
default pages 141
frames 642

HTML links 48–50
href attribute (see href attribute)

blink decoration 377
this is the index

651
the index
block elements
margins (see margins)

flow 488–489, 493–494, 542
padding (see padding)

strict HTML 4.01 253–254

<br> element 98–101, 145
versus inline elements 94–97

XHTML 1.0 Strict 275

<blockquote> element 89–92, 94

Browser Exposed 228
multiple paragraphs 92
browsers
nested 362
automatically resizing images 182
nesting <q> inside 92
choices 16
strict HTML 4.01 254
default sizes for keywords thin, medium, and

Blogger.com 650
thick 412
blogs 650
determining good design across various 358
body 23, 32
directories versus files 140

<body> element 23, 82–83
display 6
font size 358

<form> element 595
strict HTML 4.01 253
forms
border-bottom-color property 411

GET 620–621

POST 620–621
border-bottom-style property 411
text limitations 607
border-bottom-width property 411
headings, default sizes 358
border-bottom property 295, 296
how forms work 593
border-collapse property 564
images 166–168
border-color property 399, 411, 412

<img> element 166–168
border-left-color property 411
imperfect HTML 225
border-left-style property 411
links (see <a> element)

border-left-width property 411
opening HTML files 19
pixel dimensions 182
border-right-color property 411
quick overview 2–3
border-right-style property 411
resizing fonts 358
border-right-width property 411
standards compliant code 229
border-spacing property 562–563
tables 553

Internet Explorer 563

URLs 135–136
border-style property 399, 410, 412
border-top-color property 411

Bullet Points
border-top-style property 411

<a> element 69
border-top-width property 411
block elements 117
border-width property 399, 411
borders 424
border property 459, 560
content area 424

CSS properties 331
borders 391–396, 400–401, 410–412

<div> element 482
default sizes for keywords thin, medium,
fonts
and thick 412
color 379

<div> element 440
families 379
boxes, flow 488–497
size 379
box model 391–396
style 379
borders (see borders)

forms 634
content area (see content area)

FTP 161

652
index
the index
hex codes 379
color 363–376

HTML 4.01 261
background-color property 367–368

<img> element 214
hex codes 369–371
inline elements 117
shorthand 373

JPEG versus GIF 214
online color chart 373
layouts 542

Photoshop Elements, Color Picker 372
linking 69, 161
selecting good font color 373
lists 117, 581
specifying 366–368
margins 424
by hex value 369, 372
padding 424
by name 367
positioning 542
by rgb values 368, 372
pseudo-classes 482
specifying in CSS 32
relative paths 69
text 341

<span> element 482

Web-safe colors 373
style sheets 424

Web colors
tables 581
finding 372–373
tags 36
how they work 364–365

URLs 161
color property 292, 294, 343

W3C validator 261
colspan attribute 571
columns, spanning 568–571

C
comments 6

CSS comments 315
compliance 251
caption-side property 560
compliant HTML 229–230
cascading style sheets (see CSS)

conflicting properties 322–323
cd command (FTP) 132

Content-Type 240
cell phones 649
content area
cells

<div> element, width 442–446
border-collapse property 564
content attribute 240
border-spacing property 562–563
content versus style 34–35
characters (see special characters)

copyright symbol 114
checkboxes 599, 607, 615

CSS 285–340, 473–482
child elements 454
adding into XHTML 291
classes 317–321, 331
body 32
adding elements to 317
box model 391–396
adding style 399–415
classes 317–321, 331

Class Exposed 414–415

.classname 331
creating 399
color 32
creating selectors for 318, 320
comments 315
elements of multiple classes 321
font families 347
pseudo-classes 468–471, 482
how name came about 480

Class Exposed 414–415
id attribute 417

.classname 331
laying out forms
clear property 511, 542
tables versus CSS 624–625
closing tag 25, 26
precedence 479
properties (see properties (CSS))

you are here �

653
the index

CSS ( continued)

text-align property 447–449
using with XHTML 289, 290
width 442–446
validating 328–329
dividing pages into logical sections (see <div> element) versus HTML 32, 34–35

DOCTYPE 231, 240
versus XHTML 324–325
moving from transitional to strict 243–251

.css file 303

Transitional HTML 4.01 235–237
lounge.css file
tentatively valid HTML 4.01 Transitional 238
creating 304

Transitional XHTML 272
linking 305

XHTML 1.0 Strict 268

CSS Up Close
domain name
background-image property 406–407
hosting 127
background-position property 406
obtaining 128
background-repeat property 406
registration services 129

Cursive font family 345
versus Web site name 129

Cyberduck 134
why it’s called 129
dot dot (..) notation 64, 65

D
double quotes 86

Dreamweaver 16, 644
data transfer 127
default font 388

E
default pages 140–141
descendants 452–454
elements 25, 36
design
adding to classes 317
determining good design across various
attributes 29
browsers 358
block (see block elements)

Tony’s Journal 79–83
capitalization 251
destination anchors 151–155
empty 101
finding 153
strict HTML 4.01 254
name 154
floated 542
dir command (FTP) 133
inline 117
directories versus files in browsers 140
strict HTML 4.01 253–254
members of multiple classes 321

<div> element 432–457, 482
multiple selectors matching element 322
borders 440
nesting 109–111
descendants 452–454
pseudo-elements 640
float property 504–505
state 468–470
heading color 455
em, font size scaling factor 353
height 446
versus percentage (%) 358
id attribute 434

Emacs 644
labelling 434
line-height property 456

<embed> element 643
logical sections 433

<em> element 315
marking sections 434
empty elements 101
nested 436

<img> element 175
structure 436
strict HTML 4.01 254
style 435, 441, 447–449

XHTML 1.0 Strict 275
example files xxxiii

654
index
the index

F
folders
organizing files and folders 56–57
parent 65, 67, 69

Fantasy font family 345
root 65

Fetch 134
font-family property 294, 311–315, 342, 344–345, 350

<fieldset> element 632

CSS 347
files
font-size property 342
directories versus files in browsers 140
font-style property 361–362, 560
fixing broken images 66–67
font-weight property 343, 359–360
loading through forms 633
font property 460
organizing files and folders 56–65
fonts (see text, fonts)

separators 65
footer 501
updating file locations 58–65
clear property 511
fixing 527

Firefox 16
overlap problem 509
handling imperfect HTML 225
style 502

Fireside Chats
foreign characters 114
absolute positioning versus float positioning 530–531

<form> element 594–597
block elements versus inline elements 96
action attribute 596, 597
content versus style 34–35
adding 605

CSS versus XHTML 324–325
browsers 595

HTML versus XHTML 280–281

<fieldset> element 632

JPEG versus GIF 170–171
how <form> element works 596
laying out forms 624–625
how form element names work 606
transitional HTML 4.01 versus strict HTML 4.01 256–257

<input> element (see <input> element)

Five-Minute Mystery

<label> element 632

The Case of Brute Force versus Style 302

<legend> element 632

Solved 308

<option> element 601, 610

The Case of Relatives and Absolutes 148

<select> element (see <select> element)

Solved 156

<table> element 627–628

The Case of the Elements Separated at Birth 89

<textarea> element 600, 615

Solved 93

(see also forms)

fixed positioning 535–540
forms 591–638

Internet Explorer 535

[ ] (square brackets) and PHP 617

Flash 643
accessibility 632, 634
floated elements 542
browsers 595
floating layout 526
checkboxes 599, 607, 615
versus absolute layout 530–531
checkbox input 599
float property 488, 495–497
code example 594
center 512

GET 620–621
inline elements 513
how forms work 592

Starbuzz Coffee project, sidebar 504
in browsers 593

(see also flow)

laying out in tables 626
flow 488–497
and CSS 624–625
block elements 488–489, 493–494, 542
code 627–628
boxes 492–494
styling with CSS 630–631
inline elements 491–494, 542
loading files 633

(see also float property)

passwords 633
you are here �

655
the index
forms ( continued)

picking names for elements 607

H

POST 596, 620–621
radio buttons 599, 607, 612–613

<h1> element 22
submit button 607
style 294–296
submit input 598

(see also headings)

submitting 606

<h2> element 22
text input 598
style 294–296
text limitations 607

(see also headings)

what can go into 598–601
head 23

(see also <form> element)

<head> element 82–83

<frame> element 642
strict HTML 4.01 253
frames 642
header 500

<a> element 642
style 502

<iframe> element 642

Head First Lounge project

<frameset> element 642

Behind the Scenes 48–50

FrontPage 16, 644
directions.html 45
frozen layout 517, 542

<div> element 430–457

FTP 132–134, 161
borders 440
applications 134
elixirs page 438–439
cd command 132
heading color 455
connecting to server 132
style 441, 447–449
dir command 133
width 442–446
get command 133
elixir.html 45
mkdir command 133
fixing broken images 66–67
other protocols 147
float property 497
put command 132
images 46
pwd command 133
lounge.html 46

SFTP 134
editing 47
lounge folder 46

G
organizing files and folders 56–65
overview 44–45
source files 46

GET 620–621
headings 6, 22
get command (FTP) 133
adding style 294–296

GIF
color 455

JPEG photo versus GIF photo 175
default sizes 358
transparent 206–208
levels 6
versus JPEG 169–171, 214

<head> tag 23, 36

(see also images)

height attribute 177

GNU Emacs 644
height property 446

GoLive 16, 644
hex codes 32, 369–371

Google 647
shorthand 373
graphics (see images)

hosting 127–129
domain name 127
guide 127

656
index
the index
providers 127

HTTP protocol 137
renaming root folder 131
other protocols 147
href attribute 47–49
hypertext 43

.. (dot dot) notation 64
links (see <a> element)

Attributes Exposed 53
reference (see href attribute)

linking style sheet 305
relative paths 58–65
versus id attribute 155

I

HTML
attributes xxxii
id attribute 416–419
backwards compatibility of XHTML 276

CSS 417
comments 6

<div> element 434
converting to XHTML 272
versus href attribute 155

DOCTYPE 231

<iframe> element 642
elements xxxii
images 165–222
tag names xxxiii
accessibility 255
first look at code and display 4–5
adding multiple 193
history 226–227
alt attribute 255
imperfect 225
broken image icon 218
indentation of code 6
browsers 166–168
standard 230
and pixel dimensions 182
standards 52
automatically resizing images 182
tools for converting to XHTML 276
creating individual pages for each image 200
validators for HTML versus XHTML 277
determining URL 175
versions 226–230
fixing broken images 66–67
versus CSS 32, 34–35

GIF (see GIF)

versus proprietary document format 6

Head First Lounge project 46
versus XHTML 280–282

<img> element (see <img> element)

W3C validator 234, 236, 261

JPEG (see JPEG)

Web pages 2
linking directly to 203

HTML 4.01 Strict, converting to XHTML
links 55

Strict 1.0 274–275
logo

<html> element 82–83
adding to myPod Web page 211
strict HTML 4.01 253
creating 204–213

XHTML 272, 274
setting matte color 209–211
making links out of 201–203

HTML files 6

PNG 165, 175
first HTML file 22
positioning 528–529

Mac 12–13

PSD 204–205
opening in browser 19
resizing 181–190
saving in Notepad (Windows) 18

Photoshop Elements 184–190
viewing 16
width and height 177, 182

Windows 14–15
thumbnails 195–203

.html or .htm files 6
creating 196

<html> tag 23
creating folder for 195

HTML Up Close, <option> element 610
placement 198
http-equiv attribute 240
turning into links 199–203
transparent images 205–208
decisions 207
you are here �

657
the index
images ( continued)

users scrolling to see 182

J
which format to use 206

<img> element 26, 101, 173–177

JavaScript 645
adding multiple images 193

JavaServer Pages (JSPs) 646
alt attribute 176, 237
jello layout 518–519, 526, 542
browsers 166–168

JPEG
fixing broken images 66–67

JPEG photo versus GIF photo 175
linking images 55
linking directly to 203
nesting HTML problems 251
quality setting 190
src attribute 173–174
resizing in Photoshop Elements 185–190
width and height 177, 190
versus GIF 169–171, 214
imperfect HTML 225

(see also images)

indentation of code 6
index.html, as part of URL 141
index.html file 18, 24

L
inheritance 311–315, 322

<label> element 632
identifying 315
lang attribute 272, 274
overriding 314, 315
style 362
layouts
inline elements 117
absolute 526
float property 513
versus floating 530–531
flow 491–494, 542
floating 526
positioning 522
versus absolute 530–531
frozen 542
strict HTML 4.01 253–254
jello 518–519, 526, 542
versus block elements 94–97
liquid 542

<input> element 598–599, 608
liquid and frozen 517
type=“checkbox” 599, 607, 615
three-column 541
type=“file” 633
two-column 526
type=“password” 633

<legend> element 632
type=“radio” 599, 607, 612–613

<li> element 104–108
type=“submit” 598
type=“text” 598
strict HTML 4.01 254
versus <textarea> 607

(see also lists)

line-height property 389–390, 456, 460

Internet, quick overview 2
linebreaks 95

Internet Explorer 16

<br> element 98–101
border-spacing property 563

<link> element
double quotes 86
linking to style sheet file 305
fixed positioning 535
media attribute 422, 648
imperfect HTML 225
mobile devices 649
scaling font size in pixels 355
rel attribute 305

ISO-8859-1 character encoding 240, 261
style sheets 388
italics 361–362
linking
accessibility 149
adding titles 149

658
index
the index
destination anchors 151–155
margin property 402, 458–459
from html to style sheets 305
fixing two-column problem 508
grouping links and text into paragraph 145
margins 391–396, 402–403
images 55
collapsing 513
new window 157–159
right-side only 409
other Web sites 144–147
versus padding 396
relative paths 58–65
matching tags 25, 26
style sheets 388
media attribute 422

(see also <a> element)

mobile devices 649
liquid layout 517, 542
printing 648
list-style-image property 579
medium keyword 412
list-style-position property 580

<meta> tags
list-style-type property 578
and content descriptions 240
list items in strict HTML 4.01 254
improving rankings 647
lists 104–108, 117
validators 241
items 105
method attribute 594
list-style-image property 579
mkdir command (FTP) 133
list-style-position property 580
mobile devices 2, 649
list-style-type property 578
style sheets 422–423
margin-left property 579

Monospace font family 345
nested 108
multimedia 643
ordered 105, 108
myPod Fan Site project 178–213
style 580
padding-top property 579
adding multiple images 193
strict HTML 4.01 254
creating individual pages for each image 200
style 578–580
logo 204–213
text wrap 580
adding to Web page 211
unordered 105, 108
setting matte color 209–211
transparent images 205–208
logo 204–213
making links out of images 201–203
adding to myPod page 211
resizing images 181–190
setting matte color 209–211

Photoshop Elements 184–190
text softened 213
thumbnails 195–203
transparent images 205–208
creating 196
lounge.css file
creating folder for 195
creating 304
placement 198
linking 305–306
reworking HTML 197
turning into links 199–203

M

N

Mac
creating HTML file 12–13
nested lists 108

TextEdit 12–13
nested tables 572–576
margin-left property 447, 560, 579
overriding style 576
margin-right property 409, 560
nesting elements 109–111
nesting HTML problems 251
you are here �

659
the index

No Dumb Questions
element state 469

!important 477

<em> element 315
absolute path 139
empty elements 101, 175
absolute positioning 522
file separators 65

<a> element
floating center 512
linking text 55
float property, inline elements 513
anchors 155
font-family property 350
attributes 52
fonts, multiple words 350
order 155
font size
blink decoration 377
defining in <body> element 358
block elements 494
em versus percentage (%) 358

<blockquote> element 92, 255
not defining 358
border-spacing property 563
pixels (px) 358
borders 396
forms 607

<br> element 101
checkboxes 607
browsers 16
picking names for elements 607
automatically resizing images 182
radio buttons 607
display 6
submit button 607
pixel dimensions 182
text <input> versus <textarea> 607
resizing fonts 358
text limitations 607
capitalization or elements 251

GET 621
cascade 477
headings 6
child elements 454
levels 6
hosting company renaming root folder 131
closing tags 26
href attribute, versus id attribute 155
collapsing margins 513

HTML
color
comments 6
rgb values 368
files 6

Web-safe colors 373
indentation of code 6
compliance 251
standards 52
compliant HTML 230
versus CSS 32
content area 396
versus proprietary document format 6
converting HTML to XHTML 276
viewing files 16

CSS
id attribute 416, 419
body 32
images
comments 315
browsers and pixel dimensions 182
validating 329
determining URL 175
default pages 141
linking directly to 203
descendants 454
links 55
destination anchors 155
resizing with width and height 182
determining good design across various browsers 358
users scrolling to see 182

<div> element 437

<img> element 175
width 446
width and height 177, 190

DOCTYPE 240
inheritance
domain name 129
identifying 315
versus Web site name 129
overriding 315
dot dot (..) notation 65
inline elements 494
editing files on Web server 134
positioning 522
elements, attributes 29

ISO-8859-1 240

JPEG photo versus GIF photo 175

660
index
the index

JPEG quality setting 190
target attribute 158
launching new window 158
text, selecting good font color 373
linebreaks 95
text editors 16
lists 108
two-column property 512
list style 580
unordered lists 108
logo 213

URLs 139
margins 396
using CSS with XHTML 290

<meta> tag 240
validator messages 251
nested lists 108
validators for HTML versus XHTML 277
nesting HTML problems 251

Web sites 139
number of style rules 297

XHTML 276

<option> element 607
xmlns attribute 276
ordered lists 108

Notepad (Windows) 14–15
organizing files and folders 57
saving HTML files 18
padding 396
parent folder 65

<p> element, style 290

O

PNG 175
ports 147

<object> element 643
position property 522

<ol> element 105, 108

POST 621
onsubmit attribute 645
precedence 479
opening tag 25
properties (CSS) 290
attributes 36
protocols 139, 147

Opera 16

<q> element 92

<option> element 601, 607
quotes 92
ordered lists 105, 108
relative paths versus URLs 147
style 580
required attributes 255
organizing files and folders 56–65
root folder 65, 131
outlines, Tony’s Journal 79–83
serif and sans-serif fonts 350

SFTP 134
shorthand properties 461

P

<span> element 466
special characters 115
padding 391–396, 401–402
specificity 477, 479
left-side only 408
standard HTML 230
versus margins 396
strict HTML 4.01 255
padding-bottom property 447
style sheets 421
padding-left property 408, 447
links to 479
tables 555
padding-right property 447
border-spacing property 563
padding-top property 560, 579
spanning columns 571
padding property 401, 458, 560
tags 6
pages, dividing into logical sections (see <div> element) matching 26

<p> and </p> tags 22
nested 26
paragraphs, setting color 289, 292
not matching 26
shorthand notation 26
parent folder 65, 67, 69
you are here �

661
the index
passwords in forms 633
border 560

PDAs 2, 649
border-bottom 295, 296

<p> element
border-bottom-color 411
setting color 289, 292
border-bottom-style 411
style 290
border-bottom-width 411
percentage (%) 352
border-collapse 564
versus em 358
border-color 399, 412

Perl 646
border-color property 411
border-left-color 411
photos (see images; JPEG)

border-left-style 411

Photoshop Elements 184–190
border-left-width 411

Color Picker 209, 372
border-right-color 411
setting matte color 209–211
border-right-style 411
transparent images 205–208
border-right-width 411

PHP 646
border-spacing 562–563
pictures (see images)

border-style 399, 410, 412
pixels (px) 352, 358
border-top-color 411
accessibility 355
border-top-style 411

PNG 175
border-top-width 411

(see also images)

border-width 399, 411
positioning
caption-side 560
absolute 519–526, 532, 542
clear 511, 542
fixed 535–540, 542
color 292, 294, 343
float versus absolute 530–531
conflicting 322–323
negative property values 537
float (see float property)

relative 539, 542
font 460
static 540, 542
font-family (see font-family property)

(see also layouts)

font-size 342
position property 520–540
font-style 361–362, 560
absolute 520–524, 542
font-weight 343, 359
fixed 535–540, 542
height 446
relative 539, 542
line-height 389–390, 456, 460
static 542
list-style-image 579

POST 596, 620–621
list-style-position 580
precedence 479
list-style-type 578
margin 402
presentation 28–32, 87
margin-left 447, 560, 579
printing, style sheets 648
margin-right 409, 560
properties (CSS) xxxii, 290
negative values 537

!important 477
padding 401, 560

{ } braces 331
padding-bottom 447
background-color 367–368, 399
padding-left 408, 447
tables 566
padding-right 447
background-color property 289
padding-top
background-image 404–408, 447
lists 579
background-position 407
tables 560
background-repeat 407, 447
position (see position property)

662
index
the index
shorthand 458–461
rows
background 459
color 566
border 459
spanning rows and columns 568–571
font 460
rowspan attribute 569
margin 458–459

Ruby on Rails 646
padding 458
text-align 447–449
text-decoration 343, 375–378

S
removing 378
width, <div> element 442–446

Safari 16
proprietary document format 6
sans-serif font family 344, 350
protocols 147
screen magnifiers 2

PSD 204–205

<script> element 645

(see also images)

pseudo-classes 468–471, 482, 640–641
scripting

Pseudo-class Exposed 470
client-side 645
server-side 646
pseudo-elements 640
search engine tuning 647
put command (FTP) 132
search rankings 647
pwd command (FTP) 133

<select> element 601, 609–611

Python 646
multiple options 633

Q
selectors 297–301, 640–641
attribute selectors 640
combining 641

<q> element 86–87, 89, 92, 94
creating for classes 318, 320
nesting inside <blockquote> 92
multiple matching element 322

Quicktime movie, embedding 643
pseudo-elements 640
quotes 86–94
siblings 641
serif font family 344, 350

(see also <blockquote> element; <q> element)

SFTP (Secure File Transfer Protocol) 134

R
shorthand properties 458–461
background 459
border 459
radio buttons 599, 607, 612–613
font 460
rankings (search) 647
margin 458–459
registration services for domain names 129
padding 458
relative paths 60–65, 69, 145
siblings, selecting 641

.. (dot dot) notation 64, 65
sidebar 501
fixing broken images 66–67
floating 504
versus absolute paths 139
margin property, fixing two-column problem 508
versus URLs 147
style 502
relative positioning 539, 542
two-column problem 506–508
rel attribute 305

Smart FTP 134
relocating files 60–65

<span> element 464–466, 482
rgb values 368
setting properties 466
root folder 65, 131
style 465
when to use 466
you are here �

663
the index
spanning rows and columns 568–571
moving files to web server 130–135
special characters 114–115

FTP 132–134

&amp; entity 114
root folder 131

& character 114
presentation 28–32

&gt; entity 114
setting up Web site online 126–164

&lt; entity 114
sidebar 501

< character 114
floating 504
margin property 508

> character 114
style 502
copyright symbol 114
two-column problem 506–508
specificity and CSS 476–477, 479
style 502–503
speech browsers 2

Web page overview 11
square brackets 617
static positioning 540, 542
src attribute 173–174
strict.dtd file 246
standards (HTML) 52
strict HTML 4.01
adhering to 261

<a> element 254
compliant code 229–230
block elements 253–254

Starbuzz Coffee project 9–42, 498–541

<blockquote> element 254
absolute positioning 519–526
empty elements 254
adding CSS to 30–31
guide 253–254
code before next changes 500–501

<head> element 253
creating folder 18

<html> element 253
default page 141
inline elements 253–254
destination anchors 151–155

<li> element 254
domain name 127
list items 254
first HTML file 22
transitioning to 243–251
fixed positioning 535–540
versus transitional HTML 4.01 256–257
floating main content left 514–516
structure 20, 23, 25
footer 501

<div> element 436
clear property 511

<style> element 29, 36, 291
fixing 527
text/css type 29
overlap problem 509
styles
style 502
forms 604–606
applying 322

<input> element 608–609
inheritance 311–315, 322

<select> element 609–611
overriding 314, 315
checkboxes and textarea 615–616
number of style rules 297
radio buttons 612–613
tagging items 87
header 500
versus content 34–35
style 502

(see also style sheets)

hosting 127–129
style sheets 349, 388, 420–424
guide 127
creating style file 303
images, positioning 528–529

<link> element, media attribute 422
index.html file 18, 24
linking from html files 306
linking to other Web pages 144–147
links to 479
main 500–501
lounge.css file
style 502
creating 304
linking 305–306

664
index
the index
mobile devices 422–423
rows 551
multiple 421
color 566
order 421
spanning rows and columns 568–571
printing 648
style sheets 560
tables 560
summaries 557–558
submit button 607

(see also <table> element)

symbols 114
tag names xxxiii
tags 6

T
closing 25, 26
how they work 25
matching 25, 26

<table> element 551–559
nested 26
captions and summaries 557–558
not matching 26

<form> element 627–628
opening 25
nested 573
attributes 36

<td> element 552–555
shorthand notation 26
colspan attribute 571

XHTML 272
rowspan attribute 569
target attribute 158–159

<th> element 552–555

Target Attribute Exposed 159

<tr> element 552–555

<td> element 552–555

(see also tables)

colspan attribute 571
tables 551–576
rowspan attribute 569
accessibility 557
tentatively valid HTML 4.01 Transitional 238
background-color property 566
text 341–384
border property 560
browsers, resizing fonts 358
browsers 553
color property 343
caption-side property 560
default font 388
captions 557–558
font-family property 342, 344–345, 350
captions and summaries
font-size property 342
font-style property 560
padding-top property 560
font-style property 361–362
cells 551
font-weight property 343, 359–360
border-collapse property 564
font families 344–345
border-spacing property 562–563

CSS 347
color 566

Cursive family 345
columns 551

Fantasy family 345
spanning rows and columns 568–571

Monospace family 345
headings 551, 555
sans-serif family 344
serif family 344
laying out forms 624–625
fonts
code 627–628
control over 351
decisions 626
customizing 342
styling with CSS 630–631
multiple words 350
margin-left property 560
selecting good font color 373
margin-right property 560
font size 342, 352–358
nested 572–576
default sizes of heading 358
overriding style 576
defining in <body> element 358
padding property 560
determining good design across various browsers 358
you are here �

665
the index
text, font size ( continued)

style sheets 349
em 353
tables and lists 559–581
em versus percentage (%) 358

(see also lists; tables)

keywords 354
text-decoration property 377
not defining 358
transitional HTML 4.01 235–237
percentage (%) 352
tentatively valid HTML 4.01 Transitional 238
pixels (px) 352, 358
versus strict HTML 4.01 256–257
specifying 354–355

Transitional XHTML 272

Tony’s Segway Journal 356–357
italics 361–362

Transmit 134
line-height property 389–390
transparent images 205–208
overview 342–343

<tr> element 552–555
scaling 355
two-column layouts 526
slanted 361–362
style sheets 349
text-decoration property 343, 375–378

U
removing 378
text-align property 447–449

Unicode characters 114
text-decoration property 343, 375–378
unordered lists 105, 108
removing 378

URLs 135–136, 161

<textarea> element 600, 615

:8000 port 147
versus text <input> 607
absolute path 138–139

TextEdit (Mac) 12–13
determining URL of image 175
text editors 16
directories versus files in browsers 140

Notepad (Windows) 14–15

HTTP protocol 137

TextEdit (Mac) 12–13
index.html 141

<th> element 552–555
versus relative paths 147
thick keyword 412
thin keyword 412

V
three-column layouts 541
thumbnails 195–203
validators
creating 196

CSS 328–329
creating folder for 195

HTML versus XHTML 277
creating individual pages for each image 200
messages 251
making links out of images 201–203

<meta> tags 241
placement 198

W3C 234, 236, 261
reworking HTML 197

VB.NET 646
turning into links 199–203

Tidy 276
title attribute 149

W

<title> element, strict HTML 4.01 253

W3C (World Wide Web Consortium) 233

Tony’s Segway Journal 79–124

W3C validator 234, 236, 261
font-weight property 360

Watch it!

font families 348–350
font size 356–357
default sizes for keywords thin, medium, and thick 412
orange and underlined headings 375–376
image size in browser 181
rough sketch 79–83

Internet Explorer
fixed positioning 535

666
index
scaling font size in pixels 355
the index
positioning 532
windows, launching new 157–159
fixed 535

World Wide Web Consortium (W3C) 233

<q> element 86

WS_FTP 134
text scaling 355

WYSIWYG 644

W3C validator 236

Web-safe colors 373

Web browsers (see browsers)

X
weblogs 650

Web pages

XHTML
ignoring (search engines) 647
adding CSS 291
linking to other 144–147
backwards compatibility with HTML 276
quick overview 2
forms (see forms)

rankings 647

<style> element (see <style> element)

tools 644
tools for converting HTML to XHTML 276

Web servers 3
using with CSS 289, 290
editing files on 134
validators for HTML versus XHTML 277
moving files to web server 130–135
versus CSS 324–325

FTP 132–134
versus HTML 280–282
root folder 131
why bother using 279

Web sites

XHTML 1.0 227, 266
absolute path 138–139

&amp; entity 272
backups 127

<html> element 272
data transfer 127
benefits 270–271
default pages 140–141
converting from HTML 272
directories versus files in browsers 140
overview 265–284
domain name 127
tags 272
obtaining 128

XML 269
registration services 129

XHTML 1.0 Strict 268
versus Web site name 129

<br> element 275
why it’s called 129
converting to 273
hosting 127–129

HTML 4.01 Strict 274–275
guide 127
empty tags 275
providers 127

<html> element 274
hosting company renaming root folder 131

HTTP protocol 137

XHTML UP Close
linking to other 144–147
moving files to web server 130–135

<link> element 305

FTP 132–134

XML 267
root folder 131
using to recreate HTML 268

URLs 135–136

XHTML 269

Webville Guide to Strict HTML 4.01 253–254
xml:lang attribute 272, 274
width attribute 177
xmlns attribute 272, 274, 276
width property

<div> element 442–446

Y

Windows
creating HTML files 14–15

Yahoo! 647

Notepad 14–15
saving HTML files 18
you are here �

667

Document Outline

- Table of Contents
- Intro: how to use this book
- Chapter 1: getting to know HTML
- Chapter 2: going further, with hypertext
- Chapter 3: building blocks
- Chapter 4: getting connected
- Chapter 5: adding images to your pages

- Chapter 6: standards, compliance, and all that jazz

- Chapter 7: moving to XHTML
- Chapter 8: getting started with CSS
- Chapter 9: styling with fonts and colors
- Chapter 10: the box model
- Chapter 11: divs and spans
- Chapter 12: layout and positioning
- Chapter 13: tables and more lists
- Chapter 14: xhtml forms
- Appendix: leftovers
- Index

Table of Contents

- Table of Contents
- Intro: how to use this book
- Chapter 1: getting to know HTML
- Chapter 2: going further, with hypertext
- Chapter 3: building blocks
- Chapter 4: getting connected
- Chapter 5: adding images to your pages

- Chapter 6: standards, compliance, and all that jazz

- Chapter 7: moving to XHTML
- Chapter 8: getting started with CSS
- Chapter 9: styling with fonts and colors
- Chapter 10: the box model
- Chapter 11: divs and spans
- Chapter 12: layout and positioning
- Chapter 13: tables and more lists
- Chapter 14: xhtml forms
- Appendix: leftovers
- Index