Programacion HTML5 CC3 and JS
Programacion HTML5 CC3 and JS
Programacion HTML5 CC3 and JS
Page 1 of 654
Making Images Smaller...................................................................................................... 102
Creating Transparency....................................................................................................... 103
Saving Images with Transparency.................................................................................... 105
Simulating Transparency ................................................................................................... 107
Using (Mostly) Browser Safe Colors ................................................................................. 109
Reducing the Number of Colors........................................................................................ 113
Showing Images Progressively ......................................................................................... 114
Blurring Images to Aid JPEG Compression...................................................................... 115
Creating Animated GIFs..................................................................................................... 117
CHAPTER 6. USING I MAGES ....................................................................................................... 120
Inserting Images on a Page............................................................................................... 120
Offering Alternate Text ....................................................................................................... 122
Specifying Size for Speedier Viewing............................................................................... 124
Scaling an Image................................................................................................................ 127
Linking Thumbnails to Images........................................................................................... 130
Making Images Float.......................................................................................................... 132
Stopping Elements from Wrapping.................................................................................... 135
Adding Space around an Image........................................................................................ 137
Aligning Images .................................................................................................................. 139
Adding Horizontal Rules..................................................................................................... 140
CHAPTER 7. LINKS ..................................................................................................................... 143
Creating a Link to Another Web Page .............................................................................. 144
Creating Anchors................................................................................................................ 147
Linking to a Specific Anchor .............................................................................................. 149
Targeting Links to Specific Windows ................................................................................ 150
Setting the Default Target.................................................................................................. 152
Creating Other Kinds of Links............................................................................................ 154
Creating Keyboard Shortcuts for Links............................................................................. 157
Setting the Tab Order for Links ......................................................................................... 159
Using Images to Label Links.............................................................................................. 160
Dividing an Image into Clickable Regions........................................................................ 162
Creating a Client-Side Image Map.................................................................................... 164
Using a Server-Side Image Map....................................................................................... 167
CHAPTER 8. CREATING STYLES ................................................................................................. 169
Constructing a Style Rule .................................................................................................. 169
Constructing Selectors....................................................................................................... 170
Selecting Elements by Name............................................................................................. 172
Selecting Elements by Class or ID.................................................................................... 173
Selecting Elements by Context.......................................................................................... 175
Selecting Link Elements Based on Their State................................................................ 180
Selecting Part of an Element............................................................................................. 182
Selecting Elements Based on Attributes........................................................................... 185
Specifying Groups of Elements......................................................................................... 187
Combining Selectors .......................................................................................................... 189
CHAPTER 9. APPLYING STYLES ................................................................................................. 190
Creating an External Style Sheet...................................................................................... 190
Linking External Style Sheets............................................................................................ 192
Offering Alternate Style Sheets ......................................................................................... 193
Creating an Internal Style Sheet ....................................................................................... 195
Importing External Style Sheets........................................................................................ 196
Applying Styles Locally ...................................................................................................... 198
The Importance of Location............................................................................................... 199
Adding Comments to Style Rules...................................................................................... 201
CHAPTER 10. FORMATTING W ITH STYLES ................................................................................. 202
Choosing a Font Family..................................................................................................... 203
Embedding Fonts on a Page............................................................................................. 204
Creating Italics .................................................................................................................... 206
Applying Bold Formatting................................................................................................... 207
Setting the Font Size .......................................................................................................... 208
Setting the Line Height....................................................................................................... 213
Page 2 of 654
Setting All Font Values at Once......................................................................................... 215
Setting the Text Color......................................................................................................... 217
Changing the Text's Background ...................................................................................... 218
Controlling Spacing ............................................................................................................ 220
Adding Indents.................................................................................................................... 223
Setting White Space Properties......................................................................................... 225
Aligning Text ....................................................................................................................... 227
Changing the Text Case .................................................................................................... 228
Using Small Caps............................................................................................................... 230
Decorating Text .................................................................................................................. 232
CHAPTER 11. LAYOUT WITH STYLES .......................................................................................... 235
Structuring Your Pages...................................................................................................... 236
The Box Model.................................................................................................................... 237
Displaying and Hiding Elements........................................................................................ 239
Positioning Elements Absolutely....................................................................................... 240
Affixing an Element to the Browser Window..................................................................... 242
Offsetting Elements In the Natural Flow ........................................................................... 244
Changing the Background ................................................................................................. 245
Changing the Foreground Color........................................................................................ 249
Changing the Cursor .......................................................................................................... 251
Setting the Border............................................................................................................... 252
Adding Padding around an Element................................................................................. 256
Setting the Margins around an Element ........................................................................... 258
Setting the Height or Width for an Element ...................................................................... 259
Positioning Elements in 3D................................................................................................ 263
Determining Where Overflow Should Go.......................................................................... 264
Making Elements Float....................................................................................................... 266
Controlling Where Elements Float..................................................................................... 268
Aligning Elements Vertically .............................................................................................. 269
CHAPTER 12. STYLE SHEETS FOR PRINTING ............................................................................. 272
Using Media-Specific Style Sheets................................................................................... 272
How Print Style Sheets Differ ......................................................................................... 273
Controlling Page Breaks ................................................................................................. 275
Other Print Specific CSS Properties ................................................................................. 277
CHAPTER 13. LISTS ................................................................................................................... 280
Creating Ordered and Unordered Lists............................................................................. 280
Choosing Your Markers (Bullets) .................................................................................. 283
Choosing Where to Start List Numbering .................................................................... 284
Using Custom Markers.................................................................................................... 286
Controlling Where Markers Hang...................................................................................... 288
Setting All List-Style Properties at Once........................................................................... 289
Creating Definition Lists..................................................................................................... 291
Styling Nested Lists ......................................................................................................... 293
CHAPTER 14. TABLES ................................................................................................................ 296
Mapping Out Your Page..................................................................................................... 297
Creating a Simple Table..................................................................................................... 298
Adding a Border.................................................................................................................. 301
Setting the Width ................................................................................................................ 304
Centering a Table on the Page....................................................................................... 308
Wrapping Text around a Table.......................................................................................... 309
Combining Tables............................................................................................................... 311
Aligning a Cell's Contents.................................................................................................. 314
Changing the Background ................................................................................................. 317
Controlling the Space......................................................................................................... 321
Spanning a Cell across Columns .................................................................................. 326
Spanning a Cell across Rows ........................................................................................ 328
Dividing Your Table into Column Groups......................................................................... 329
Dividing the Table into Horizontal Sections ................................................................ 333
Choosing Which Borders to Display.................................................................................. 335
Controlling Line Breaks in a Cell................................................................................... 338
Page 3 of 654
Speeding up Table Display................................................................................................ 339
CHAPTER 15. FRAMES .............................................................................................................. 340
Creating a Simple Frameset.............................................................................................. 340
Creating Frames in Columns............................................................................................. 345
Creating Frames in Rows and Columns........................................................................... 347
Combining Framesets........................................................................................................ 349
Creating an Inline Frame.................................................................................................... 351
Adjusting a Frame's Margins ............................................................................................. 353
Showing or Hiding Scroll Bars....................................................................................... 355
Adjusting the Color of the Borders ............................................................................... 357
Adjusting the Frame Borders......................................................................................... 360
Keeping Visitors from Resizing Frames....................................................................... 364
Targeting Links to Particular Frames................................................................................ 366
Targeting Links to Special Spots....................................................................................... 369
Changing the Default Target .......................................................................................... 371
Nesting Framesets ............................................................................................................. 372
Offering Alternatives to Frames......................................................................................... 373
Embedding Content with Objects...................................................................................... 377
Making Frames More Accessible ...................................................................................... 379
CHAPTER 16. FORMS ................................................................................................................ 380
About CGI Scripts............................................................................................................... 380
Getting a Script ................................................................................................................... 383
Using the Scripts Included with This Book........................................................................ 385
Preparing a Script............................................................................................................... 386
Creating a Form ................................................................................................................ 386
Sending Form Data via E-mail........................................................................................... 388
Using a Form Hosting Service........................................................................................... 390
Creating Text Boxes......................................................................................................... 393
Creating Password Boxes .............................................................................................. 395
Creating Radio Buttons................................................................................................... 397
Creating Checkboxes ...................................................................................................... 399
Creating Menus................................................................................................................. 401
Creating Larger Text Areas............................................................................................. 405
Allowing Visitors to Upload Files....................................................................................... 407
About Hidden Fields........................................................................................................... 408
Adding Hidden Fields to a Form .................................................................................... 409
Creating the Submit Button................................................................................................ 409
Resetting the Form............................................................................................................. 413
Using an Image to Submit Data......................................................................................... 416
Organizing the Form Elements ...................................................................................... 418
Formally Labeling Form Parts........................................................................................ 420
Setting the Tab Order in a Form .................................................................................... 421
Adding Keyboard Shortcuts............................................................................................... 423
Disabling Form Elements................................................................................................... 424
Keeping Elements from Being Changed........................................................................... 426
CHAPTER 17. MULTIMEDIA ........................................................................................................ 429
Of Plugins and Players....................................................................................................... 429
Getting Players for Your Visitors ....................................................................................... 433
Getting Multimedia Files..................................................................................................... 435
Embedding QuickTime Movies.......................................................................................... 435
Scaling a QuickTime Movie ............................................................................................... 440
Looping a QuickTime Movie.............................................................................................. 442
Putting QuickTime Sounds on a Page.............................................................................. 443
Hiding QuickTime Sounds ................................................................................................. 444
Embedding Windows Media Player Files ..................................................................... 445
Inserting Java Applets........................................................................................................ 450
Embedding Other Multimedia Files................................................................................... 452
Linking to Multimedia Files................................................................................................. 454
Creating an Automatic Slide Show.................................................................................... 455
Creating a Marquee.......................................................................................................... 457
Page 4 of 654
Adding Background Sound ............................................................................................ 458
CHAPTER 18. SCRIPTS .............................................................................................................. 458
Adding an "Automatic" Script........................................................................................ 458
Calling an External Automatic Script................................................................................. 460
Triggering a Script .............................................................................................................. 461
Creating a Button that Executes a Script.......................................................................... 463
Adding Alternate Information............................................................................................. 465
Hiding Scripts from Older Browsers.................................................................................. 467
Hiding Scripts from XML Parsers ...................................................................................... 469
Setting the Default Scripting Language ....................................................................... 470
CHAPTER 19. JAVASCRIPT ESSENTIALS ..................................................................................... 471
Adding the Current Date and Time ................................................................................... 471
Changing a Link's Status Label......................................................................................... 473
Changing Multiple Frames with One Link......................................................................... 475
Keeping Frames in Their Framesets................................................................................. 477
Changing an Image When a Visitor Points....................................................................... 479
Loading Images into Cache............................................................................................... 481
Controlling a New Window's Size...................................................................................... 484
CHAPTER 20. SYMBOLS AND NON-ENGLISH CHARACTERS ........................................................ 484
About Character Encodings............................................................................................... 485
Saving Your Page with the Proper Encoding................................................................... 488
Editing a Page with the Proper Encoding .................................................................... 490
Declaring Your Page's Character Encoding..................................................................... 493
Adding Characters from Outside the Encoding................................................................ 496
Specifying Your Page's Language.................................................................................... 499
CHAPTER 21. FORMATTING: THE OLD W AY............................................................................... 500
Choosing Default Characteristics for Text........................................................................ 500
Formatting Bits of Text ....................................................................................................... 505
Another Way to Choose Default Colors............................................................................ 509
Changing the Color of Links .............................................................................................. 510
Striking Out or Underlining Text ........................................................................................ 512
Making Text Blink............................................................................................................. 514
CHAPTER 22. LAYOUT : THE OLD W AY....................................................................................... 514
Using Background Color.................................................................................................... 515
Using Background Images................................................................................................. 516
Centering Elements on a Page.......................................................................................... 518
Specifying the Margins....................................................................................................... 519
Keeping Lines Together..................................................................................................... 521
Creating Discretionary Line Breaks................................................................................... 522
Specifying the Space Between Paragraphs................................................................. 524
Creating Indents ................................................................................................................. 526
Creating Indents (with Lists).............................................................................................. 527
Creating Blocks of Space................................................................................................... 529
Using Pixel Shims............................................................................................................... 531
Creating Columns............................................................................................................... 533
Positioning Elements with Layers...................................................................................... 535
CHAPTER 23. WML: WEB PAGES FOR MOBILE DEVICES.......................................................... 538
Preparing Your Server..................................................................................................... 539
Starting Your WML Page ................................................................................................... 540
Creating a Card................................................................................................................. 541
Creating Basic Content...................................................................................................... 543
Including an Image ............................................................................................................. 544
Creating a Table................................................................................................................ 546
Creating a Link.................................................................................................................. 548
Programming Buttons ..................................................................................................... 551
Creating Conditional Actions ............................................................................................. 553
Scheduling an Action ...................................................................................................... 555
Making a Call ...................................................................................................................... 556
Setting and Using Variables .............................................................................................. 558
Creating Input Boxes ....................................................................................................... 559
Page 5 of 654
Creating Menus .................................................................................................................. 562
Processing Data from Visitors ........................................................................................... 565
Creating Elements on Multiple Pages........................................................................... 568
Restricting Access to a Deck............................................................................................. 570
Testing WML Pages........................................................................................................... 571
CHAPTER 24. TESTING AND DEBUGGING W EB PAGES ............................................................... 574
Validating Your Code ......................................................................................................... 574
Checking the Easy Stuff: HTML ........................................................................................ 576
Checking the Easy Stuff: XHTML...................................................................................... 576
Checking the Easy Stuff: CSS........................................................................................... 577
Testing Your Page.............................................................................................................. 579
When the Browser Displays the Code.............................................................................. 581
When Images Don't Appear............................................................................................... 582
Differences from Browser to Browser ............................................................................... 584
When Nothing Appears in Netscape 4.............................................................................. 586
Still Stuck? .......................................................................................................................... 587
CHAPTER 25. PUBLISHING YOUR PAGES ON THE W EB .............................................................. 589
Finding a Host for Your Site............................................................................................... 589
Getting Your Own Domain Name...................................................................................... 589
Transferring Files to the Server......................................................................................... 591
Transferring Files to AOL................................................................................................... 599
CHAPTER 26. GETTING PEOPLE TO VISIT .................................................................................. 604
About Keywords.................................................................................................................. 604
Explicitly Listing Keywords................................................................................................. 606
Providing a Description of Your Page............................................................................... 607
Controlling Other Information............................................................................................. 608
Keeping Visitors Away .................................................................................................... 610
Keeping Pages From Being Archived............................................................................... 611
Creating a Crawler Page.................................................................................................... 613
Submitting Your Site to a Search Engine ......................................................................... 616
Improving Your Ranking by Getting Linked...................................................................... 618
Writing Pages That Are Easy to Index.............................................................................. 618
Other Techniques for Publicizing Your Site...................................................................... 620
APPENDIX A. (X)HTML ELEMENTS AND ATTRIBUTES ................................................................ 622
APPENDIX B. CSS PROPERTIES AND VALUES ........................................................................... 632
APPENDIX C. INTRINSIC EVENTS ............................................................................................... 640
APPENDIX D. (X)HTML SYMBOLS AND CHARACTERS ................................................................ 641
Characters with special meaning in HTML and XHTML.................................................. 642
Accented characters, accents, and other diacritics from Western European Languages
............................................................................................................................................. 642
Punctuation characters ...................................................................................................... 643
Mathematical and technical characters, (including Greek).............................................. 645
Shapes and Arrows............................................................................................................ 647
APPENDIX E. HEXADECIMALS .................................................................................................... 649
APPENDIX F. (X)HTML TOOLS .................................................................................................. 651
(X)HTML Editors................................................................................................................. 651
Page 6 of 654
Special thanks to:
Nancy Davis, at Peachpit Press, who I'm happy to report is not only my awesome editor, but also
my friend.
Kate Reber and Nolan Hester, both formerly of Peachpit Press, for their help with earlier editions
of this book.
The dedicated betatesters who poured through the drafts of my book and diligently pointed out
errors and suggested improvements. In particular, I'd like to thank Jennifer Simmons Wheelock
(http://www.wheelockweb.com), Randal Rust (http://www.r2communications.com), Marc Seyon
(http://www.delime.com/milsweb/), Andrew Stevens (http://4serendipity.com), Jonathon Isaac
Swiderski (http://dangercat.net/),Elaine Nelson, and Deepak Sharma (http://www.webjives.com).
Thanks also to Bob Sawyer, Morten Reiersen, John Kenneth Fisher, Andy J. Williams Affleck,
Nicole E.M. Ramsey, Hugh Blair, and Ward Conant.
The Web is an incredible resource. Not only do people share their knowledge freely on their Web
sites, but they are also incredibly generous with their time, answering my questions. In particular,
I'd like to thank Alan Wood, whose Unicode Resources Web site
(http://www.alanwood.net/unicode/) was a major source of information for the Symbols and Non-
English Characters chapter, Eric Costello (http://www.glish.com), who designed the beautiful
example I used in the Layout with Styles chapter, Jeffrey Zeldman, whose online magazine, A
List Apart (http://www.alistapart.com), is an essential resource for Web designers, and Arun
Ranganathan, the Netscape engineer who helped me with the Multimedia chapter. I could not
have written this book without the specifications published by The World Wide Web Consortium
(http://www.w3.org).
Andreu, for his feedback, for his great Photoshop tips, and for sharing his life with me.
Llumi and Xixo, for chasing cherry tomatoes and each other around my office and for helping me
think up examples of HTML documents.
And all the readers of earlier versions of this book, who took the time to write me with accolades,
questions, and suggestions.
Introduction
The World Wide Web is the Gutenberg press of our time. Just about anyone can create their own
Web site and then present it to the Internet public. Some Web pages belong to businesses with
services to sell, others to individuals with information to share. You get to decide what your page
will be like.
All Web pages are written with some form of HTML. HTML lets you format text, add graphics,
sound, and video, and save it all in a Text Only or ASCII file that any computer can read. (Of
course, to project video or play sounds, the computer must have the necessary hardware.) The key
to HTML is in the tags, keywords enclosed in less than (<) and greater than (>) signs, that indicate
what kind of content is coming up.
While there are many software programs that will create HTML code for you (see page 462),
learning HTML yourself means you'll never be limited to a particular program's features. Instead
you'll be able to add whatever you need without having to struggle with confusing software or
wait for software updates.
Page 7 of 654
In this book, you'll find clear, easy-to-follow instructions that will take you through the process of
creating Web pages step-by-step. It is ideal for the beginner, with no knowledge of HTML, who
wants to begin to create Web pages.
If you're already familiar with HTML, this book is a perfect reference guide. You can look up
topics in the hefty index and consult just those subjects about which you need more information.
The World Wide Web, for its part, is much more ethereal. It is an ever-changing, kaleidoscopic
collection of hundreds of millions of documents, all of which reside someplace on the Internet and
are written in some form of HTML.
HTML, or HyperText Markup Language, has two essential features—hypertext and universality.
Hypertext means you can create a link in a Web page that leads the visitor to any other Web page
or to practically anything else on the Internet. It means that the information on the Web can be
accessed from many different directions. Tim Berners-Lee, the creator of the Web, wanted it to
work more like a person's brain and less like a static source of data, such as a book.
Universality means that because HTML documents are saved as Text Only files, virtually any
computer can read a Web page. It doesn't matter if your visitors have Macintosh or Windows
machines, or whether they're on a Unix box or even a hand-held device like a Palm. The Web is
open to all.
So it is with HTML. While practically any computer can display Web pages, what those pages
actually look like depends on the type of computer, the monitor, the speed of the Internet
connection, and lastly, the software used to view the page: the browser. The most popular
browsers today are Internet Explorer, Netscape Communicator, and Opera, with handhelds and
PDAs on the way. Unfortunately, none of these displays a Web page exactly like the next. So it
turns out it's not enough to design a beautiful park, you've also got to worry about your visitor's
accommodations.
But as you worry, remember that your control is limited. While the New York City Tourist Board
would like to ensure that everyone has a good time in their town, they're not handing out free
vouchers for rooms at the Park Plaza Hotel, and some people wouldn't accept them even if they
did, preferring instead a bed and breakfast or their sister's house. You get the idea. The moral is
this: People will be viewing your pages with vastly different setups. Create your pages
accordingly—so that the largest number of visitors can view your page as close to the way you
want them to as is possible. This book will show you how.
Page 8 of 654
The Browser Wars
Now imagine what would happen if each hotel and apartment building on Fifth Avenue staked out
a bit of Central Park and put a fence around it, limiting access to its own residents. It's bad enough
that those of us on park benches can only glimpse in to "exclusive" areas. But, there's also the
problem that folks from one hotel can't get to the piece of park that belongs to the other hotel.
Instead of a rich, public resource, teeming with rollerbladers, hot dog carts, and strolling elders,
the park is divided into small, sterile, isolated lots. This is what is happening on the Web.
In 1994, Netscape put up the first fences on the Web in the so-called browser wars. In order to
attract users, they threw universality to the wind and created a set of extensions to HTML that
only Netscape could handle. For example, Web surfers using Netscape could view pages with
colored text, photographs, and other improvements. Surfers with any other browser would get
errors and funny looking results. Or nothing at all.
But people liked those extensions so much that they flocked to Netscape's "hotel". By 1996, it had
become the most popular computer program in the world. Microsoft started fencing in its own
chunk of the Web. Again, to attract users they added non-standard extensions that only Internet
Explorer, Microsoft's browser, could recognize.
Both Netscape Communications (now a part of America Online) and Microsoft are members of
the W3C, as are other important Webrelated companies, including Adobe and Macromedia
(makers of some of the more important Web tools), and many others. The idea is that these
companies come together and agree on the standards and then try to differentiate their products
with speed, ease of use, price, or other features that don't turn the Web back into the tower of
Babel.
The W3C's first answer to the Web's balkanization was to standardize the proprietary extensions,
including some in the official specifications and removing others altogether. At the same time,
they encouraged browser manufacturers to support the official HTML specifications as closely as
possible, so that a Web page written to standards would behave the same way across browsers.
The W3C's next move was much more bold. The old version of HTML joined content, structure,
and formatting instructions in a single document, which was simple but not very powerful. The
W3C envisioned a new system in which formatting instructions could be saved separately from
the content and structure and thus could be applied not just to a single paragraph or Web page but
to an entire site, if so desired. So, in the new HTML version 4, the W3C marked most of the
Page 9 of 654
formatting elements for future removal from the specifications. These elements would henceforth
be deprecated, and their use discouraged. At the same time, they created the new system for
formatting instructions—called Cascading Style Sheets, or CSS— to fill the gap.
The original specifications for Cascading Style Sheets mostly limited themselves to recreating
HTML effects. CSS Level 2, published in 1998, however, brought new capabilities, in particular
the ability to position elements on a Web page with great precision. CSS could now not only
recreate HTML's formatting, it could make professional looking layouts.
However, between proprietary extensions and just plain sloppy code, HTML pages themselves
were still a mess. Most browsers bent over backward to accommodate them, always in slightly
different ways, which just made the whole situation worse. And there was still no standard system
for adding new features. HTML was simply not a sturdy enough platform upon which to build.
The W3C decided that we all needed a bit of structure. Their answer was XML, or Extensible
Markup Language.
From the outside, XML looks a lot like HTML, complete with tags, attributes, and values. But
rather than serving as a language just for creating Web pages, XML is a language for creating
other languages. You can use XML to design your own custom markup language which you can
then use to format your documents. Your custom markup language will contain tags that actually
describe the data that they contain.
And herein lies XML's power: If a tag identifies data, that data becomes available for other tasks.
A software program can be designed to extract just the information that it needs, perhaps join it
with data from another source, and finally output the resulting combination in another form for
another purpose. Instead of being lost on an HTML-based Web page, labeled information can be
reused as often as necessary.
But, as always, power comes with a price. XML is not nearly as lenient as HTML. To make it
easy for XML parsers—software that reads and interprets XML data—XML demands careful
attention to upper- and lowercase letters, quotation marks, closing tags and other minutiae. In
addition, there are billions of Web pages already written in HTML and millions of servers and
browsers that already know how to read them.
The solution was quite clever. The W3C rewrote HTML in XML. This new language has all of the
features of HTML and thus can be understood by every browser on the planet. And since its entire
lexicon comes from HTML, people who already know HTML only have to learn a few basic
syntax rules before they're off and running. And at the same time, since it uses XML's syntax, it
gains all of XML's power and flexibility and is a perfect foundation for CSS. It is the best of both
worlds. It's name? XHTML.
Netscape 6, completely reformed from its extension madness days, now boasts the most complete
support for CSS. Opera 6, though lesser known, is a fast, lean browser with excellent CSS support.
And the market frontrunner, Internet Explorer 6, is not far behind, although it still has a number of
glaring bugs.
Page 10 of 654
However, while current browsers finally support most of CSS, not everyone uses a current
browser. While estimates vary, perhaps 10% of the Web-surfing public still use a browser with
marginal CSS support, which may not sound like a lot until you translate it to the 50 million
people it represents.
At the same time, we can't wait forever. One option, espoused by the folks at A List Apart[1], a
leading Web design online magazine, is to write XHTML/CSS based pages that look brilliant on
standards-compliant browsers and reasonable, if a bit simpler, on older browsers. A note appears
in the pared down version explaining the situation and suggesting an upgrade. Whether that
solution works for you depends on your circumstances and perhaps your boss.
[1]
1http://www.alistapart.com/stories/tohell/
There are a lot of people out there that will tell you that HTML is evil and XHTML is the only
solution. I think that's silly. XHTML is a great improvement over HTML. It's stronger, more
flexible, more powerful, more likely to be supported in the future, and can be expanded to fit any
need. But I'll tell you something. Sometimes you don't need to fill every need. Sometimes, you
just want to publish a simple page without stressing over every last quotation mark.
Luckily there is a lot of middle ground. There are actually three standard flavors of both HTML
and XHTML. The first, called transitional, allows the use of the deprecated tags. The second,
called frameset, allows both the use of deprecated tags and the use of frames, which we'll discuss
later in this book. The third flavor,strict, prohibits the use of any of the deprecated tags. You can
combine each of these flavors in varying degrees with CSS. Which combination you choose may
depend on several factors. (Keep reading.)
While I don't recommend using proprietary extensions—since they leave out part of your
audience—there are a lot of other options. Here are some guidelines.
• The bigger the site, the more important it is that you use CSS and XHTML. The former
makes it easy to apply, edit, and update formatting across the entire site; the latter gives
your page the structure it needs to make sure it lasts into the future.
• Many companies and government agencies, including the U.S. government, require that
your Web page fulfill specific accessibility requirements in order to make their sites
available to people with disabilities. In these cases, you should adhere as closely as
possible to XHTML strict, with CSS for formatting. And be sure to check the company's
or agency's pertinent guidelines for details in your particular case.
• Large commercial sites that want to reach the widest audience may opt for transitional
XHTML, taking advantage of some deprecated tags' practically universal support, while
banking on XHTML's rock-solid stability. These kinds of sites will very likely shift to the
more powerful CSS as support continues to increase.
• Small or personal sites may want to take advantage of HTML's easy going syntax along
with CSS's powerful formatting and an occasional deprecated tag where necessary.
• My personal choice is to use XHTML and CSS and a bare minimum of deprecated tags
Page 11 of 654
If you've ever been to a different part of your country than where you're from, you've probably
noticed how the folks there talk, well, a little funny. They use different words or they say them
with a different accent. And yet, you understand them just fine even if you chuckle about it in the
car afterwards. That's the way it is with HTML and XHTML. In their case, they share precisely
the same vocabulary (to the letter) but have a slightly different syntax.
Since they are so similar, I'll teach you HTML and XHTML at the same time. I'll start by
explaining the syntax differences that distinguish them. And then throughout the book I will
explain the vocabulary that they share. In those explanations, I use the stricter XHTML syntax.
You can either use it as is (to write XHTML), or opt for the looser HTML syntax (to write
HTML). The choice is yours.
It would be tiresome to have to refer to HTML and XHTML all the time, so I have chosen to use
the abbreviated (X)HTML to refer to both at once. In the few instances I use one of the individual
names, you'll know that the information pertains to that language only and not to the other.
CSS is incorporated into the descriptions of (X)HTML—again, that means, both HTML and
XHTML—as a natural extension and yet a separate tool. While the information about CSS is
concentrated in Chapters 8–11, you'll find bits and pieces throughout the book, next to the part of
(X)HTML to which it is most applicable.
I have taken pains to offer illustrations from all of the major browsers, on both platforms. While
you may stick with one browser on your computer, there's no telling what your visitors will use.
It's a good idea to get used to how other browsers treat (X)HTML.
On my site, you'll find the full source code for every one of the examples in this book, including
the (X)HTML and the CSS (http://www.cookwood.com/html5ed/examples/), a list of errata,
updates, articles, reviews and comments, a complete discussion of the new features in this edition,
and even the full table of contents and index.
There are also several resources available on my site that I hope you'll enjoy, including color
tables, symbol and character tables, pixel shims, and complete lists of both (X)HTML elements
and attributes and of CSS properties and values.
Next, as I was writing this book, I amassed a collection of lesser tips and tricks that simply didn't
fit on the appropriate page. I've made them all available on the site.
Finally, you'll find a lively Question and Answer board (www.cookwood.com/html/qanda) where
you can post your most vexing questions—and easy ones too. While I hang out there and will do
my best to answer, there is a dedicated team of Web designers who usually beat me to the punch.
If you're so inclined, feel free to step in and answer questions yourself. Your help will be greatly
appreciated.
Page 12 of 654
Chapter 1. Web Page Building Blocks
While Web pages have become increasingly complex, their underlying structure remains
remarkably simple. A Web page is made up of three principal components: text content, the actual
headers and paragraphs that appear on the page; occasional references to more complex content
like links, images, and even Flash animations; and markup—instructions that describe how the
content and references should be displayed. It is important to note that each of these components
is comprised exclusively of text. This essential feature means that Web pages can be saved in text-
only format and viewed on practically any browser on any platform. It guarantees the universality
of the Web.
Web pages also include information about the language or script in which the text was written (the
encoding) as well as the kind of the markup that describes it (doctype).
Note: As I mentioned in the introduction, I use (X)HTML to simultaneously refer to both HTML 4
and XHTML 1.0 in situations where they have identical properties, as in "(X)HTML's table
element". On the other hand, for those instances in which I'm highlighting special characteristics
unique to one or the other, I will use their individual names: "XHTML requires quotation marks
around attribute values." For more details, consult How This Book Works on page 23.
XHTML has three principal types of markup: elements, attributes, and values. Later on in the
book we'll also talk about declarations (see page 38) and entities (see page 340).
Elements
Elements are like little labels that identify and structure the different parts of a Web page: "This is
a header, that thing over there is a paragraph, and that is important information." Some elements
have one or more attributes, which further describe the purpose and content, if any, of the element.
Elements can contain text and/or other elements, or they can be empty. A non-empty element
consists of an opening tag (the element's name and attributes, if any, enclosed in less than or
greater than signs), the content, and a closing tag (a forward slash followed by the element's name,
again enclosed in greater than and less than signs) (Figure 1.1).
Figure 1.1. Here is a typical (X)HTML element. The opening and closing tags
surround the text that will be affected. In this case, the word "ephemeral" will be
emphasized, which in most browsers means it will be set in italics.
Page 13 of 654
An empty element looks like a combination opening and closing tag, with an initial less than sign,
the element's name followed by any attributes it may have, a space, a forward slash, and the final
greater than sign (Figure 1.2).
Figure 1.2. Empty elements, like img shown here, do not surround any text
content. They have a single tag which serves both to open and close the element.
In HTML the final slash is optional. In XHTML it is required.
In XHTML, the closing tag is always required In HTML, it is sometimes optional. The
corresponding section in this book for each element will provide the pertinent details.
Attributes contain information about the data in the document, as opposed to being that data itself
(Figures 1.3 and 1.4). In XHTML, an attribute's value must always be enclosed in quotation
marks. In HTML, quotes may sometimes be omitted (see page 36) though I recommend you
always use them anyway.
Figure 1.3. Here is an element (for a table cell) with a simple attribute-value pair.
Attributes are always located inside an element's opening tag. Their values should
always be enclosed in quotation marks.
Figure 1.4. Some elements, like img shown here, can take one or more attributes,
each with its own value. The order is not important. Separate each attributevalue
pair from the next with a space.
While you'll find complete details about an attribute's acceptable values in the appropriate section
of this book, let me give you an idea of the kinds of values you'll run into.
Some attributes can accept any value at all, others are more limited. Perhaps the most common are
those that accept enumerated or predefined values. In other words, you must select a value from a
standard list of choices (Figure 1.5). In XHTML, enumerated values are always written in all
lowercase letters. (In HTML, the case doesn't matter.)
Figure 1.5. Some attributes only accept specific values. For example, the media
attribute in the link element can be set to screen, handheld , or print, among
others, but you can't just make up a value for it. When an attribute is limited to a
Page 14 of 654
given list of values, XHTML requires that they always be written in lowercase
letters.
Many attributes require a number or percentage for their value, particularly those describing size
and length. A numeric value never includes units. Where units are applicable, as in the height of
text or the width of an image, they are understood to be pixels.
The attributes controlling color can contain values that are either a color name or a hexadecimal
representation of the red, green, and blue content of the color. You can find a list of the sixteen
predefined color names as well as a selection of hex colors on the inside back cover of this book.
You can find instructions for creating your own hex colors on page 46. Note that (X)HTML does
not support numeric or percentage values for color.
Some attributes reference other files and thus must contain values in the form of a URL, or
Uniform Resource Locator, a file's unique address on the Web. We'll talk more about URLs
beginning on page 45.
Block vs Inline
Block-level elements are considered the bigger structural pieces of your Web page, and as such
can usually contain other block-level elements, inline elements, and text. Inline elements, in
contrast, can generally only contain other inline elements and text.
(Elements can also be list-items, which is considered distinct from block-level or inline, but it
seems such a small category as to hardly warrant discussion outside of Chapter 13, Lists.)
Figure 1.6 The block-level elements, shown here highlighted in bold, are div and
p. The inline elements, highlighted but without bold, are img and em.
Page 15 of 654
Figure 1.7. Each block-level element starts on a new line. The inline elements (the
image and the italic text) continue the line begun by the block-level element in
which they're contained.
If one element contains another, it is considered to be the parent of the enclosed, or child element.
Any elements contained in the child element are considered descendants of the outer, parent
element (Figure 1.8). You can actually create a family tree of a Web page, that both shows the
hierarchical relationships between each element on the page and uniquely identifies each element.
Figure 1.8. The div element is parent to the img and both p elements. Conversely,
the img and p elements are children (and descendants) of the div. The first p
element is parent to the em tag. The em is a child of the first p and also a
descendant (but not a child) of the div.
Page 16 of 654
This structure is a key feature of (X)HTML code and facilitates adding style to the elements
(which we'll introduce on page 41) and applying JavaScript effects to them (briefly discussed in
Chapter 19, JavaScript Essentials).
It is important to note that when elements contain other elements, each element must be properly
nested, that is fully contained within its parent. Whenever you use a closing tag, it should
correspond to the last unclosed opening tag. In other words, first open A then open B, then close
B, and then close A (Figure 1.9).
Figure 1.9. Elements must be properly nested. If you open p and then em, you must
close em before you close p.
First, (X)HTML compresses extra spaces or tabs into a single space and either converts returns
and line feeds into a single space or ignores them altogether (Figures 1.10 and 1.11).
Figure 1.10 The text content is basically anything outside of the markup. Note that
each line happens to be separated with a carriage return. Also, I've used a special
character reference © for the copyright symbol to ensure that it is properly
displayed no matter how I save this document.
Page 17 of 654
Figure 1.11. Note how the extra returns are ignored when the document is viewed
with a Web browser, the text appears otherwise as expected, and the character
reference is replaced by the corresponding symbol (©).
Next, HTML used to be restricted to ASCII characters—basically the letters of the English
language, numerals, and a few of the most common symbols. Accented characters (common to
many languages of Western Europe) and many everyday symbols had to be created with special
character references like é (for é) or © (for ©).
Nowadays, you have two options. You can still use character references for maximum
compatibility or you can simply type most characters and then encode your (X)HTML files in
Unicode, and particularly with UTF-8, which is explained on pages 334–335 (Figure 1.12).
Because Unicode is a superset of ASCII—that is, everything ASCII is, and a lot more—Unicode-
encoded documents are compatible with existing browsers and editors. Browsers that don't
understand Unicode will interpret the ASCII portion of the document properly, while browsers
that do understand Unicode—Netscape and IE 4+—will display the non-ASCII portion as well.
(See Chapter 20, Symbols and Non-English Characters.)
Figure 1.12. If you save your Web page in Unicode with the UTF-8 encoding, you
don't have to bother with character references as in Figure 1.10.
The only symbol that you must not type in directly is the &. Since it has special meaning in
(X)HTML, namely to begin those character references, it must always be expressed as &
when used as text, as in AT&T. For more details, consult Adding Characters from Outside the
Encoding on page 340.
Page 18 of 654
Links, Images, and Other Non-Text Content
Of course, what makes the Web so vibrant are the links from one page to another, the images,
Flash animations, RealAudio transmissions, QuickTime movies, and more. Instead of actually
enclosing the external files in the (X)HTML file, these files are saved independently and are
simply referenced from within the page. Since the reference is nothing more than text, the
(X)HTML file remains universally accessible.
Most browsers can handle links and images without any trouble. They can't necessarily handle
every other kind of file, however. If you reference a file that your visitor's browser doesn't
understand, the browser will usually try to find a plugin or helper application—some appropriate
program on the visitor's computer—that is capable of opening that kind of file. You can also give
browsers extra information about how to download plugins for viewing particular files if the
visitor doesn't already have one on their computer.
We'll cover images in Chapters 5 and 6 (Creating Web Images and Using Images, respectively),
and plugins and helper applications in Chapter 17, Multimedia.
Figure 1.14. Images, and other non-text content, are referenced from a Web page
and the browser displays them together with the text.
Page 19 of 654
File Names
Like any other text document, Web pages have a file name that identifies the documents to you,
your visitors, and to your visitors' Web browser. There are a few tips to keep in mind when
assigning file names to your Web pages that will help you organize your files, make it easier for
your visitors to find and access your pages, and ensure that their browsers view the pages
correctly.
Since the file name you choose for your Web page determines what your visitors will have to type
in order to get to your page, you can save your visitors from inadvertent typos (and headaches) by
using only lowercase letters in your file names. It's also a big help when you go to create links
between your pages yourself. If all your file names have only small letters, it's just one less thing
you'll have to worry about.
The principal way a browser knows that it should read a text document as a Web page is by
looking at its extension: .htm or .html. If the page has some other extension, like say ".txt", the
browser will treat it as text, and show all your nice code to the visitor.
• Macintosh users—unless you're on a Mac server and all your visitors use Macs—this
goes for you too.
• Windows folks, be aware that Windows doesn't always reveal a document's real
extension. Change your Folder Options, if necessary, so you can see extensions.
• Only folks on Windows 3.1 are limited to .htm. Practically everyone else can use either
.htm or .html without problem. Just be consistent to avoid having to remember which one
you used.
Figure 1.15. Remember to use all lowercase letters for your file names and to
consistently add either the .htm or .html extension. Mixing upper and lowercase
letters makes it harder for your visitors to type the proper address and find your
page.
Page 20 of 654
Figure 1.16. Use all lowercase letters for your directories and folders as well. The
key is consistency. If you don't use uppercase letters, your visitors (and you) don't
have to waste time wondering, "Now, was that a capital C or a small one?"
URLs
Uniform resource locator, or URL, is a fancy name for address. It contains information about
where a file is and what a browser should do with it. Each file on the Internet has a unique URL.
The first part of the URL is called the scheme. It tells the browser how to deal with the file that it
is about to open. One of the most common schemes you will see is HTTP, or Hypertext Transfer
Protocol. It is used to access Web pages (Figure 1.17).
Figure 1.17. Your basic URL contains a scheme, server name, path, and file name.
The second part of the URL is the name of the server where the file is located, followed by the
path that leads to the file and the file's name itself. Sometimes, a URL ends in a trailing forward
slash with no file name given (Figure 1.18). In this case the URL refers to the default file in the
last directory in the path (which generally corresponds to the home page), often called index.html
or default.htm.
Figure 1.18. A URL with a trailing forward slash and no file name points to the
default file in the last directory named (in this case the liz directory). Some
common default file names are index.html and default.htm.
Other common schemes are HTTPS, for secure Web pages; FTP (File Transfer Protocol) for
downloading files from the Net (Figure 1.19); News, for sending and reading messages posted to
a Usenet newsgroup (Figure 1.20); Mailto, for sending electronic mail (Figure 1.21); and File, for
accessing files on a local hard disk (Figure 1.22).
Page 21 of 654
Figure 1.19. When the user clicks this URL, the browser will begin an FTP transfer
of the file prog.exe.
Figure 1.20. A URL for a newsgroup looks a bit different. There are no forward
slashes after the scheme and colon, and generally, there is no file name. (Although
you could add the message number or ID, a message's extremely short lifespan
limits its usefulness as a link.)
Figure 1.21. A URL for an e-mail address is similar in design to a newsgroup URL
(Figure 1.20); it includes the mailto scheme followed by a colon but no forward
slashes, and then the e-mail address itself.
Page 22 of 654
Figure 1.22. To reference a file on a local Windows machine, use the file scheme.
For Macintosh, use file:///Harddisk/path/filename. No vertical bar is required. (This
sometimes works for Windows as well.)
A scheme is generally followed by a colon and two forward slashes. Mailto and News are
exceptions; these take only a colon.
Notice that the File scheme uses three slashes. That's because the host, which in other schemes
goes between the second and third slashes, is assumed to be the local computer. Always type
schemes in lowercase letters.
Absolute URLs
URLs can be either absolute or relative. An absolute URL shows the entire path to the file,
including the scheme, server name, the complete path, and the file name itself. An absolute URL
is analogous to a complete street address, including name, street and number, city, state, zip code,
and country. No matter where a letter is sent from, the post office will be able to find the recipient.
In terms of URLs, this means that the location of the absolute URL itself has no bearing on the
location of the actual file referenced—whether it is in a Web page on your server or on mine, an
absolute URL will look exactly the same.
When you're referencing a file from someone else's server, you'll always use an absolute URL.
You'll also need to use absolute URLs for FTP sites, newsgroups, and e-mail addresses—in short,
any kind of URL that doesn't use an HTTP protocol.
Figure 1.23. The document that contains the URLs—youarehere.html in this case—
is the reference point for relative URLs. In other words, relative URLs are relative
to that file's location on the server. Absolute URLs don't care where they are
located.
Page 23 of 654
Absolute URLs vs. Relative URLs
File name Absolute URL (can be used Relative URL (only works in
anywhere) youarehere.html)
index.html www.site.com/web/index.html index.html
Relative URLs
To give you directions to my neighbor's house, instead of giving her complete address, I might
just say "it's three doors down on the right". This is a relative address—where it points to depends
on where the information is given from. With the same information in a different city, you'd never
find my neighbor.
In the same way, a relative URL describes the location of the desired file with reference to the
location of the file that contains the URL itself. So, you might have the URL say something like
"show the xyz image that's in the same directory as the current file".
Thus, the relative URL for a file that is in the same directory as the current file (that is, the one
containing the URL in question) is simply the file name and extension (Figure 1.24). You create
the URL for a file in a subdirectory of the current directory with the name of the subdirectory
followed by a forward slash and then the name and extension of the desired file (Figure 1.25).
Figure 1.24. The relative URL for a file in the same folder (see Figure 1.23) as the
file that contains the link is just the file's name and extension.
Page 24 of 654
Figure 1.25. For a file that is within a folder inside the current folder (see Figure
1.23), add the folder's name and a forward slash in front of the file name.
To reference a file in a directory at a higher level of the file hierarchy, use two periods and a
forward slash (Figure 1.26). You can combine and repeat the two periods and forward slash to
reference any file on the same hard disk as the current file.
Figure 1.26. This file, as you can see in Figure 1.23, is in a folder that is inside the
folder that contains the current folder (whew!). In that case, you use two periods
and a slash to go up a level, and then note the subdirectory, followed by a forward
slash, followed by the file name.
Generally, for files on the same server, you should always use relative URLs. They're much easier
to type and they make it easy to move your pages from a local system to a server—as long as the
relative position of each file remains constant, the links will work correctly.
One added advantage of relative URLs is that you don't have to type the scheme—as long as it's
HTTP.
Page 25 of 654
HTML vs XHTML
I like to imagine HTML as a laid-back don't-sweat-the-details kind of person. Perhaps not quite as
hard-working as XHTML, but much happier and at ease with herself. XHTML, on the other hand
is downright uptight. Always vigilant, never taking a rest. Sure, she gets more done, but what a
price!
Before I go off the deep end with my personification of Web page code types, let me tell you the
specifics. For starters, know that HTML 4 and XHTML 1.0 use precisely the same elements,
attributes, and values. The difference is in the syntax.
• Where HTML doesn't care if you use the html, head and body elements and
DOCTYPE, XHTML requires them.
• Where HTML lets you omit some closing tags, XHTML insists on them for every
element, even empty ones. For the best compatibility with browsers, add a space and/to
empty elements and include an independent closing tag for non-empty elements (Figures
1.27–1.30). Note that the slash is not strictly valid in empty elements in HTML, though
all browsers I've seen simply ignore it.
Figure 1.27 In HTML, some elements, like p, do not requiring a closing tag.
Subsequent p tags implicitly close earlier ones.
Figure 1.29 In HTML, empty elements do not have a final slash, though
browsers won't complain if they do.
Page 26 of 654
Figure 1.30 In XHTML, even empty elements must have a closing tag. While
an independent closing tag for an empty element, like </img>, would be
technically correct, adding a space and / to the single img tag ensures
compatibility with non-XHTML-savvy browsers.
• Where HTML lets you omit quotes around attribute values that contain just letters,
numbers and four simple symbols (-, ., _, and :), XHTML gets nightmares (and generates
errors) if you leave quotes out (Figures 1.31 and 1.32).
Figure 1.31 In HTML, attribute values only need to be quoted when they
contain spaces or other special characters (anything besides letters,
numbers, hyphens, periods, underscores, or colons). So, in this example,
only the alt attribute's value must be quoted (though it wouldn't hurt to
quote all of them).
• Where HTML is flexible about case, XHTML is not, demanding that all elements,
attributes, and predefined values be in lowercase (Figures 1.33 and 1.34).
Figure 1.33 In HTML, it doesn't matter if you write element names, attribute
names, or predefined values in upper or lowercase.
Figure 1.34 In XHTML, all element names, attribute names, and predefined
values must be written in lowercase.
• Where HTML allows you to omit values that have the same name as the attribute,
XHTML insists that all values be stated explicitly (Figures 1.35 and 1.36).
Figure 1.35 In HTML, some attributes, like noshade shown here, don't
require any value.
Page 27 of 654
<hr width=75% noshade>
Figure 1.36 In XHTML, attribute values must be stated explicitly. For those
attributes that in HTML have no value, simply repeat the attribute's name as
its value.
You might be wondering if it's worth it to worry about every last quotation mark. The answer is, it
depends.
XHTML's rigidity affords a lot of advantages. Think of a clean workshop, with hammers and
screwdrivers hanging in their places on the wall and all the nuts and bolts in labeled containers.
It's so easy to find what you need that it makes projects a hundred times easier. Similarly,
XHTML helps you keep your code consistent, well structured, and free of non-standard tags,
which in turn makes it easier to update and edit, to format with CSS, to generate from or convert
into a database, and to adapt for other systems, like handhelds and aural browsers.
In addition, XHTML is a logical step in the transition from HTML to XML, since it uses familiar
HTML elements and attributes together with modern XML syntax. And since XHTML is the new
standard, you can be sure that it will be used with other new and future technologies.
Perhaps one of XHTML's most important gifts is that its insistence on standards makes it more
likely to be properly and consistently supported by current browsers, on all platforms—which
makes good business sense. And since Web page accessibility is now required by U.S. law, and
the laws of many other nations, it is something that should not be ignored. For more information
on accessibility laws, visit the W3C Web Accessibility Initiative at http://www.w3.org/WAI/.
For more details about why standards matter, I recommend a trip to The Web Standards Project
(http://www.webstandards.org), a consortium of designers turned diplomats determined to end the
browser wars, and Jeffrey Zeldman's A List Apart, an excellent online magazine for Web
designers (http://www.alistapart.com).
Figure 1.37 Here is the official DOCTYPE for XHTML transitional documents. You
can find a list of DOCTYPE declarations on my Web site. (They're rather a drag to
type in manually.)
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1 -transitional.dtd">
Does it matter which version you use? The flip answer is "not to me". I think it's perfectly
reasonable to use HTML and depend on its easy-going nature if you're writing a personal site. If
Page 28 of 654
you want your pages to follow strict standards, take advantage of XHTML's ability to connect to
databases and the like, work well with styles (see page 41), and be easily updated for future
systems, use XHTML.
Likewise, if you use deprecated tags, you should use the transitional flavor of either HTML or
XHTML. No deprecated tags? Use strict. If your site uses frames (see page 241), use the frameset
flavor. Note that there is no strict flavor that allows frames—which clues you in about what the
W3C thinks of them.
You can state which version and flavor you're using in your document by using a DOCTYPE
declaration (see page 60). Once that information is part of your Web page, you can use a validator
to determine if the code used in your page actually corresponds to the code allowed for that
version and flavor. Validators are a great way to check for typos and in general, to make sure your
code is correct. For more details, see page 394.
Note that there are earlier versions of HTML (3.2 and earlier), but they are outdated and not
particularly useful.
In the old days, when each browser had its own way of interpreting HTML and CSS, Web
designers often used workarounds or hacks that depended on a browser's quirky behavior in order
to create a desired effect on a Web page. Now that browsers for the most part support the
(X)HTML and CSS standards, designers no longer need to rely on such hacks and can take
advantage of the power of standards to control the display of their new pages.
What becomes, however, of the millions upon millions of existing pages designed for quirky
browsers? Instead of displaying these pages according to standards, which might ruin their quirk-
dependent designs, Explorer and Netscape 6 revert to their old quirky ways in order to display
these pages "properly"—that is, how they were designed, but not according to standards. (Opera
has no quirks mode.)
And how can a browser tell if a page might rely on quirks? It looks for the DOCTYPE declaration
at the top of the page. If it finds a proper DOCTYPE declaration, it assumes the page has been
designed using all the power of standards, and displays it accordingly. This is called standards
mode (or sometimes strict mode, though this is more confusing since it has nothing to do with
strict (X)HTML). If there is no proper DOCTYPE declaration (or if it is omitted entirely), the
browser assumes the page is old-fashioned and relies on soon to be obsolete browser bugs, and
displays it in that way. This is called quirks mode.
These two modes allow you to write standards-based pages for the future without losing your
quirks-based pages of the past. I'll show you how to write appropriate DOCTYPE declarations on
page 60.
Figure 1.38 Some browsers, notably Internet Explorer, do not care if you leave out
the initial hash sign (#) for a hexadecimal color. While you may think that's nice of
them, it encourages Web developers to write incorrect code which then breaks on
other browsers.
Page 29 of 654
Figure 1.39. If you omit the DOCTYPE, Explorer continues to act in its non-
standard, quirky way, and views the text color correctly—as dark blue (shown here
in red).
Figure 1.40. If you use the DOCTYPE , IE assumes you want it to follow the
standards, and so it ignores the faulty color value (and displays the text as black).
Figure 1.41. If you decide to clean up your faulty CSS, and add the missing #
symbol, then you should use the DOCTYPE in the corresponding document since
IE can view your document properly in standards mode.
Page 30 of 654
The Default Display of (X)HTML
Every Web browser has a default system for displaying each kind of (X)HTML element. While
the system may vary from browser to browser, they all maintain the basic structure that you set
forth in the Web page.
So, for example, a level one header (h1) will always be set larger than a level two header (h2),
which will always be larger than a level three header (h3). Similarly, an em element will always
be set off from the surrounding text in order to emphasize it.
That doesn't mean that the h1 element will always be in say, 24pt Times, or that emphasis will
always be achieved with italics. While the default display systems are very similar on all personal
computer-based browsers—including Explorer, Netscape, and Opera on both Macs and PCs
(Figure 1.42), they are quite different on PDAs, cell phones, and of course, on aural browsers.
And that's a good thing. The structure of the Web page is maintained but its display is adapted to
fit the browser on which it appears. And that means your Web page is universally accessible and
intelligible.
Figure 1.42. With no styles applied, the text appears after the image, in its default
font and color. Most current versions of major browsers have identical defaults.
Page 31 of 654
Page 32 of 654
It doesn't mean, however, that your Web page is a work of art. A browser's default display system
is typically quite generic. Luckily you can override that system by applying styles to your
elements. We'll get to them next.
A CSS style sheet is made up of one or more rules. Each rule is comprised of a selector, which
identifies the parts of the Web page that should be affected, and one or more declarations, which
specify the formatting which should be applied. For example, a style sheet might be comprised of
two rules, one that says all level one headers should be big and blue and another that says all
paragraphs should be in a sans serif font.
The simplest kind of selector is just the name of an (X)HTML element, like h1 or p. More
complex selectors might specify that a rule be applied to an entire class of elements, to the
children of a particular element, or even to all the descendants of an element. You'll learn how to
define all sorts of selectors in Chapter 8, Creating Styles.
A rule's declaration lists the property that is being defined followed by a colon and then the
desired value for that property. For example, to make the text blue, I've used the color property
with a value of #3366cc (Figure 1.43).
Figure 1.43. Here is a typical CSS rule. This one has a simple selector (that
indicates the rule will be applied to all p elements), and three associated
declarations.
Page 33 of 654
A rule can have as many declarations as you need. Simply separate multiple declarations with a
semicolon. You may omit the semicolon from the last declaration in a rule, though some people
prefer to leave it for consistency's sake.
Note: CSS prefers one aspect of XHTML over HTML: the use of closing tags. If you want to use
CSS with HTML, be sure to close all your non-empty elements, even when it's not required (like
p and li). CSS doesn't care if you add the / to empty tags like img.
Figure 1.44. With styles, the image floats to the left, the text is displayed in a
different font and weight, and there is a background image in the bottom-right
corner. Styles are well supported by current versions of major browsers, including
IE5 and Opera 6 (shown) and Netscape 6, on both platforms.
What happens, you might ask, when there is more than one style rule that applies to a given
element? CSS uses the principle of the cascade, from which it gets its first initial, to take into
Page 34 of 654
account such important characteristics as inheritance, specificity, and location in order to
determine which of a group of conflicting rules should win out.
Let's start with inheritance. Many CSS properties affect not only the elements defined by the
selector but are also inherited by the descendants of those elements. For example, suppose you
make all your h1 elements blue with a red border. Since the color property is inherited, but the
border property is not, any elements contained within the h1 elements will also be blue, but will
not have their own red border. You'll learn which properties are inherited in the individual section
describing each property (and in Appendix B, CSS Properties and Values). You can also use a
value of inherit with most properties to force inheritance.
While inheritance determines what happens if no style rule is applied to an element, specificity is
the key when more than one rule is applied. The law of specificity states that the more specific the
selector, the stronger the rule. So if one rule states that all h1 elements should be blue but a
second rule states that all h1 elements with a class of Spanish be red, the second rule will
override the first for all those h1 elements whose class is Spanish.
Figure 1.45 Here is the style sheet for this document. Don't worry too much about
the details right now, but do notice that there is a rule for p elements, but not for
em elements.
Figure 1.46 The em element is contained within the p element, and thus is a child of
p.
Figure 1.47. In the absence of a rule specified explicitly for the em element in
Figure 1.45, it inherits the font, weight, and color from its parent, the p element.
Page 35 of 654
Figure 1.48 Here are four rules of varying specificity. The first affects any old p
element, the second affects only those p elements with a class equal to group, and
the third and fourth affect only the single p element with an id equal to one. Since
the third and fourth rules have the same specificity, their position becomes a
factor—and thus the fourth rule wins out since it appears last. Don't worry about
the specifics yet. We'll discuss classes and ids and how to apply styles to them
later, in detail.
p {color:red}
p.group {color:blue}
p#one {color:green}
p#one {color:magenta}
Figure 1.49 Here are three paragraphs, one generic one, one with just a class, and
one with a class and an id.
Note that id attributes are considered the most specific (since they must be unique in a
document), while the presence of a class attribute makes a selector more specific than a simple
selector that has none. (You'll learn all about classes and ids in Chapter 3, Basic (X)HTML
Structure.) Inherited rules are considered to be the most general of all, and are overruled by any
other rule.
Sometimes, specificity is not enough to determine a winner among competing rules. In that case,
the location of the rule breaks the tie: Rules that appear later have more weight. For example,
rules that are applied locally right in the (X)HTML element (see page 153) are considered to
appear after (and thus have more weight than) equally specific rules applied internally at the top of
the (X)HTML document (see page 151). For details, consult The Importance of Location on page
154.
If that isn't enough, you can override the whole system by declaring that a particular rule should
be more important than the others by adding !important at the end of the rule. However, this
feature is not well supported, and in my opinion, creates more problems than it solves.
In summary, in the absence of a rule, many styles are inherited from parent element to child. With
two competing rules, the more specific the rule, the more weight or importance it has—regardless
of its location. With two rules of equal specificity, the one that appears later wins.
Figure 1.50. The first paragraph is red, the second is blue, and the third one is
magenta. (You can see for yourself on my Web site—see page 24.)
Page 36 of 654
A Property's Value
Each CSS property has different rules about what values it can accept. Some properties only
accept one of a list of predefined values. Others accept numbers, integers, relative values,
percentages, URLs, or colors. Some can accept more than one type of value. While the acceptable
values for each property are listed in the section describing that property (mostly in Chapters 10
and 11), I'll discuss the basic systems here.
Predefined Values
Most CSS properties have a few predefined values that can be used. For example, the display
property can be set to block, inline, list-item, or none. In contrast with (X)HTML, you don't need
to and indeed must not enclose predefined values in quotation marks (Figure 1.51).
Figure 1.51. Many CSS properties will only accept values from a predefined list.
Type them exactly and do not enclose them in quotation marks.
Many CSS properties take a length for their value. All length values must contain a quantity and a
unit, with no spaces between them, for example, 3em or 10px (Figure 1.52). The only exception
is 0, which may be used with or without units.
Figure 1.52. Lengths must always explicitly state the unit. There should be no
space between the unit and the measurement.
Page 37 of 654
There are length types that are relative to other values. An em is usually equal to the element's
font-size , so 2em would mean "twice the font-size". (When the em is used to set the
element's font-size property itself, its value is derived from the font size of the element's
parent.) The ex should be equal to the font's x-height, that is, the height of a letter x in the font, but
is not well supported.
Pixels (px) are relative to the resolution of the monitor—though not to other style rules. Most
monitors these days display about 80 pixels to the inch (though they range from 72 to 96 pixels to
the inch), so 16 pixels is about 1/5 of an inch high (or 0.5cm).
Figure 1.53. Percentages are generally relative to the parent element. So, in this
example, the font would be set to 80% of the parent's font-size.
There are also the largely self-explanatory absolute units—inches (in), centimeters (cm),
millimeters (mm), points (pt), and picas (pc). In general, you should only use absolute lengths
when the size of the output is known (as with the printed page—see Chapter 12).
Percentage values, 65%, for example—work much like ems, in that they are relative to some
other value (Figure 1.53).
Bare Numbers
A very few CSS properties accept a value in the form of a number, without a unit, like 3. The most
common are line-height (Figure 1.54) and z-index . (The others are mostly for print and
aural style sheets and are not yet well supported.)
Figure 1.54. Don't confuse numbers and integers with length. A number or integer
has no unit (like px). In this case, the value shown here is a factor that will be
multiplied by the font-size to get the line-height.
Page 38 of 654
URLs
Some CSS properties allow you to specify the URL of another file. In that case, use url(file.ext),
where file.ext is the path and file name of the desired document (Figure 1.55). Note that the
specifications state that relative URLs should be relative to the style sheet and not the (X)HTML
document. Unfortunately, Netscape 4 got that one wrong, so to be compatible with that browser,
you have to use absolute URLs.
While you may use quotations around the file name, they're not required. On the other hand, there
should be no space between the word url and the opening parentheses.
For more information on writing the URLs themselves, consult URLs on page 33.
CSS Colors
There are several ways to specify colors for CSS properties. First, and easiest, the value can be
one of 16 predefined color names (Figure 1.56). Of course, 16 colors get pretty boring pretty
quickly.
Figure 1.56. Here are the sixteen predefined color names together with their
equivalent hexadecimal codes. You can find these colors—in color!—on the inside
back flap of this book and on my Web site (see page 24).
Page 39 of 654
Instead of limiting yourself to those colors, you can construct your own by specifying the amount
of red, green, and blue in the desired color. You can give the values of each of these contributing
colors as a percentage, a number from 0–255, or a hexadecimal representation of the number. For
example, if you wanted to create a dark purple, you might use 35% red with 50% blue. That color
could be written rgb(%35, 0%, 50%) as shown in Figure 1.57. If you use numerical values, you
could write the same color as rgb(89, 0, 127), since 89 is 35% of 255 and 127 is 50% of 255.
Figure 1.57. You can express the amount of each of the three contributing colors
with a percentage (shown here), or with a number ranging from 0-255. Define the
red first, followed by green, and then blue.
I've saved the most common though most convoluted method for last (Figure 1.58): convert those
numerical values to hexadecimals, join them together, and add an initial #: #59007F. (59 is the
hexadecimal equivalent of 89, 00 is the hexadecimal equivalent of 0, and 7F is the hex equivalent
of 127.)
Figure 1.58. The most common way to define a color is by specifying, with
hexadecimal numbers, the amounts of red, green, and blue that it contains. Notice
the initial hash symbol and note that hex numbers are case insensitive, that is, it
doesn't matter if you write #ffffff or #FFFFFF or indeed #ffFFfF.
And if that weren't enough, when a hexadecimal color is comprised of three pairs of repeating
digits, as in #ff3344, you may abbreviate the color to #f34.
While most current image editors, including Photoshop and Photoshop Elements, include tools for
choosing colors and displaying their hex values, I've also included a do-it-yourself table in
Appendix E, along with some esoteric details about hexadecimal conversions.
Perhaps more useful is the inside back cover of this book, in which you'll find a selection of
colors, together with their hex values, that you can use on your Web pages. I'd also recommending
taking a look at Color on page 84.
Page 40 of 654
Chapter 2. Working With Web Page Files
Before you start writing (X)HTML elements and attributes, it's important to know how to create
the files in which you'll use such code. In this chapter, you'll learn how to create, edit, and save
Web page files. I'll also touch on some design and organizational considerations.
If you can't stand waiting any longer, and already know how to create the actual files, skip on
ahead to Chapter 3, Basic (X)HTML Structure, where I begin to explain the (X)HTML code itself.
1. Figure out why you're creating this site. What do you want to convey?
2. Think about your audience. How can you tailor your content to appeal to this audience?
For example, should you add lots of graphics or is it more important that your page
download quickly?
3. How many pages will you need? What sort of structure would you like it to have? Do you
want visitors to go through your site in a particular direction, or do you want to make it
easy for them to explore in any direction?
4. Sketch out your site on paper.
5. Devise a simple, consistent naming system for your pages, images, and other external
files (see page 32).
Tips
• Don't overdo the design phase of your site. At some point, you've got to dig in
and start writing.
• If you're not very familiar with the Web, do some surfing first to get an idea of
the possibilities. You might start with Yahoo (http://www.yahoo.com) or
Google (http://www.google.com/dirhp) or even your competitors.
• There are lots of good books on Web design. You might ask people for
recommendations on my Question and Answer board (see page 24).
Figure 2.1. Sketching out your site and thinking about what it might contain can help you
decide what sort of structure it needs: a centralized, hierarchical model (top), a circular
model that leads the visitor from one page to the next (above), or some other system.
Page 41 of 654
Page 42 of 654
Creating a New Web Page
You don't need any special tools to create a Web page. You can use any word processor, even
WordPad or SimpleText, which are included with the basic Windows and Macintosh system
software.
Figure 2.2. Open your text editor or word processor and choose File > New.
(Shown are Simple-Text for Macintosh at far left and WordPad for
Windows.)
Figure 2.3. This is SimpleText's document window where you'll write the
(X)HTML code for your Web page.
Page 43 of 654
Figure 2.4. This is WordPad's document window where Windows users can
create (X)HTML pages.
3. Create the (X)HTML content as explained in the rest of this book, starting on page 59.
4. Be sure to save your file as directed on page 50.
Tips
• If you like Microsoft Word, you can use it for writing (X)HTML too. Just be
sure to save the file correctly (as Text Only and with the .htm or .html
extension). For more details, see pages 50–52.
• If you use FrontPage, Dreamweaver, or some other Web page editor to start
your pages, you can still tweak the (X)HTML code by hand. Just choose File
> Open from your text editor of choice and open the file. Then use the rest of
this book to add your own (X)HTML tags and create the (X)HTML page you
want.
• You can use SimpleText or WordPad, but if you want to get fancy, try BBEdit
for Mac or HomeSite for Windows. Both display (X)HTML tags in color, and
have powerful search and replace functions, syntax checkers for debugging
problematic pages, and assorted other helpful features. For more details,
consult (X)HTML Editors on page 462.
So that browsers (and servers) recognize Web pages and know to interpret the markup they
contain, as well as distinguish them from plain text files that are not Web pages, Web page files
also have the .htm or .html extension.
Because of that extension, a Web page's icon matches the system's default browser and not the
word processor with which the file was written. Indeed, when you double-click a Web page file, it
Page 44 of 654
is opened in a browser, not a word processor. This is great for Web surfers, but it adds an extra
step to editing Web pages (see page 54).
To resume, when you save your Web page, you must save it in text only format with either the
.htm or .html extension.
Figure 2.5. An Excel file has the .xls extension and is identified with the Excel icon
(left). If you double-click it, it is displayed with Excel. A Web page file, created with
any word processor, has the .htm or .html extension but is identified with the
default browser's icon. If you double-click it, it is displayed with the browser (not
the word processor).
1. Once you've created your Web page, choose File > Save As from your word processor
(Figure 2.6).
Figure 2.6. Choose File > Save As from your word processor or text editor.
(WordPad is on the left, SimpleText on the right.)
2. In the dialog box that appears, choose Text Only or Text Document (or however your
program words it) for the format.
3. Give the document the .htm or .html extension. (This is very important!)
4. Choose the folder in which to save the Web page.
5. Click Save.
Figure 2.7. In SimpleText, give the file the .htm or .html extension, choose the
desired location, and then click Save. (Since SimpleText only saves in Text Only
format, you don't have to specify the format.)
Page 45 of 654
Figure 2.8. In WordPad, choose Text Document under Save as type, give the file
the .htm or .html extension, choose the desired location, and then click Save.
Tips
• Only Windows 3.1 users are limited to the three letter extension, .htm.
Practically everyone else—Windows 95/98, Unix, and Macintosh—can
choose what they like best. Just be consistent.
• Some word processors (like Microsoft Word and Corel WordPerfect to name a
few) offer a "Save as HTML" or "Save as Web page" option. Don't touch it!
That option is for folks who want to create a Web page from a word
processing document without learning HTML and it completely messes up
hand-written code (see page 52).
• Some text editors on Windows have the annoying habit of adding their default
extension to your file name, even if you've already specified .htm or .html.
Your file, now named webpage.html.txt cannot be properly viewed in a
browser. To make matters worse, Windows often hides extensions on the
Desktop so that the problem is not completely obvious, especially to the
uninitiated. There are two solutions. The first is to enclose your file name in
double quotes when you save your document. This should keep the extra
extension from being added. Next, you can display the extensions on the
Desktop and then select the offending extension and eliminate it. For details,
see my Web site (see page 24).
• When you choose Text Only (or similar), your file is saved with your system's
default character encoding. If you want to create Web pages in another
encoding (perhaps to include special symbols or text in other languages),
you'll have to use a word processor that lets you choose the encoding (Figure
2.9). For more details, see Chapter 20, Symbols and Non-English Characters.
Figure 2.9. Many word processors let you choose the encoding
for your file, so that you can save characters from different
languages in the same document. This illustration is from BBEdit
6.5.2. (Click the Options button in the Save box to get here.)
Page 46 of 654
About Microsoft Word and Web Pages
Word can automatically create Web pages from existing documents, often whether you want it to
or not. Its commands are particularly confusing to Web page designers who create their own
markup code—which is probably you if you're reading this book.
Word's "Save as Web Page" command (available both from the File menu (Figure 2.10) and as a
format in the Save dialog box) means "convert the present document into HTML, adding markup
where there is formatting, and saving as text-only with the .htm extension". There are two
problems with this command. First, it converts any markup that you've entered manually into plain
text, using special symbols. Second, Microsoft adds an incredible amount of proprietary code. If
you're writing your own markup with this book, you don't want to use this option.
Figure 2.10. Don't use Word's Save as Web Page option. It's for converting regular
Word documents into Web pages and will mess up hand-coded markup.
Instead, choose File > Save As (Figure 2.11), choose Text Only from the Save as type box, and
then change the default .txt extension to .htm or .html (Figure 2.12).
Figure 2.11. Instead, choose Save As and then choose the proper type and
extension as shown in Figure 2.12.
Page 47 of 654
Figure 2.12. In the Save As dialog box, first choose Text Only in the Save as type
box. Then add the .htm or .html extension. (If you do it in the reverse order, the
Text Only option will change your extension back to .txt.)
Tips
o Text Only saves files with the ANSI encoding. If you'd prefer some other encoding
(perhaps a more standard or a non-Western European encoding), Word 2000 offers
Encoded Text in the Save as type box. Once you click Save, you'll have to confirm
that you really want to save as Encoded Text and will be able to choose the desired
Page 48 of 654
Encoding. For more details, consult Saving Your Page with the Proper Encoding on
page 336.
o These instructions cover Word 2000 for Windows. Other versions may have slightly
different wording or dialog boxes.
1. First, ask your ISP how such a default page should be named. On most servers, use
index.html. (Microsoft servers generally use default.htm.)
2. Next, when you save your file (see page 50), use the proper name.
Figure 2.13. Save the file with the special default name: either index.html or
default.htm, depending on your server. Note that this is BBEdit's Save box (on Mac
OS X), but it doesn't matter which program you use to save the files.
Figure 2.14. When the visitor types the path to the directory, but omits the file
name itself, the file with the default name is used.
Page 49 of 654
Tips
Page 50 of 654
Figure 2.16. Once files with any extension are displayed, you can choose
the appropriate file and click Open.
Tips
• Usually, once you've made changes to an already saved document, you can
simply choose File > Save to save the changes, without having to worry about
the format as described on page 50.
• Right-click the Web page's icon in Windows and then choose Edit to open the
Web page in the default HTML editor (Figure 2.17). You can specify the
word processor that should appear in this menu, but it's a bit involved to go
into right here. Check my Web site for the details (see page 24).
Page 51 of 654
Organizing Files
Before you have too many files, it's a good idea to figure out where you're going to put them.
1. Create a central folder or directory to hold all the material that will be available at your
Web site. On the Mac, choose File > New Folder in the Finder (Figure 2.18). In
Windows, from the Desktop, choose File > New > Folder (Figure 2.19).
Figure 2.18. On a Mac, choose New Folder, and then give the folder a name.
Then create a separate folder for each section of your site.
Page 52 of 654
2. Give the folder a name and divide it in a way that reflects the organization of your Web
site (Figure 2.20).
Figure 2.20. Give the folder a name. Then divide it into additional folders if
needed. You can use the Windows Explorer (as shown here) to display the
complete hierarchy of your site.
3. You may decide to create a separate folder for each section of your site, along with
individual subfolders for images and other external files.
4. You can create a top-level images folder for images that are common to all areas of your
Web site.
Tip
o Use simple, one-word names without symbols or punctuation for your files and
folders. Use all lowercase letters so that your URLs are easier to type and thus your
pages are easier to reach. For more details on how to create good file names, consult
File Names on page 32.
Page 53 of 654
Once you've created a page, you'll want to see what it looks like in a browser. In fact, since you
don't know which browser your visitors will be using, it's a good idea to look at the page in
several browsers.
1. Open a browser.
2. Choose File > Open, Open File, or Open Page (just not Open Location), depending on the
browser (Figure 2.21).
Figure 2.21. From the desired browser (this is Netscape for Windows),
choose File > Open Page. In Explorer for Windows, it's called File > Open.
In Explorer for Mac, it's File > Open File.
3. In the dialog box that appears, either type the location of the page on your hard disk, or
click Browse (IE) or Choose File (Netscape) to find it (Figure 2.22).
4. If you've clicked Browse or Choose File in step 3, in the new dialog box that appears,
navigate to the folder on your hard disk that contains the desired Web page and click
Open (Figure 2.23).
Figure 2.23. Choose the file that you want to open and click the Open
button.
Page 54 of 654
5. Back in the Open Page dialog box, click Open. The page is displayed in the browser just
as it will appear when you actually publish it on the server (see page 405).
Tips
o You can (usually) also double-click a Web page's icon to view it in a browser.
o If your Web page does not appear in the Open dialog box, make sure that you have
saved it as Text Only and given it the .htm or .html extension (see page 50).
o You don't have to close the document in the text editor before you view it with a
browser, though you do have to save it.
o It is generally not necessary to publish your pages on the server before you view
them.
Figure 2.24. The page appears in the browser. Check it over well
to see if it's coming out the way you planned.
Page 55 of 654
One of the easiest ways to expand your (X)HTML fluency is by looking at how other page
designers have created their pages. Luckily, (X)HTML code is easy to view and learn from.
However, text content, graphics, sounds, video, and other external files may be copyrighted. As a
general rule, use other designers' pages for inspiration with your (X)HTML, and then create your
own contents.
Figure 2.25. All browsers have a menu command that lets you view a page's
(X)HTML code. The name varies from Page Source (in Netscape, shown) to
View Source, to just Source.
Figure 2.26. Most browsers will also let you right-click (click and hold on a
Mac) and choose the Source command (however it's called) from the pop-
up menu that appears.
Page 56 of 654
Figure 2.27. Some browsers display the code in the specified text editor.
Others, like Netscape, let you choose between the default window right
inside the browser or your preferred text editor.
Tips
o You can also save the source code by selecting File > Save As and then HTML
Source in the Format pop-up menu in the dialog box that appears.
Page 57 of 654
o Most browsers also let you right-click (or click and hold on a Mac) and then choose
a source command (of varying wording) from the pop-up menu (Figure 2.26). This
is also a good way to look at the code for a frame (which you'll learn about in
Chapter 15, Frames).
o Although there are JavaScript scripts that can make it more difficult (for Windows
folks, but not for Mac users), there's no real way to keep people from looking at a
Web page's source code. Instead, you might want to add a copyright notice,
encourage people to link instead of stealing, and do periodical searches of key
phrases in your documents.
Page 58 of 654
Chapter 3. Basic (X)HTML Structure
This chapter covers the most basic (X)HTML elements—the ones you need to create the structure
of your document. You'll learn how to create new paragraphs, headers, page breaks, comments,
and more.
Creating a clear and consistent structure makes it that much easier to apply styles to your
document.
Figure 3.1 Here's the DOCTYPE for a transitional HTML document as well as the
opening and closing html tags. It's a gruesome bit of text. I recommend just
copying it from one document to the next instead of trying to type all that
gobbledy-gook.
"http://www.w3.org/TR/html4/loose.dtd ">
<html>
Page 59 of 654
</html>
Tips
o Both the DOCTYPE and the html element are optional in HTML (even strict
HTML). XHTML requires both (with the namespace declaration in the opening
html tag). Note that there is no xhtml element.
o I've only shown how to write the DOCTYPE for transitional HTML and XHTML.
You can find a list of common DOCTYPE declarations on my Web site (see page
24) or at http://www.w3.org. For help choosing an appropriate DOCTYPE, see page
38.
o Create a template with the appropriate DOCTYPE declaration and html tag as a
starting point for all your pages.
o Declaring a DOCTYPE with a URL at the top of your Web page generally puts
current browsers in standards mode—letting you use standards-compliant code in
order to have more control over the display of your Web page (see page 39).
o If you start an XHTML page with the xml declaration, IE 6 for Windows goes into
quirks mode. That's a huge bug. The workaround? Skip the (optional) declaration
and declare the encoding with the meta tag instead (see page 63).
o If you use non-standard HTML tags, there's no point in specifying a DOCTYPE .
Just enclose your page in opening and closing html tags. Current browsers will
use quirks mode when displaying your pages, letting you take advantage of old,
soon-to-be-obsolete bugs (see page 39).
o Declaring the appropriate DOCTYPE tells validators which specifications to
compare your code against (see page 394).
o Note that the word DOCTYPE (since it actually originated from another language
called SGML) is typed in all uppercase letters, both in HTML and in XHTML.
Figure 3.2 Here's the DOCTYPE for a transitional XHTML document, the opening
html tag and required namespace declaration, and the closing html tag. Ugh!
</html>
Page 60 of 654
To create the head section:
1. Directly after the opening html tag (see page 60), type <head>.
2. Leave a few spaces for the contents of the head section.
3. Type </head>.
The body of your (X)HTML document encloses the content of your Web page, that is, the part that
your visitors will see, including the text and graphics.
Figure 3.3 The head and body elements help you structure your (X)HTML
documents.
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
</body>
</html>
Tips
o The head and body tags are required in XHTML. They're optional in HTML but
even if you don't physically type them, the browser acts as if they are there and even
lets you assign styles to them.
o Another reason to use head and body tags is for controlling when a particular
script will run (see page 314).
Page 61 of 654
To declare the character encoding:
Tips
• Your Web page's character encoding depends on the way you saved it. If you
saved it as Text Only—that is, you didn't choose a special encoding—it's a
safe bet that your document was saved with the default encoding for your
language. For example, the default encoding for English Windows is
windows-1252 and for English Macintosh is x-mac-roman.
• If you chose a particular encoding upon saving the file, that's the encoding you
should use in the meta tag.
• You can find a list of common character set codes at
http://www.w3.org/International/O-charset-lang.html.
• XHTML requires that you declare the encoding if it is anything other than the
default UTF-8 or UTF-16. You can use either the xml declaration (see page
60) or the meta tag described above.
• For more about encodings, see Chapter 20, Symbols and Non-English
Characters.
Figure 3.4. I've saved my files in Unicode, with the UTF-8 encoding. (This is BBEdit.
For more details about saving files with encodings other than the default for your
system, consult Chapter 20, Symbols and Non-English Characters.)
Figure 3.5 When the visitor's browser sees this meta tag, it will know that the page
was encoded with UTF-8, and will display it properly. The key is that the encoding
that you declare in the meta tag match the one with which you actually saved the
file.
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
Page 62 of 654
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
Creating a Title
Each (X)HTML page must have a title element. A title should be short and descriptive. In
most browsers, the title appears in the title bar of the window (Figure 3.7). Perhaps even more
importantly, the title is used by search indexes like Yahoo and Google as well as in your visitors'
browsers' history lists and bookmarks.
Figure 3.6 The title element should be placed in the head section. It is required.
<head>
<meta http-equiv="content-type" content="text/html;
charset=utf-8" />
<title>Antoni Gaudí - Introduction</title>
</head>
<body>
</body>
Figure 3.7. The title of a Web page is shown in the title bar of the window.
To create a title:
1. Place the cursor between the opening and closing head tags (see page 62).
2. Type <title>.
3. Enter the title of your web page.
Page 63 of 654
4. Type </title>.
Tips
• The title is also used in History lists, Favorites lists, and Bookmarks menus to
identify your page (Figure 3.9).
Figure 3.9. The title also appears in your visitor's History pane
(shown), Favorites list, and Bookmarks list.
• If your title contains special characters like accents or some symbols, they'll
either have to be part of your encoding (see page 63) or you'll have to write
them with references (see page 340).
Page 64 of 654
</body>
</html>
1. In the body section of your (X)HTML document, type <hn>, where n is a number from 1
to 6, depending on the level of header that you want to create.
2. Type the contents of the header.
3. Type </hn> where n is the same number used in step 1.
Figure 3.10 You can use headers to give your document structure, like an outline.
<head>
<meta http-equiv="content-type" content="text/html;
charset=utf-8" />
<title>Antoni Gaudí - Introduction</title>
</head>
<body>
<h1>Antoni Gaudí</h1>
</body>
Figure 3.11. The most common default display for first level headers is 24 pixels,
Times New Roman, in boldface.
Page 65 of 654
Tips
1. Type <p>.
2. Type the contents of the new paragraph.
3. Type </p> to end the paragraph.
Figure 3.12 Enclose each paragraph in opening and closing p tags. If you don't
close them (which is perfectly legal in HTML but not XHTML), styles won't be
applied properly.
Figure 3.13. The amount of space inserted by default with a p tag depends on the
size of the text surrounding it.
Page 66 of 654
Tips
Naming Elements
You can give your HTML elements either a unique name or one that identifies them as belonging
to a particular class. You can then apply styles to all elements with a given name.
Within the opening tag of the element, type id="name", where name uniquely identifies the
element.
Page 67 of 654
Within the opening tag of the element, type class="name", where name is the identifying name of
the class.
Tips
Figure 3.14 There is one large enclosing division (that begins with the level one
header and goes to just before the closing body tag) and two inner divisions (that
include the level two headers and corresponding paragraphs).
<div class="works">
<h2>La Casa Milà</h2>
<p>Gaudí's work was essentially useful. La Casa Mil à is an
apartment building and real
people live there.</p>
</div>
<div class="works">
Page 68 of 654
<h2>La Sagrada Família</h2>
<p>The complicatedly named and curiously unfinished
Expiatory Temple of the Sacred Family
is the most visited building in Barcelona. </p>
</div>
</div>
</body></html>
Figure 3.15. You generally can't see the effect of divisions until you add styles (see
page 147). Then they really shine. You can see this page with styles on my Web
site (see page 24).
Tips
o A division is a block-level element. That means that its contents automatically start
on a new line.
o In fact, the line breaks are the only formatting inherent to a division. Apply
additional formatting by assigning styles to the division's class or id.
o You're not required to label each division with a class or id, though they're much
more powerful if you do.
o You may apply both a class and id attribute to the same div element, although
it's probably more usual to apply one or the other. The principal difference is that
class is for a group of elements while id is for identifying individual, unique
elements.
Page 69 of 654
Creating Inline Spans
While you can organize big chunks of your Web page into head and body sections, into divisions,
or even with headers (h1, h2, etc.), you can name smaller chunks or spans of text or other inline
elements in order to identify them and apply styles to them.
Figure 3.16 The span tag is used to mark a bunch of inline content, usually, but
not always, text. You can then format the marked text however you like (which we'll
do in Chapters 10 and 11).
<div class="works">
<h2>La Casa Milà</h2>
<p>Gaudí's work was essentially useful. La Casa Mil à is an
apartment building and
<span class="emph">real people</span> live there.</p>
</div>
<div class="works">
<h2>La Sagrada Família</h2>
<p>The complicatedly named and curiously unfinished
Expiatory Temple of the Sacred Family
is the <span class="emph">most visited</span> building in
Barcelona. </p>
</div>
</div>
</body></html>
Figure 3.17. Again, the span element gives your document underlying structure.
You can't see its effect until you apply styles (see page 147). You can see this page
with styles on my Web site (see page 24).
Page 70 of 654
Tips
o For more details on the difference between block-level and inline content, consult
Block vs Inline on page 28.
o A span has no inherent formatting. It becomes useful when you apply styles to it
(generally through its class or id).
o You may apply both a class and id attribute to the same span element,
although it's probably more usual to apply one or the other. The principal difference
is that class is for a group of elements while id is for identifying individual,
unique elements.
The br tag is perfect for poems or other short lines of text that should appear one after another
without a lot of space in between.
Type <br /> where the line break should occur. There is no separate closing br tag.
Figure 3.18 I've created a new division at the top of the page that can serve as a
table of contents. There will be three lines (thanks to the br tag) with the minimum
of space between each one.
Page 71 of 654
[View full width]
<body>
<div id="toc">Antoni Gaudí<br />La Casa Milà<br />La Sagrada
Família</div>
<div id="gaudi">
<h1>Antoni Gaudí</h1>
<p>Many tourists are drawn to Barcelona to see Antoni
Gaudí's incredible architecture. </p>
<p>Barcelona celebrates the 150th anniversary of Gaud í's
birth in 2002.</p>
<div class="works">
<h2>La Casa Milà</h2>
<p>Gaudí's work was essentially useful. La Casa Mil à is an
apartment building and <span
class="emph">real people</span> live there.</p>
</div>
Figure 3.19 Remember that the returns in your code are always ignored. This code
is equivalent to that shown above in Figure 3.18.
<body>
<div id="toc">Antoni Gaudí
<br />La Casa Milà
<br />La Sagrada Família</div>
Figure 3.20. The br element starts the subsequent elements on a new line.
Page 72 of 654
Tips
o The closing slash (/) is only required in XHTML documents to satisfy the rule that
all elements be properly closed (see page 36). Make sure there is a space between br
and the slash. You may omit the slash entirely in HTML documents, though it does
no harm to include it.
o You can use multiple br tags to create extra space between lines or paragraphs.
o Styles can help you control the space between lines in a paragraph (see page 164)
and between the paragraphs themselves (see pages 188 and 189). There are also a
slew of non-standard and deprecated methods.
o The br tag used to be used with the deprecated clear attribute to control text that
is wrapped around images (see page 112). Its function has been replaced by the CSS
clear property (see page 195).
o The CSS white-space property is great for maintaining original page breaks
(see page 170). Also see page 358 for details on the non-standard nobr element.
Adding Comments
You can add comments to your (X)HTML documents in order to remind yourself (or future
editors) what you were trying to achieve with your (X)HTML tags. These comments only appear
when the document is opened with a text editor. They are invisible to visitors in the browser.
1. In your (X)HTML document, where you wish to insert comments, type <!--.
2. Type the comments.
3. Type --> to complete the commented text.
Figure 3.21 Comments are a great way to add reminders to your text. You can also
use them to keep track of revisions.
<div class="works">
<h2>La Casa Milà</h2>
<p>Gaudí's work was essentially useful. La Casa Mil à is an
apartment building and <span
class="emph">real people</span> live there.</p>
</div>
Page 73 of 654
<div class="works">
<h2>La Sagrada Família</h2>
<p>The complicatedly named and curiously unfinished
Expiatory Temple of the Sacred Family
is the <span class="emph">most visited</span> building in
Barcelona. </p> </div> </div> </
body></html>
Figure 3.22. Comments are invisible (though they readily appear when the source
code is displayed—see page 57).
Tips
o Comments are particularly useful for describing why you used a particular tag and
what effect you were hoping to achieve.
o Another good use for comments is to remind yourself (or future editors) to include,
remove, or update certain sections.
o You should view your commented page with a browser before publishing to avoid
sharing your (possibly) private comments with your public.
o Beware, however, of comments that are too private. While invisible in the browser,
they cheerfully reappear when the user saves the page as (X)HTML code (source).
For more information on viewing a page's code, consult The Inspiration of Others
on page 57.
o Comments may not be nested within other comments.
Page 74 of 654
In the (X)HTML tag for the item you want to label, add title="label", where label is the text that
should appear in the tool tip when a visitor points at the element.
Figure 3.23 You can add a title to any element you wish.
<div class="works">
<h2>La Casa Milà</h2>
<p>Gaudí's work was essentially useful. La Casa Mil à is an
apartment building and <span
class="emph">real people</span> live there.</p>
</div>
<div class="works">
<h2>La Sagrada Família</h2>
<p>The complicatedly named and curiously unfinished
Expiatory Temple of the Sacred Family
is the <span class="emph">most visited</span> building in
Barcelona. </p>
Figure 3.24. When your visitors point at the labeled element, the title will appear.
Page 75 of 654
Tip
o Explorer for Windows also makes popup labels or tool tips out of the alt attribute
used in image tags (see page 105). However, if both the title and alt attributes
are present in an image tag, the tool tip is set to the contents of the title tag, not
the alt tag. So, if you don't want Explorer for Windows to use your alt tag as a
tool tip, use an empty title:title="".
Why should you use basic (X)HTML formatting instead of CSS? There are two main reasons.
First, most of the elements discussed in this chapter are logical elements, that is, they give
structure to your document by describing what they contain. For example, the code element is
specifically designed for formatting lines of code from a script or program. While it formats such
content in a monospace font, it also more importantly identifies the text as code.
The second reason to use the basic formatting elements in this chapter is because CSS is
sometimes too big a bazooka for the job. If you want to highlight a word or phrase on your page,
instead of enclosing it in a span element with a particular class and then creating a style sheet for
that class, you can just wrap it in a simple formatting element and be done with it.
There are a number of formatting elements—for changing the font, size, and color, for example—
that, while still legal and supported, are being phased out of (X)HTML in favor of style sheets. I
discuss these (and the pros and cons of using them) in Chapter 21, Formatting: The Old Way.
1. Type <b>.
2. Type the text that you want to make bold.
3. Type </b>.
1. Type <i>.
2. Type the text that you want to make italic.
3. Type </i>.
Figure 4.1 You may use bold or italic formatting anywhere in your HTML document,
except in the title.
Page 76 of 654
<p>Barcelona is such a great place to live. People there
really put a premium on <b>
socializing</b>. Imagine it being more important to go out
with your friends than to get
that big promotion. Even when you're, gasp, <i>pushing
30</i>. They say there are more bars in Barcelona than in
the rest of the
European community <i>combined</i>.</p>
Figure 4.2. Bold and italic formatting are the simplest and most effective ways to
make your text stand out.
Tips
• You can also use the less common em and strong tags to format text
(Figures 4.3 and 4.4). These are logical formatting tags for "emphasizing"
text or marking it as "strong". In most browsers, em is displayed in italics and
strong in bold. Both require opening (<em>, <strong>) and closing
tags (</em>, </strong> ).
Figure 4.3 If you prefer, you can use the em and strong tags for
emphasizing text.
Page 77 of 654
Figure 4.4. Most browsers display em with italics and strong
with bold.
o You may use cite (for citations), dfn (for definitions), and var (for variables)
to make text italic, although they are less widely used than the i tag.
o The address tag—old-fashioned but still valid—is another logical tag for
making text italic. It's usually only used to format the Web page designer's e-mail
address.
o For more control over bold and italics, try style sheets. For details, consult Creating
Italics on page 160 and Applying Bold Formatting on page 161.
1. Type <big> or <small> before the text that you wish to make bigger or smaller,
respectively.
2. Type the text that should be bigger or smaller.
3. Type </big> or </small> according to the tag used in step 1.
Figure 4.5 The big and small tags are a fast and easy way to make text stand out.
Page 78 of 654
<p><big>Don't get me wrong,</big> I don't mean that everyone
gets drunk all the time--bars are for hanging out and
talking
or for having a cup of coffee (espresso, of course).</p>
Figure 4.6. The big and small elements enjoy wide support. They have identical
effects in most browsers (Netscape above, Explorer below).
Tips
Page 79 of 654
o Of course, big and small are relative, and the specifications do not dictate just how
much bigger or smaller browsers are supposed to make the text. In general, they
stick to typical font sizes, like 8, 9, 10, 12, 14, 16, 18, 24, 36, and 48, moving one
step up or down the ladder depending on the element used. The default size for most
browsers is 16px.
o Although the big and small tags have not been deprecated in (X)HTML, you
may still want to use style sheets in order to have more control over the size of the
text. For more information, consult Setting the Font Size on page 162.
o Both the big and small tags have a cumulative effect if used more than once. So
<small><small>teensy text</small> </small> would be two sizes smaller than
surrounding text.
The tt element (it stands for typewriter text) is the most common monospaced font tag. Use code
for formatting computer code in languages like C or Perl. Use kbd for formatting keyboard
instructions. And samp is for displaying sample text. None of these tags is used very often. The
truth is that monospaced text is kind of ugly.
Figure 4.7 The code element not only formats its contents with a monospaced font
but also indicates that the contents are computer code. It's a logical tag.
<p><code>#!/usr/local/bin/perl</code></p>
Figure 4.8. Monospaced text is perfect for URLs and computer code and anything
else that should look kind of geeky.
Page 80 of 654
Figure 4.9. Any text tagged with code, kbd, samp, or tt will be displayed in the
font that your visitors have chosen for monospaced text for their browser. The
dialog box shown here is the Windows Fonts box. It appears when you choose
Tools > Internet Options from Explorer and then click the Fonts button in the
General tab.
Tips
o Remember that the monospaced font tags will not have a very dramatic effect in
browsers that display all their text in monospaced fonts (like Lynx:
http://www.delorie.com/web/lynxview.html).
o You can also format several lines of monospaced text with the pre tag (see page
77).
o You can apply any font (that your visitor has installed) to your text with styles (see
page 158).
Page 81 of 654
Usually, browsers eliminate all extra returns and spaces and automatically create line breaks
according to the size of the window. Preformatted text lets you maintain the original line breaks
and spacing that you've inserted in the text. It is ideal for code, poetry, homemade tables, and
ASCII art.
1. Type <pre>.
2. Type or copy the text that you wish to display as is, with all the necessary spaces, returns,
and line breaks.
3. Type </pre>.
Figure 4.10 The pre element is ideal for text that contains important spaces and
line breaks, like the chunk of Perl CGI code shown above.
<p>Here's the first part of the Cat and Otter Bistro script
(see the WAP/WML chapter),
where the variables are declared, and the $number variable
is screened to make sure it's
actually a number:
$number =~ /([0-9]*)/ ;
$number = $1;
</pre>
Figure 4.11. Notice how the line breaks, including the extra return between the
third and fourth lines of code, are maintained.
Page 82 of 654
Tips
o Preformatted text is generally displayed with a monospaced font like Courier. You
can use styles to change the font, if you like (see page 158).
o You can insert additional formatting within preformatted text. However, you should
do it after you set up your preformatted text, since the tags take up space in the
(X)HTML document, but not in the page.
o If what you want to display contains (X)HTML elements, you'll have to substitute
the appropriate character entities for the greater than and less than signs (namely
> and <, respectively). Otherwise the browser will try to display those
elements; the pre tag works no magic on them. For more information, consult
Adding Characters from Outside the Encoding on page 340.
o You can also use styles to maintain line breaks and spaces (see page 170).
o Note that pre is block-level while the tags on page 76 are all inline.
Quoting Text
There are two special tags for marking quoted text so that you can identify its author, origin, and
language. Block-level quotes are generally indented by browsers. Inline quotes are supposed to be
automatically enclosed in quotation marks and thus, you should not include them in the text.
Figure 4.12 A block quote can be as short or as long as you need. You can even
divide it into various paragraphs by adding p tags as necessary.
<blockquote cite="http://www.kingsolver.com">
Page 83 of 654
<p>It's not hard to figure out what's good for kids, but
amid the noise of an
increasingly antichild political climate, it can be hard to
remember just to go ahead and
do it: for example, to vote to raise your school district's
budget, even though you'll
pay higher taxes. (If you're earning enough to pay taxes at
all, I promise, the school
needs those few bucks more than you do.) To support
legislators who care more about
afterschool programs, affordable health care, and libraries
than about military budgets
and the Dow Jones industrial average. To volunteer time and
skills at your neighborhood
school and also the school across town. To decide to notice,
rather than ignore it, when
a neighbor is losing it with her kids, and offer to babysit
twice a week. This is not
interference. Getting between a ball player and a ball is
interference. The ball is
inanimate.</p>
</blockquote>
Figure 4.13. Block quotes are generally indented from both sides. The cite
attribute is not yet supported by any browser I've seen.
Page 84 of 654
Figure 4.14 The lang attribute in the html tag is supposed to be a default for the
other tags. In my tests, it does serve as a default, but can't quite be overridden.
[snip]
<p>And then she said <q>Have you read Kingsolver's <q> High
Tide in Tucson </q>
? It's inspiring.</q></p>
Figure 4.15. If you specify "en" for the lang attribute in the html element,
Explorer for Mac uses curly quotes. Note how the inner quotes are single in the
English quote, but all of the quotes are double in the French quote.
Figure 4.16 This time, we use "fr" for the lang attribute in the html tag. (And
please, pardon my French!)
Figure 4.17. Now we've got those cute guillemet quotes around everything except
nested quotes—which might be OK if the document is all French.
Page 85 of 654
Tips
o Text and inline elements should not be placed directly between the opening and
closing blockquote tags. Instead, enclose the text and inline elements in a
blocklevel tag—like p, for example—within the blockquote tags.
o You can nest both blockquote and q elements. Nested q elements should
automatically have the appropriate quotation marks—in English the outer quotes
should be double and the inner ones should be single.
o Proper support for q varies widely from one browser to the next. Explorer 5 for
Mac is best, using curly quotes and nesting them properly, and even using
guillemets («») for French (as long as you set the lang attribute in the html tag).
Netscape 6 Mac/Win uses straight double quotes for everything except nested q
elements, where it uses single straight quotes. Opera 5 Mac/Win uses straight
double quotes for everything, including nested q elements. Explorer for Windows
(up to and including version 6) ignores the q element completely.
o The cite attribute may also be used with the q element, although it makes less
sense. I haven't seen a browser that does anything with it in either element.
o For more details on the xml:lang and lang attributes, consult Specifying Your
Page's Language on page 342.
o You can find a complete list of language codes at
http://www.w3.org/WAI/ER/IG/ert/iso639.htm.
Figure 4.18 The opening sup or sub tag precedes the text to be affected.
<h1>Famous Catalans</h1>
Page 86 of 654
<p>When I was in the sixth grade, I played the cello. There
was a teacher at school who
always used to ask me if I knew who "Pablo Casals" was. I
didn't at the time (although I
had met Rostropovich once at a concert). Actually, Pablo
Casals' real name was <i>Pau</i>
Casals, Pau being the Catalan equivalent of Pablo
<sup>1</sup>.</p>
Figure 4.19. Unfortunately, the sub and sup elements spoil the line spacing.
Notice that there is more space between lines 3 and 4 of the first paragraph and
lines 1 and 2 of the second than between the other lines.
Figure 4.20. You can use styles to adjust the size and leading so that the lines are
properly spaced.
Page 87 of 654
Tips
1. Type <ins>.
2. Type the new text.
3. Type </ins>.
1. Place the cursor before the text you wish to mark as deleted.
2. Type <del>.
3. Place the cursor after the text you wish to mark as deleted.
4. Type </del>.
Figure 4.21 You have to be a little bit careful to include the associated punctuation
with the ins and del elements.
Page 88 of 654
litter, and not watch more than <del>six</del> a half
hour<del>s</del> of tv.</big></p>
<p>signed</p>
Tips
o Text marked with the ins tag is generally underlined. Since links are often
underlined as well (if not in your site, in many others), this may be confusing to
visitors. You may want to add an explanation at the beginning of your page and/or
use styles to change how inserted passages (or links) are displayed (see page 157).
o Text marked with the del element is generally stricken out. Why not just erase it
and be done with it? Striking it out makes it easy for others to see what has changed.
o You can also use styles to underline and strike out text (see page 174). The
advantage of the ins and del elements is that they identify the text as being
inserted or deleted, and not just underlined or stricken.
Explaining Abbreviations
Abbreviations and acronyms (an abbreviation that can be pronounced as a word) abound.
Unfortunately, people use them so often that they sometimes forget that not everyone knows what
they mean. You can use the abbr and acronym elements to add meaning to the abbreviation or
acronym in question without breaking the flow of your Web page or distracting your readers with
extra links.
To explain abbreviations:
1. Type <abbr.
2. Next type title="explanation", where explanation gives more details about the
abbreviation.
3. Type >.
4. Then type the abbreviation itself.
5. Finally, finish up with </abbr> or </acronym> depending on what you used in step 1.
Page 89 of 654
Figure 4.23 It seems an awful lot of code for just a few words. Still, it can be very
helpful to get immediate information about an abbreviation, at least the first time it
is used.
Tips
o Netscape 6 (on both platforms) supports both abbr and acronym, highlighting
both elements with a dotted underline and providing the title attribute's contents
as a tool tip (Figure 4.24).
Page 90 of 654
o Explorer for Mac supports just the acronym tag, displaying its contents in small
caps and the title attribute as a tool tip (Figure 4.25), though you have to point
at just the right place. It completely ignores the abbr element.
o Explorer for Windows (up to version 6) supports neither abbr nor acronym
(though it still shows titles as tool tips).
Page 91 of 654
Chapter 5. Creating Web Images
There are many other alternatives, including Paint Shop Pro for Windows by Jasc
Software and GraphicConverter for Macintosh. Feel free to use whatever program you're
most comfortable with.
Let me stress, in addition, that the basic techniques for optimizing images for the Web
are the same regardless of the software you choose. The command names may be
slightly different and there may be more or fewer steps, but the ideas remain the same.
In short, my hope is that this chapter will be useful even if you don't use the same
software that I do.
Creating images for the Web is a bit different from creating images for output on paper. Although
the basic characteristics of Web images and printable images are the same, six main factors
distinguish them: format, color, size/resolution, speed, transparency, and animation. This chapter
will explain the important aspects of each of these six factors and how to use that knowledge to
create the most effective images for your Web site.
Please note, however, that this chapter is no substitute for your image editing program's
documentation. Nor is it meant to be a manual for learning about design. Instead, use this chapter
to learn about the particular components and features that distinguish Web images. Then combine
that knowledge with your computing and design expertise to create awesome images for your
page.
Format
People who print images on paper don't have to worry about what their readers will use to look at
the images. You do. The Web is accessed every day by millions of Macs, Windows-based PCs,
Unix machines, and other kinds of computers. The graphics you use in your Web page should be
in a format that each of these operating systems can recognize. Presently, the two most widely
used formats on the Web are GIF and JPEG, with PNG gaining in popularity. Current versions of
Explorer and Netscape can view all three image formats.
Color
Currently (mid 2002), 50% of the Web surfing public use 24-bit monitors, 40% use 16-bit
monitors, and fewer than 10% (which is still a lot of people) use 8-bit monitors. My guess is that
Page 92 of 654
the first number will continue to rise, while the second two will fall, although probably never all
the way to zero.
What's the difference? 24-bit, or "True Color" monitors can show any one of 16,777,216 colors. In
fact, if the monitor was big enough, you could show every one of those colors on the same 24-bit
monitor. In contrast, while an 8-bit monitor can show the same variety of colors, it can only
display 256 of them at any one time. 16-bit monitors, for their part can display some 65,536
colors. (The details are a bear; it's all about the amount of memory devoted to each pixel.) To
make matters worse, browsers, in order to run faster, take a little shortcut. Instead of showing any
256 colors, on 8-bit monitors they will only display a specific set of 256 colors.
Figure 5.1. Logotypes and other computer-generated images or images with few
colors are compressed efficiently with LZW and thus could be saved in GIF format.
Even better at compressing images of this type is PNG format, but not everyone
supports it.
Figure 5.2. Full-color photographs and other naturally created images, or images
with more than 256 colors, should be saved in JPEG format.
Page 93 of 654
Figure 5.3. Both of these images have exactly 18 colors and look about the same
on high-end monitors. But notice how the dither image is full of noise and
patterning (called dithering) while the safe image is clean and sharp. That's
because this page was viewed on an old 8-bit monitor and the safe image uses
browser-safe colors while the dither image doesn't.
Page 94 of 654
If a browser is called upon to show a color that's out of its range, it has two options: it can mix two
colors to produce the missing one (this is called dithering), or it can shift the missing color to one
in the current set. Sometimes you hardly notice; sometimes it's a disaster.
So, if you don't want your colors to dither or shift on an 8-bit monitor, you have to use one of the
colors in the browser's particular set. However, since browsers reserve a bunch of colors for the
browser window itself, and because the sets for Windows and Mac are slightly different, there are
actually only 216 colors that won't ever dither on browsers on 8-bit monitors on either platform.
These colors are called Web-safe or browser-safe. On the down side, this set of colors, or palette,
offers a very limited choice of colors. (And if that weren't enough, version 4 browsers and earlier
shift them around on 16-bit monitors.)
But since there are fewer and fewer 8-bit monitors, it's seeming less and less important to
completely limit color choice because of them—especially when you may exacerbate a problem
with 16-bit monitors.
My recommendation is to first analyze your Web logs (if you have access to them—ask your ISP)
to gauge your public. What monitors do the people who surf your site use? Then, base your use of
colors on that data. If your numbers match the averages, try to limit dithering and shifts—
particularly in large areas of color—but feel free to take advantage of the other sixteen million
colors!
Check the inside back cover of this book for a handy table for choosing colors. If you'd rather
stick to browser-safe colors, you can find a complete table on my Web site. (Since browser-safe
colors don't print well, it doesn't make sense to include them on the cover.)
Page 95 of 654
Computer images are measured in pixels. Your digital camera, for example, may take pictures that
are 640 pixels wide by 480 pixels high. But how big is that? The answer is, it depends. If you're
printing the image to a printer at 200 ppi (pixels per inch), that image will measure a rather petite
3.2 by 2.4 inches. But if you're using that page on the Web, the image will depend on your visitor's
monitor's resolution, which is more likely to be around 86 ppi (and might be as low as 72 or as
high as 100 or so), and thus will display at a heftier 7.5 x 5.5 inches (about 19 x 14 cm) on screen.
Perhaps a better way to think of image size is with respect to the browser window. Since monitors
with a resolution of 640 pixels wide by 480 pixels high were the standard for so long, browser
manufacturers, and indeed Web page designers, tend to keep their pages under 600 pixels wide, so
that viewers can see the entire contents of the page without scrolling horizontally. So, if you can
envision the width of a basic browser window (say, just to the end of the navigation bar), then you
know approximately how big 640 pixels is and can plan your images accordingly.
Don't forget of course, that plenty of people have bigger monitors (1024 x 768 is not unusual) and
more than a few have smaller. Still, just because someone has a bigger monitor doesn't mean
they're going to fill it with a single browser window containing your Web page.
Note that resolution can mean one of two quite distinct concepts: the actual number of pixels on a
monitor or in an image, say 640 x 480, or the number of pixels in an inch of that monitor or
image, say 72 or 86 ppi. Regardless, the higher the resolution, the more pixels. On paper, pixels
can add details or size. On screen, more pixels always translate to a bigger size image.
Figure 5.4. This particular image is 1704 pixels wide and in Photoshop has an
output resolution of 284 ppi and only measures 6 x 8 inches. Here in Explorer on
this monitor, however, its output resolution is determined by the visitor's
monitor—about 86ppi—which means that the picture is about 20 inches wide!
Page 96 of 654
Figure 5.5. This image also measures 6 x 8 inches in Photoshop, though it has an
output resolution of 50ppi. Again, however, these relative measurements are
irrelevant. What counts is that it measures 300 pixels wide, which is about half the
width of an average browser window.
Speed
The next principal difference between Web images and printed images is that your visitors have to
wait for Web images to download. (Imagine waiting for pictures to appear in your morning
paper!)
How can you keep download time to a minimum? The easiest way is to use small images. The
larger an image's file size, the longer it takes to appear before your visitors' eyes.
The second way to speed up download time is by compressing the image. There are three popular
compression methods (that correspond to the three major formats): LZW (for GIF images), JPEG,
and PNG. LZW is particularly effective for computer-generated art like logos, rendered text, and
other images that have large areas of a single color. In fact, if you can reduce the number of colors
in an image, LZW can often (but not always) compress the image even more.
JPEG, on the other hand, is better at compressing photographs and other images that have many
different colors. In fact, if you blur an image, thereby creating even more colors, JPEG
compression is often more effective (see page 100).
Each method has its drawbacks. Because LZW is patented (at least until 2003), developers have to
pay royalties on software that uses it. (This is one of the principal reasons that PNG was
developed.) And GIF images are limited to 256 colors. JPEG has two main disadvantages. First,
its compression information takes up a lot of space and is simply not worth it for very small
images. Second, it is lossy compression—permanently eliminating details in order to save space.
Page 97 of 654
Uncompressing the image will not restore the lost data. If you plan on editing an image in the
future you should save a copy in an uncompressed format (e.g., PSD or TIFF) and only save it as a
JPEG after you have made your final edits.
PNG compresses better than LZW without losing information like JPEG. Its chief weakness is its
limited support in older browsers, though current browsers display PNG images just fine.
Another way to keep your visitors happy while they're waiting is to offer a sneak preview of what
the image will look like. All three major formats offer some form of progressive display, often
called interlacing. For details on progressively rendering images, consult page 99.
Transparency
Transparency is important for two reasons. First, you can use it to create complex layouts by
making one image move behind another. Second, you can take advantage of transparency to give
an image a non-rectangular outline, adding visual interest to your pages (Figure 5.6). Both GIF
and PNG allow transparency; JPEG does not.
Figure 5.6. The courthouse image's transparent background helps the image blend
into the page, no matter what background color the visitor has chosen to view Web
pages against. Real transparency is only available for GIF and PNG images.
Animation
One thing you won't be seeing on paper anytime soon are moving images. On the Web, they're
everywhere. For information on creating animated images, see page 101. Animated images can be
saved in GIF format, but not JPEG. You can also create animation with Flash (see page 464).
Getting Images
So how do you get an image that you can use for your Web page? There are several ways. You
can buy or download ready-made images, digitize photographs or handdrawn images with a
scanner, use a digital camera, or draw images from scratch in an image editing program like
Photoshop. Once you've got them in your computer, you can adapt them to the Web, if necessary,
with the rest of the techniques in this chapter.
To get images:
Page 98 of 654
o Although you can use Google to find images on the Web (clicking the Images button and
entering criteria as usual), the results are not necessarily images you can use on your site.
Instead, do a regular search for "free images".
o Generally, even free images found on the Web are for personal use only and cannot be
modified. Images you buy can usually be used for any purpose (except for reselling the
images themselves). Read any disclaimers or licenses carefully.
o Many companies sell stock photography and images on CD. Such disks often have
several versions of each image for different purposes. Look for the Web or Multimedia
version.
o Many photo processing outfits will develop a roll of film directly onto a CD.
o Scanners and digital cameras have grown in quality as they've plummeted in price. They
are an ideal way to convert print photographs into digital ones, or to create digital ones
from scratch.
o If you create your own images, save them as GIF, JPEG, or PNG. Don't save them as
BMP—only Explorer for Windows users will be able to see them.
In general, images that have been created on a computer, including logos, banners, line
art, text, and any graphic with large areas of a single color and sharp detail should be
saved in GIF or PNG-8 format (Figure 5.7).
Figure 5.7. In this example, the image has a lot of flat color, as well as text,
which should be kept sharp. Both are good reasons to choose GIF format
(lower right), which you can see compresses the image the best, to just
over 2K. JPEG, even at very low quality, doesn't do nearly as well.
Page 99 of 654
Images with continuous tones, like photographs, should be saved in either JPEG or PNG-
24 format (Figure 5.8).
Figure 5.8. The original image is shown in the top left. Since this is a
photograph, the GIF compression is pretty useless (top right). I can choose
between the bottom two JPEG options depending on my bandwidth and
quality constraints.
Tips
• Remember that your main objective is to get the smallest file size possible
while still maintaining acceptable image quality.
• Images should be created in RGB mode, not CMYK (which is for print).
• If you're not sure which format to choose, compare two optimizations and see
which format compresses better while leaving the image at the best quality.
• PNG is a powerful lossless format that can be used for both computer-
generated and "natural" color images. It is often better than GIF but not quite
as good as JPEG. Unfortunately, Photoshop is probably not the best tool for
creating PNG images, as its compression algorithms aren't as tight as they
might be. PNG's other disadvantage is that older browsers don't support it,
although frankly, older browsers don't support much of anything, so it hardly
seems a deciding factor.
• If you have an image with both types of content, you can either slice it into
distinct chunks and compress them separately (and then reassemble them with
a borderless table—see page 215) or you can just use a single format and let it
do its best.
• The Save for Web command creates a new, independent image and leaves the
original image intact. The exception, of course, is if you save the new image
with the same name and extension as the old.
• Only an image's visible layers are saved in the optimized version.
• The Save For Web window varies a bit between Photoshop and Photoshop
Elements (and between versions of these) but the key commands stay the same
(Figure 5.9).
1. In the lower right portion of the Save For Web window, click the Image Size tab.
2. Enter a new width or height in pixels, or a percentage, and then click Apply.
Figure 5.10. The original image, snapped with my digital camera's default values
measured 1600 by 1200 pixels, which besides being big enough for almost three
browsers, weighed in at a whopping 192.2K, even when compressed as a medium
quality JPEG. Instead, type the desired new width of 200 pixels in the Width box
and click Apply.
Figure 5.11. The reduced-size image will fit properly on my page and will take only
4 seconds to download at 28.8Kbps (less with a faster connection).
o You can continue to adjust the size up or down until you're satisfied. The image is
not actually resampled until you press OK or Save.
o Don't use this technique to make an image bigger than its original. Adding pixels
with Photoshop increases the file size but doesn't add any image data. If you must
increase the image's size, use (X)HTML (see page 108) or better yet, rescan or
redigitize your image.
o You can also use the Image Size command to change the size of an image.
Remember that the Resolution box is irrelevant (it refers to the output resolution,
which is determined on the Web not by you or Photoshop, but rather by the visitor's
monitor). Instead, base the size on the number of pixels in the image. You will have
to check the Resample Image box to get it to change the image's size (as opposed to
its output resolution).
o Before you make images proportionally smaller, be sure to crop them to eliminate
any unwanted areas.
Creating Transparency
Transparency allows the background to shine through the affected areas often creating a more
interesting layout. Images with transparent areas can be saved either in GIF or PNG format, but
not JPEG.
In Photoshop and Photoshop Elements, you create transparency in an image and then you indicate
that you want that area to be transparent in the Save For Web window. In addition, if you know
what color will be showing through the transparent areas, you can have Photoshop create a smooth
transition from the image to the transparent areas, using the background color. This is called a
matte.
1. Choose File > New to create a new document and click the Transparent button at the
bottom of the New dialog box to start with a transparent background (Figure 5.12). Then
click OK.
Figure 5.12. Choose File > New to create a new image being sure to check
the Transparent box at the bottom of the New dialog box to start with a
transparent background.
2. Create the image in the normal way, leaving part of the background transparent.
Or...
Figure 5.13. Select the desired portion of an existing image (left) and then
choose Edit > Copy.
Figure 5.14. Choose Edit > Paste to create a new layer with the copied
image. Notice how the background around the pig's head at right is
transparent (shown with checkered pattern).
Or...
You may have to combine the two techniques, for example, pasting a new layer into a new
document with a transparent background.
1. In the Save For Web window, choose the GIF or PNG-8 format.
2. Click Transparency (Figure 5.15).
Figure 5.15. Once you're satisfied with the image that contains transparent
areas, choose File > Save for Web, choose a format that supports
transparency (GIF or PNG) and then click the Transparency box.
Figure 5.16. If you know the color of the background upon which the image
will go, select it in the Matte menu. This will create a smooth transition
between the image and the background color.
Figure 5.17. Here's the result. Both the title and the left pig were created with a
matte set to the background color of this Web page and thus have smooth
borders. The right pig was created with no matte and thus has a hard, sometimes
jagged border.
Tips
o In Photoshop, but not Photoshop Elements, you can select individual colors from
the Color Table and convert them to transparency.
o While creating titles out of GIF images lets you use fancy fonts, it has a number of
disadvantages: namely, that search engines can't read them (see page 416) and
they're a bit of a hassle to update. If you insist, at least be sure to set the Matte to the
background color of your page, otherwise the text will look jagged and any benefit
from the nice font is lost.
Simulating Transparency
Simulating transparency means making the image's background the same color as the background
of your page so that the image blends in as if the background were transparent. It's useful in JPEG
images which don't allow real transparency.
2. Click the foreground color control box to set it to the desired color.
3. Press Option-Delete (Alt-Delete on Windows) to change the color of the selected area
(the background) to the selected color (Figure 5.19).
Figure 5.19. Once the background is selected, choose the desired color in
the foreground color box (the upper of the two boxes at the bottom of the
toolbar) and then press Option-Delete (or Alt-Delete if you're on Windows).
The background is changed to the desired color.
Figure 5.20. This time the pig looks like it's on a transparent background, but it's
actually not. It's on a background that matches the Web page's background.
Tips
o It's probably a good idea to choose a browser safe color for the background (though
I didn't in this example). Otherwise, it will dither on 256-color monitors. For more
details, consult Using (Mostly) Browser Safe Colors on page 96.
o Since JPEG compresses photographs much better than GIFs, this is a way to
simulate transparency on files that have too many colors to be effectively
compressed as GIFs.
o Of course, if your visitors override the background color, the effect is lost.
Before getting rid of dither, it's helpful to know if it's a problem. Photoshop has a helpful, if rather
hidden option to preview dither.
To preview dither:
1. If necessary, select the desired optimized GIF image in the Save For Web window.
2. Choose Browser Dither—in the pop-up menu that descends from the triangle in the top-
right corner of the image area (Figure 5.21)—to preview how the selected optimized
image will appear on an 8-bit monitor (Figure 5.22).
1.
In the Save For Web window, choose Web in the Dither pattern menu (Figure 5.23). All colors in
the image are converted to Web-safe colors, which may or may not be close substitutes.
Figure 5.23. In Photoshop Elements, your only recourse is to change all of the
colors in the image to Web-safe colors by choosing Web in the Dither pattern
menu in the top right area of the Save For Web window. And in this example, the
result is a non-dithered image. Remember that most monitors are 16 and 24-bit
which never dither images. (The Web option for Dither is available in Photoshop as
well.)
Figure 5.24. In Photoshop only, select the eyedropper (from the top left) and
then click in the color that's getting dithered. Notice how the color is
selected in the Color Table at right.
Figure 5.25. Then click the little cube at the bottom of the Color Table
(second icon from the left) to shift the selected color to its nearest Web-
safe substitute.
Figure 5.26. Instead of changing all the colors, we change only the color that was
dithering badly.
Tips
1. In the Save For Web window, choose GIF or PNG-8 in the Format menu (Figure 5.27).
Figure 5.28. Select a reduced number of colors in the Colors pop-up menu
in the top-right part of the window. Reducing the colors in this admittedly
large image saved an impressive 31.1K and 11 seconds of download time.
Tip
In the Save For Web window, check the Interlaced box for GIF or PNG formats (Figure 5.29) or
the Progressive box for JPEG.
Figure 5.29. Choose GIF or PNG and then click the Interlaced box. Or choose JPEG
and then click Progressive.
Figure 5.30. In both Photoshop and Photoshop Elements, you can select part of
your image and then choose Filter > Blur > Gaussian Blur.
(Photoshop Only) In the Save For Web window, adjust the Blur slider. Keep an eye on the ratio of
quality vs. file size (Figures 5.31 and 5.32).
Figure 5.31. By default, no Blur is applied. This image will occupy 58.74K and take
22 seconds to download. Note that we've lost the transparency since we're saving
in JPEG.
Tips
o This is one of those cases in which a little goes a long way. You don't need to blur
the image beyond recognition to get file size savings.
o You have to decide if the loss of detail is worth faster download times and less
waiting for your visitors. If all your visitors use 14K modems on 256-bit monitors,
this technique may be very useful. Visitors with T1 lines on high-end systems, on
the other hand, may not benefit enough from the speed improvement to make
sacrificing image sharpness worthwhile.
o You can make a selection before applying the Gaussian Blur filter in order to limit
and control what gets blurred. You needn't blur the entire image. (Photoshop's Blur
slider does nothing more than apply a Gaussian Blur to the entire image.)
1. In Photoshop Elements, create each frame of the animated GIF on a separate layer. The
bottom layer corresponds to the first frame, the second to bottom is the second frame, and
so on (Figure 5.33).
Figure 5.34. In the Save For Web window, choose the GIF format, click
Animation and then choose the desired options in the lower part of the
window.
4. Set the number of seconds that should elapse between each frame in the Frame Delay
box.
Tips
o You insert an animated GIF on your page just like any other image (see page 104).
o I set a frame delay of about one second if the animation's frames contain text. If you
want to animate an actual graphic, you'd probably want to use less.
o Animated GIFs are created essentially the same way in Photoshop, but it relies on
ImageReady (which is included with Photoshop) for saving them.
Figure 6.1 The URL for this image, since it contains only the file name and no path,
indicates that the image is located in the same folder as this Web page.
Figure 6.2. Images are aligned to the left side of the page, by default. You can
change the alignment or wrap text around an image. See page 171 and page 194
for details.
1. Within the img tag, after the src attribute and value, type alt=".
2. Type the text that should appear if, for some reason, the image itself does not.
3. Type ".
Figure 6.3 While the alternate text can theoretically be as long as you like, most
browsers don't automatically wrap long lines. Therefore, it's a good idea to keep it
under 50 characters.
Figure 6.4. The alternate text appears if the image can't be found, if the visitor has
deselected Autoload images, or if the browser doesn't support images.
• The alt attribute is required for all img tags in both XHTML and HTML.
• On IE Win 5+ and Netscape 4.x, the alt tag text is automatically used as a
tool tip (Figure 6.5), similar to the effect of the title tag in all current
browsers (see page 72). If you'd like tool tips on images in all browsers, use
the title tag in addition to alt (which will still appear when the image
does not). If you don't want tool tips at all, set title="".
o If the image is just for formatting, like a horizontal line or a bullet image, the W3C
suggests you use alt="".
o Some browsers, like Lynx, that do not support images, are used by the blind
because they can read the contents of the alt tag out loud. This is just one more
reason to add alternate text to your images.
o You can actually format the alternate text with different fonts and sizes by applying
styles to the img tag. For details on styles, see Chapter 10, Formatting with Styles.
You can either use your browser or your image editing program to get the exact dimensions of
your image.
1. Right-click (in Windows) or Control-click (in Macintosh) the image. A contextual pop-up
menu appears (Figure 6.6).
Figure 6.7. A box appears (its appearance varies depending on the browser
you're using) that shows the dimensions of the image in pixels.
Figure 6.8. If you open an image directly in a browser (this is Explorer 5 for
Mac), its dimensions are displayed in the title bar.
1.
Figure 6.10 If you specify the exact height and width values in pixels, the browser
won't have to spend time doing it and will display the image more quickly.
<p>I love how they stack up the fruit and vegetables. I'm
always tempted to take a pepper
out of the bottom row, but of course, you're not supposed to
touch them at all. Which I
guess makes sense. Sort of. Ok, so you're at the market and
there are ten thousand other
people milling around.
1. Figure out the size of your image using one of the techniques described on page 106.
2. Within the img tag, after the src attribute, type width="x" height="y", using the
values you jotted down in step 1 to specify the values for x and y (the width and height of
your image) in pixels.
Figure 6.11. Notice that the second paragraph of text is displayed even though the
image has not finished loading. This means your visitors will have something to do
while they're waiting.
o The width and height attributes don't necessarily have to reflect the actual size
of the image. For more details, consult Scaling an Image on page 108.
o If you have several images that are all the same size, you can set their height and
width all at the same time with styles (see page 190).
o You can also find the size of an image in a browser by opening the image in its own
window. The size is shown in the title bar (Figure 6.8). (This is the only way to get
the size with Explorer for Mac.)
o In Photoshop or Photoshop Elements, if you Option-click (Alt-click on Windows)
the "Doc" bar in the lower-left corner of the image's window, a small box appears
with information about the image, including its size. If you can't see the "Doc" bar,
make the window larger until it appears.
Scaling an Image
To scale an image:
1. Type <img src="image.url", where image.url is the location on the server of the image
(see page 33).
2. Type width="x" height="y" where x and y are the desired width and height,
respectively, in pixels, of your image.
3. Add any other image attributes as desired and then type the final />.
Figure 6.12. At its original size of 396 by 439 pixels, the image is way too big on the
page.
Figure 6.13 Since the width and height always reflect the dimensions in pixels,
you never explicitly specify the units in (X)HTML.
Figure 6.14. The image appears at half its original size. It's important to note,
however, that it takes the same time to load as before. After all, it's the same file.
Tips
o You can also use a percentage value in step 2, with respect to the browser window
(not the original image size).
o Using the width and height attributes is a quick and dirty way to change how
the image is displayed on a Web page, especially if you don't have an image editor
(or don't have the time or inclination to use it). However, since the file itself is not
changed, the visitor always gets cheated. Reduced images take longer to view than
images that are really that size; enlarged images appear grainy. A better solution is
to use your image editor to change the size of the image (see page 92).
o You can set just the width or just the height and have the browser adjust the other
value proportionally.
1. Place the cursor in your (X)HTML page where you wish the icon to be placed.
2. Type <a href="image.jpg">, where image.jpg is the location of the full-sized image on
your server (see page 33).
3. Type <img src="mini.jpg", where mini.jpg is the location of the thumbnail version on
the server.
4. If desired, type alt="alternate text", where alternate text is the text that should appear if,
for some reason, the thumbnail does not.
5. Type the final /> of the thumbnail definition.
6. If desired, type the label text that should accompany the thumbnail. It's a good idea to
include the actual file size of the full-sized image so the visitor knows what they're
getting into by clicking it.
7. Type </a> to complete the link to the full sized image.
Figure 6.15 Remember to use the full size image in the link and the thumbnail in
the image definition.
Figure 6.16. In this example, the thumbnails are about 4K and take a few seconds
to load. The visitor can choose to view the larger image (by clicking the icon) or to
continue reading the page.
Tip
1. Type <img src="image.jpg" where image.jpg indicates the location of the image on the
server.
2. Either type align="left" to float the image on the left of the screen while the text flows to
the right, or type align="right" to float the image on the right edge of the screen while
the text flows on the left side of the image.
3. Add other image attributes, as described in other parts of this chapter, if desired.
4. Type the final />.
5. Create the elements that should flow next to the image.
Figure 6.18 When you align an image to the right, you are actually wrapping text to
its left.
<body>
Figure 6.19. The image is aligned to the right and the text wraps around it.
<body>
Figure 6.21. With the image floated on the left, the text wraps around on the right
side.
Tips
• Don't get confused about right and left. When you choose align="right", it's
the image that goes to the right (while the text goes to the left). When you
choose align="left", again, the image will be on the left side with the text
flowing around the right side.
• The align attribute is deprecated. Nevertheless, since the CSS float
property (see page 194) is still not fully supported by all current browsers, I
think it's important to know how the align attribute works.
• Why use align for floating images? I don't know. Personally, I'd prefer a
float attribute, but it doesn't exist. For more details about what you can do
with align, see page 114.
Figure 6.22 The image always precedes the text that should flow around it.
</body>
Figure 6.23. The first image is floated to the right and the text flows to its left. The
next image appears after the last line of text in the preceding paragraph and
pushes the following paragraph to the right.
o The key is to place each image directly before the text it should "disrupt."
o Each image will continue to push the text to one side until it either encounters a
break (see page 112) or until there is no more text.
o The align attribute is deprecated. Nevertheless, since the CSS float property
(see page 194) is still not fully supported by all current browsers, I think it's
important to know how the align attribute works.
1. Create your image and the text or other elements (see pages 110 and 111).
2. Place the cursor where you want to stop wrapping text and elements to the side of the
image.
3. Either type <br clear="left" /> to stop flowing content until there are no more floating
objects aligned to the left margin.
Or type <br clear="right" /> to stop flowing content until there are no more floating
objects aligned to the right margin.
Or type <br clear="all" /> to stop flowing content until there are no more floating
objects on either margin.
Figure 6.24 Notice the order: first comes the house, then the header, then the
flower logo, then the text.
Figure 6.25. The clear="left" attribute makes the text stop flowing until it
reaches an empty left margin (that is, below the bottom of the left-aligned flower).
Figure 6.27. The clear="all" code stops the flow of text until all images have
been passed.
Tips
• The clear attribute is deprecated in favor of style sheets. However, the CSS
float and clear properties are still not fully supported in all current
Figure 6.28. No space is left, by default, between floating images and the elements
they float next to.
Figure 6.29 You can add horizontal space or vertical space, or both, to your
images.
Figure 6.30. One of the limitations of hspace and vspace is that they add space
to both sides of an image. Note, for example, that the words The Pioneer are no
longer aligned with the top of the image.
Tips
o You don't have to add both hspace and vspace at the same time.
o Both hspace and vspace are deprecated in favor of style sheets. For
information about using styles to control the space around your images, consult
Adding Padding around an Element on page 188 and Setting the Margins around an
Element on page 189.
o The worst part about hspace and vspace is that you can't add space to just one
side. This is a perfect example where styles are really worth the extra trouble.
Aligning Images
Perhaps the more expected use of the align attribute is for aligning images with text. You can
align an image in various ways to a single line in a paragraph. However, be careful with multiple
images on the same line—different align options have different effects depending on which
image is taller and which appears first.
Figure 6.31 Each image can be aligned in its own way with respect to the line. For
example, in the last example, the first image is aligned to the top of the text while
the second is aligned to the bottom of the entire line.
Figure 6.32. There are four elements on each line: a castle, some text, a
star, and some more text. The first word indicates the castle's alignment,
the second word describes the star's alignment.
Tips
Figure 6.33 The hr tag includes an automatic line break both before and after the
rule.
<body>
<h1>New products</h1>
<p>AstroFinder 3
</body>
Figure 6.34. Horizontal rules are helpful for dividing sections on your page.
Tips
A link has three parts: a destination, a label, and a target. The first part, the destination, is arguably
the most important. You use it to specify what will happen when the visitor clicks the link. You
can create links that show an image, play a sound or movie, download files, open a newsgroup,
send an e-mail message, run a CGI program, and more. The most common links, however,
connect to other Web pages, and sometimes to specific locations on other Web pages called
anchors. All destinations are defined by writing a URL (see page 33) and are generally only
visible to the visitor in the status area of the browser.
The second part of the link is the label, the part the visitor sees and clicks on to reach the
destination. It can be text, an image, or both. Label text is often, but not always, shown underlined.
The more appealing, enticing, and attractive the label, the more likely a visitor will click on it. In
fact, eliciting Web visitors' clicks is an art.
The last part of the link, the target, is often ignored or left up to the browser. The target
determines where the destination will be displayed. The target might be a particular named
window or frame, or a new window or frame.
Figure 7.1. Some of your pages may have links to many other pages. Other pages
may have only one link. And still others may have no links at all.
1. Type <a href="page.html"> where page.html is the URL of the destination Web page.
2. Type the label text, that is, the text that is highlighted (usually blue and underlined), and
that when clicked upon will take the user to the page referenced in step 1.
3. Type </a> to complete the definition of the link.
Tips
• As a general rule, use relative URLs for links to Web pages on your site and
absolute URLs for links to Web pages on other sites. For more details, consult
URLs on page 33.
Figure 7.2 Since there is only a file name (and no path) referenced
in the href attribute, the file pioneerval.html must be in the same
directory as this Web page that contains the link.
<body>
• There seems to be some question in the Web community about whether it's
OK to link to any page on a site besides the home page. A direct "deep" link,
as they're sometimes called, helps your visitor arrive promptly at their
destination. However, they may miss important information or advertising that
the site's creators left on the home page. One possible compromise is to give
the direct connection as well as a connection to the site's home page. You may
want to create a link to your home page from every other page on your site in
case other sites create deep links to your inner pages.
• Don't make the link's label too long. If the label is part of a sentence, keep
only the key words within the link definition, with the rest of the sentence
before and after the less than and greater than signs.
Figure 7.5 If you're creating links to someone else's Web site, you'll have to use an
absolute URL, with the http://, server, full path, and file name.
<h1>Pixel</h1>
</body>
Figure 7.6. When a visitor points at a link (displayed in blue underlined text, by
default), the destination URL is shown in the status area. If they click on a link...
Creating Anchors
Generally, a click on a link brings the user to the top of the corresponding Web page. If you want
to have the user jump to a specific section of the Web page, you have to create an anchor and then
reference that anchor in the link.
To create an anchor:
1. Place the cursor in the part of the Web page that you wish the user to jump to.
2. Type <a name="anchor name">, where anchor name is the text you will use internally
to identify that section of the Web page.
3. Add the words or images that you wish to be referenced.
4. Type </a> to complete the definition of the anchor.
Figure 7.8 Notice that most of the anchors are created with the a element and
name attribute, while the last is created by simply adding an id attribute to the
existing h2 element (see first tip). The id attribute does double duty as an anchor
in all but the oldest browsers.
<p>Frankie feels bad but it's kind of late now, and Johnny
<em>was</em> a lech. But the
police come and cart her off anyway.</p></body>
Tips
1. Type <a href="#anchor name">, where anchor name is the value of the name attribute
in the destination's a tag (step 2 on page 120) or the value of the destination's id
attribute (see first tip on page 120).
2. Type the label text, that is, the text that is highlighted (usually blue and underlined), and
that when clicked upon will take the user to the section referenced in step 1.
3. Type </a> to complete the definition of the link.
Figure 7.9. When the visitor points at a link with an anchor, the URL and the anchor
name appear in the status bar (in the lower-left corner of the window).
Tips
Within the link definition, type target= "window", where window is the name of the window
where the corresponding page should be displayed.
Figure 7.11 In this example, some links will appear in the characters window and
others will appear in the books window. (Note that this document is XHTML
transitional, not strict.)
"http://www.w3.org/TR/2000/REC-xhtml1-20000126/DTD/ xhtml1-
transitional.dtd">
[snip]<h1>Nathaniel Hawthorne</h1>
Figure 7.13. ...the corresponding page is shown in the targeted window. In this
example, it's the characters window.
• Target names are case sensitive! In addition, you should always enclose them
in quotation marks.
• Open a link in a completely new window by using target="_blank".
• If you target several links to the same window (e.g., using the same name), the
links will all open in that same window.
• If a named window is not already open, the browser opens a new window and
uses it for all future links to that window.
• Targets are most effective for opening Web pages (or even FTP links) in
particular windows or frames (see page 255). They don't make sense for e-
mail or news links which open in different kinds of windows.
• The W3C has removed the target attribute from (X)HTML strict to
promote accessibility. Instead, they suggest using JavaScript or the yet-to-be-
finalized XLink. I say, use target. (It is part of both (X)HTML transitional
and frameset.)
Figure 7.14 Use the base tag to set the default target (in this case the characters
window) in order to save typing. Notice that I no longer have to specify the target
for the links in the first paragraph. This document is equivalent to the one shown
in Figure 7.11.
"http://www.w3.org/TR/2000/REC-xhtml1-20000126/DTD/ xhtml1-
transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<base target="characters"/>
</head>
<body>
<h1>Nathaniel Hawthorne</h1>
Tips
Figure 7.15 You can create a link to all different kinds of URLs.
</p> </body>
Figure 7.16. No matter where a link goes, it looks pretty much the same in the
browser window. Notice that I've tried to create labels that flow with the body of
the text—instead of a lot of "click me's". These are all real links (OK, except the
private FTP site). You can see where they lead by opening this page in your own
browser—http://www.cookwood.com/html5ed/examples/links/links_other.html
• If you create a link to a file that a browser doesn't know how to handle (an
Excel file, for example), the browser will either try to open a helper program
to view the file or will try to download it to the visitor's hard disk. For more
information, consult Of Plugins and Players on page 294.
• It's a good idea to compress files that you want visitors to download. This
makes them faster to download and it also protects them from being corrupted
as they go from one system to another. Aladdin Systems
(www.aladdinsys.com) has some good compression tools for both Macs and
Windows machines.
• You can also create links to less common destinations (like Gopher and WAIS
servers). Just enter the URL in step 2.
Figure 7.17 Create a keyboard shortcut for a link by adding the accesskey
attribute to its tag. The explanatory text (Alt-W, etc.) is optional but helpful.
<p>Each of our cats has their own home page. Click on the
corresponding link or use the
keyboard shortcut to see each one.
</body>
Figure 7.18. There's no way to tell a link has a keyboard shortcut unless you've
labeled it as such.
Tips
In the link's tag, type tabindex="n", where n is the number that sets the tab order.
Figure 7.20 This page begins with a set of links, which, while useful, don't have
anything to do with this particular page. So that the first tab selects the first "real"
link, I've assigned it the lowest tab index.
<h1>Our Cats</h1>
</body>
Figure 7.21. When the visitor hits Tab the first time (OK, the second time, see the
second to last tip), the Woody link is selected. If they hit Tab again, Cookie will be
selected, and so on until Llumeta. At that point, a tab will bring them up to the
Contents link.
• To activate a link the visitor must tab to it and then press Enter.
• The value for tabindex can be any number between 0 and 32767. Use a
negative value to take a link out of the tab sequence altogether.
• By default, the tab order depends on the order of the elements in the
(X)HTML code. When you change the tab order, the lower-numbered
elements are activated first, followed by higher numbered ones.
• Elements with the same tab index value are accessed in the order in which
they appear in the (X)HTML document.
• You can also assign tab order to client-side image maps and form elements.
For more information, consult Creating a Client-Side Image Map on page 130
or Setting the Tab Order in a Form on page 289, respectively.
• Actually, when the visitor hits Tab for the first time, the page's URL is
selected (in the Address/Location bar, even if it's hidden). The second time
they hit Tab, the link with the lowest tab index on the page will be selected.
• In a page with frames, the visitor has to select the frame before they can tab
through the links it contains.
Figure 7.22 There is no text in the first two button links. The final </a> comes right
after the image tag.
<p>
<p><a href="mailto:[email protected]"><img
src="writeletter.gif" alt="Send mail" /> Send me comments</a>
on this page!</p>
</body>
Figure 7.23. If you do add text to the link, make sure you insert a space between
the text and the image (or use hspace or styles to space the text, see pages 188–
190).
Tips
• If you invert steps 5 and 6, only a click on the image will produce the desired
jump. A click on the text has no effect. (You can also leave the text out
altogether.)
• Most browsers surround clickable images with a border of the same color as
the links (generally blue). For no border, use a value of 0 in step 3. Note that
the border attribute is deprecated for images. You can use CSS instead (see
page 186).
There are two important steps to implementing a clickable image: First you must map out the
different regions of your image, and second you must define which destinations correspond to
which areas of the image.
4. Make sure that the units are pixels (by clicking the tiny arrow next to the cross hairs at the
bottom of the Info window).
5. Point the cursor over the upper-left corner of the region you wish to define.
6. Using the Info window, jot down the x and y coordinates for that corner (Figure 7.26).
Figure 7.26. Place the cursor in the upper-left corner of the rectangle and jot
down the x and y coordinates shown in Photoshop's Info palette. (In this
example, x=395 and y=18.) Then do the same with the lower-right corner.
For a circle, type coords="x, y, r" where x and y represent the center of the circle and r is
the radius.
For a polygon, type coords="x1, y1, x2, y2" (and so on), giving the x and y coordinates
of each point on the polygon.
7. Type href="url.html", where url.html is the address of the page that should appear when
the user clicks in this area.
Or type nohref if a click in this area should have no result. For XHTML add ="nohref"
immediately thereafter.
8. If desired, type target="name", where name is the name of the window where the page
should appear (see page 122).
Figure 7.27 You can put the map anywhere you like in your (X)HTML document.
Each clickable area is defined by its own set of coordinates, and has its own
corresponding URL. Then, don't forget to add the usemap attribute to the image
that will serve as the map.
</map>
</p>
<div id="content">
<h1>Starsearch Enterprises</h1>
</div>
</body>
Figure 7.29. And if a user clicks the link, the browser will immediately display the
corresponding page.
Tips
• Usually, maps are in the same (X)HTML document as the image that uses
them. Internet Explorer, however, can use maps that are in an external
(X)HTML file. Just add the full URL of that file in front of the label name:
usemap="map.html#label".
• With overlapping areas, most browsers use the URL of the first area defined.
Figure 7.30 The text-based alternate links below the image point to the same URLs
as the buttons in the clickable image. This gives equal access to your users who
can't see the images.
<body>
<p><a
href="http://www.cookwood.com/cgibin/imagemap/banner.map ">
</a></p>
<h1>Starsearch Enterprises</h1>
Tip
In Chapter 9, Applying Styles, you'll learn how to organize a collection of style rules in a style
sheet and then associate them with one or more (X)HTML pages.
You'll learn about the actual properties and values used in style rules principally in Chapter 10,
Formatting with Styles and in Chapter 11, Layout with Styles. Some more specialized style
properties are discussed throughout the rest of this book. Until then, we'll use the very simple and
relatively obvious
Figure 8.1. A style rule is made up of a selector (which indicates which elements
will be formatted), and a declaration (which describes the formatting that should
be executed).
1. Type selector, where selector identifies the elements you wish to format. You'll learn
how to create all sorts of selectors throughout the rest of this chapter.
2. Type { (an opening curly bracket) to begin the declaration.
Tips
• You may add extra spaces between the steps above as desired to keep the style
sheet readable (Figure 8.2).
• While each property/value pair should be separated from the next by a
semicolon, you may omit the semicolon that follows the last pair in the list.
Still, it's easier to always use it than to remember when it's possible to omit it.
• Missing (or duplicate) semicolons can make the browser completely ignore
the style rule.
Constructing Selectors
The selector determines which elements a style rule is applied to. For example, if you want to
format all p elements with the Times font, 12 pixels high, you'd need to create a selector that
identifies just the p elements while leaving the other elements in your code alone. If you want to
format the first p in each division with a special indent, you'll need to create a slightly more
complicated selector that identifies only those p elements that are the first element in their
division.
A selector can define up to five different criteria for choosing the elements that should be
formatted:
Figure 8.3. The simplest kind of selector is simply the name of the type of
element that should be formatted, in this case, h1 elements.
Figure 8.4. This selector uses context. The style will only be applied to the
em elements within h1 elements. The em elements found elsewhere are not
affected.
Figure 8.5. The first selector chooses all the em elements that belong to the
very class. The second selector chooses the one div element with an id of
gaudi.
• the pseudo-class of an element or a pseudo-element itself (Figure 8.6). (I'll explain that
awful sounding pseudoclass, I promise.)
Figure 8.6. In this example, the selector chooses a elements that belong to
the link pseudoclass (in English this means the a elements that haven't yet
been visited).
• and whether or not an element has certain attributes and values (Figure 8.7).
Figure 8.7. You can use the square brackets to add information to a selector
about the desired element's attributes and/or values.
Selectors can include any combination of these five criteria in order to pinpoint the desired
elements. Mostly, you use one or two. In addition, you can apply the same declarations to several
selectors at once if you need to apply the same style rules to different groups of elements (see
page 145).
The rest of this chapter will explain exactly how to define selectors and will give information
about which selectors are best supported by current browsers.
1. Type selector, where selector is the name of the desired type of element, without any
attributes.
2. Create the rest of the style rule as usual For more details, consult Constructing a Style
Rule on page 134.
<div id="gaudi">
Figure 8.9 This selector will choose all of the h2 elements in the document.
h2{color:red;}
• Unless you specify otherwise (using the techniques in the rest of this chapter)
all the elements of the specified type should be formatted, no matter where
they appear in your document. (Older browsers don't always follow this
imperative, especially with elements in tables.)
• Not all selectors need to specify an element's name. If you want to apply
formatting to an entire class of elements, regardless of which elements have
been identified with that class, you'd want to leave the name out of the
selector.
• The wild card, * (asterisk), matches any element name in your code.
• You can choose a group of element names for a selector by using the comma
to separate them. For more details, consult Specifying Groups of Elements on
page 145.
• Name or type selectors are well supported by current browsers.
Figure 8.11 The division with an id of gaudi encloses almost the entire page
(everything but the initial h1).
<div id="gaudi">
Figure 8.12 This selector will choose the div element with an id equal to "gaudi".
div#gaudi {color:red;}
Figure 8.13. The gaudi div, but not the h1 element, is displayed in red.
• You can use class and id selectors alone or together with other selector
criteria. For example, .news {color: red;} would affect all elements with the
news class, while h1.news {color: red;} would affect only the h1 elements
of the news class.
• For more information on assigning classes to elements in the (X)HTML code,
consult Naming Elements on page 67.
• Class and id selectors are well supported by current browsers.
An ancestor is any element that contains the desired element (the descendant), regardless of the
number of generations that separate them.
Figure 8.14 I've snipped the text to make the relationships between elements easier
to see. Each indentation represents a generation. Note that there are two second
generation p elements, directly within the gaudi div, and two third generation p
elements, within the works divs (within the gaudi div).
<div id="gaudi">
<p>Barcelona...</p>
<p>Gaudí's work...</p>
</div>
</div> </div>
1. Type ancestor, where ancestor is the name of the element that contains the element you
wish to format.
2. Type a space (Figure 8.15).
Figure 8.15 The space between div#gaudi and p means that this selector
will find any p element that is a descendant of the gaudi div, regardless of
its generation.
div#gaudi p {color:red;}
Figure 8.16. All of the p elements that are contained within the gaudi div are red,
even if they're also within other elements within that gaudi div.
A parent is the element that directly contains the desired element (the child) with no intermediary
containing elements.
1. Type parent, where parent is the name of the element that directly contains the element
you wish to format.
2. Type > (the greater than sign) (Fig. 8.17).
Figure 8.17 This selector will only choose those p elements that are
children of the gaudi div. They may not be contained within any other
element in order to qualify.
Figure 8.18. Only the first two p elements are children of the gaudi div. The two
other p elements are children of the works div. For the (X)HTML code used in this
example, see Figure 8.14 on page 138.
Tips
It's sometimes useful to be able to select only the first child of an element, as opposed to all of the
children of an element.
To select elements to format that are the first child of their parent:
Figure 8.19 This selector chooses only those p elements that are the first
child of the gaudi div.
An adjacent sibling is the element that directly precedes the desired element within the same
parent element.
1. Type sibling, where sibling is the element that directly precedes the desired element
within the same parent element.
2. Type + (a plus sign).
3. If necessary, repeat steps 1–2 for each successive sibling.
4. Type tag, where tag is the name of the element you wish to format.
5. Create the rest of the style rule as usual (see page 134).
Figure 8.20. The first p element contained in the gaudi div is colored red. Only
Netscape 6 properly deals with the first-child pseudo-element. For the (X)HTML
code, see Figure 8.14 on page 138.
Figure 8.21 This selector chooses only those p elements which directly follow a
sibling p element.
Figure 8.22. Only the p elements that directly follow a sibling p element are red.
(Currently, only Netscape 6 supports this rather useful selector. Think indented
paragraphs with the first paragraph flush.)
Tips
Or type visited to change the appearance of links that the visitor has already clicked.
Or type focus if the link is selected via the keyboard and is ready to be activated.
4. Create the rest of the style rule as usual (see page 134).
Figure 8.23 You can't specify in the code what state a link will have. It's controlled
by your visitors.
<div id="gaudi">
Figure 8.24 Styles for links should always be defined in this order, to avoid
overriding properties when a link is in more than one state (say, visited and
hovered).
a:link {color:red;}
a:visited {color:yellow;}
a:focus {color: olive;}
a:hover {color:green;}
a:active {color:blue;}
Tips
1. Type tag, where tag is the name of the element whose first line you'd like to format.
2. Type : (the colon).
3. Type first-line to select the entire first line of the element referenced in step 1.
4. Create the rest of the style rule as usual (see page 134).
1. Type tag, where tag is the name of the element whose first line you'd like to format.
2. Type : (the colon).
3. Type first-letter to select the first letter of the element referenced in step 1.
4. Create the rest of the style rule as usual (see page 134).
<div id="gaudi">
</p>
</div>
</div>
Figure 8.27 Here the selector will choose the first line of each p element.
p:first-line {color:red;}
Figure 8.28. Adjusting the width of the window changes the content of the first line
(and thus, what is formatted).
p:first-letter {color:red;}
Figure 8.30. Netscape 6 continues its good record of support by displaying just the
first letter of each p element in red.
1. If desired, type element, where element is the name of the element whose attributes are in
question.
2. Type [attribute, where attribute is the name of the attribute that an element must have to
be selected.
3. If desired, type ="value" if you want to specify the value that the attribute must have for
its element to be selected.
Or, if desired, type ~="value", to specify a value that the attribute can contain (along
with other content) for its element to be selected.
Or, if desired, type |="value" to specify that the attribute's value begin with value- (that
is, what you typed followed by a hyphen) in order for its element to be selected. (This is
most common when searching for elements in a particular language.)
Figure 8.31 In this code, only the two inner div elements have class
attributes.
<h1>Antoni Gaudí</h1>
<div id="gaudi">
Figure 8.32 The square brackets enclose the desired attribute and any
desired value.
Figure 8.33. Every div element that contains a class attribute, regardless of the
class's value, is red.
Tip
• Selecting elements based on the attributes (and values) they contain is not
supported by current versions of Internet Explorer (for either Windows or
Macintosh).
1. Type selector1, where selector1 is the name of the first element that should be affected
by the style rule.
2. Type , (a comma).
3. Type selector2, where selector2 is the next tag that should be affected by the style rule.
4. Repeat steps 2–3 for each additional element.
<div id="gaudi">
Figure 8.35 You can list any number of individual selectors, as long as you
separate each with a comma.
h1, h2 {color:red;}
Figure 8.36. Now both the h1 and the h2 elements will be colored red.
• This is nothing more than a handy shortcut. The rule h1, h2 {color: red} is
precisely the same as the two rules h1 {color: red} and h2 {color: red}.
• You can group any kind of selector, from the simplest (as shown in the
example) to the most complex. For example, you could use h1, div.works
p:first-letter to choose the level one headers and the first letter of the p
elements in divs whose class is equal to works (!).
• It is sometimes useful to create a single style rule with the common styles that
apply to several selectors and then create individual style rules with the styles
they do not share. Just be careful about the cascade (see page 42).
Combining Selectors
You can combine any of the techniques that I've explained in the last few pages in order to
pinpoint the elements that you're interested in formatting.
To combine selectors:
1. Define the context of the desired element. For more details, consult Selecting Elements by
Context on page 138.
2. Next, either spell out the element's name (see page 136) or use the wild card character
(see page 136).
Figure 8.37. Here's a doozy for you. It says "choose only the first letter of the em
elements that are found within p elements that are in the div elements whose
class is equal to works.
Tip
• You may leave out any of the steps that you don't need. This page is designed
to show you the order in which the different criteria should be listed.
We start working on the actual properties and allowed values in Chapters 10, Formatting with
Styles, and 11, Layout with Styles.
Figure 9.1. Use any text editor you like to write CSS documents. This is
WordPad.
Figure 9.2. Be sure to save the CSS file with the .css extension and as a
Text Document (or Text Only, or in ASCII, or however your text editor calls
it).
Tips
• Make sure you save the style sheet as Text Only (sometimes called Text
Document or ASCII) and give it the .css extension. When you upload it to the
server (which we'll get to in Chapter 25), be sure to choose ASCII mode—not
Binary—just the same as for (X)HTML files. This goes for Mac folks too!
• External style sheets must be either linked to (see page 149) or imported (see
page 152).
• XSL is an up and coming style sheet language for XHTML documents. Since
it is not as well supported as CSS, I do not cover it in this book. Note that
XSL style sheets are also saved as text only but with the .xsl extension. For
more information, see http://www.w3.org/Style/XSL/, the W3C's XSL site.
1. In the head section of each (X)HTML page in which you wish to use the style sheet,
type <link rel="stylesheet" type="text/css", where text/css indicates that the style sheet
is written in CSS.
2. Type href="url.css", where url.css is the name of your CSS style sheet (see step 3 on
page 148).
3. Type the final />.
Figure 9.3 Here's the external style sheet that we created on page 148 (called
base.css). Don't worry about the properties and values just yet. (It just means
create a solid red border around all the img elements.)
Figure 9.4 The link tag goes inside the head section of your (X)HTML document.
Figure 9.5. The styles (a red, solid border) are applied to each img element.
Tips
• When you make a change to an external style sheet, all the pages that
reference it are automatically updated as well.
• URLs in an external style sheet are relative to the location of the style sheet
file on the server, not to the (X)HTML page's location. Note that Netscape 4.x
gets this wrong, considering relative URLs with respect to the (X)HTML file.
One solution is to use absolute URLs (see page 33). For more details about
dealing with Netscape 4.x's bugs, consult Importing External Style Sheets on
page 152.
• The relative influence of styles applied in different ways is summarized on
page page 154.
• You can link to several style sheets at a time. The later ones take precedence
over the earlier ones.
• You can offer alternate versions of linked style sheets and let your visitors
choose among them (see page 150).
1. To designate the style sheet that should be used as a base, regardless of the visitor's
preferences, use the simple syntax described on page 149.
2. To designate the style sheet that should be offered as a first choice, but that can be
deactivated by another choice, add title="label" to the link element, where label
identifies the preferred style sheet.
Figure 9.7 This CSS file (base.css) will be our persistent style sheet, and will be
applied no matter what the visitor does.
Figure 9.8 This style sheet (preferred.css) is the one that I want to be loaded by
default, when the visitor jumps to my page.
Figure 9.9 The visitor will be able to load this alternate style sheet if they want. Its
file name is alternate.css.
Figure 9.10 In order, I've defined the base or persistent style sheet, the preferred or
automatic style sheet, and an alternate style sheet. Each style sheet needs its own
link element.
<head>
<meta http-equiv="content-type" content="text/html;
charset=utf-8" />
<title>La Casa Milà</title>
<link rel="stylesheet" type="text/css" href="base.css" />
<link rel="stylesheet" type="text/css" href="preferred.css"
title="Dashed" />
<link rel="alternate stylesheet" type="text/css"
href="alternate.css" title="Dotted" />
</head>
Figure 9.11. When the page is loaded, it has a dashed border (the preferred value
overrides the base value of solid, but the base color is maintained). If the visitor
chooses Dotted, the alternate style sheet will be used instead of the Dashed one.
Currently, only Netscape (versions 6.x+) makes it easy for visitors to choose
among alternate style sheets.
• Currently, only Netscape 6 (on both Mac and Windows) offers a way to
switch from one style sheet to another. However, there are JavaScript
solutions for other browsers. For one such solution, check out
http://www.alistapart.com/stories/alternate/.
• You can also create style sheets that are used just for printing your Web page
(or just for viewing it on screen). For more details, consult Chapter 12, Style
Sheets for Printing.
Figure 9.12 The style element and its enclosed style rules go in the head section
of your document. Don't forget the closing </style> tag, as for some reason I am
wont to do.
<head>
<meta http-equiv="content-type" content="text/html;
charset=utf-8" />
<title>La Casa Milà</title>
<style type="text/css">
img { color: red; border: solid;
}
</style>
</head>
<body>
<img src="palau250.jpg" alt="El Palau de la Música"
width="250" height="163" />
<p>I love the Palau de la Música. It is ornate and
Figure 9.13. The result is exactly the same as if you linked to the styles in an
external style sheet. However, no other Web page can take advantage of the styles
used on this page.
• Add (X)HTML comment tags (<!--) after the initial <style> tag and before
(-->) the final </style> tag to hide styles from very old browsers (see
page 71). In XHTML, you can enclose an internal style sheet in <![CDATA[
... ]]> to hide it from XML parsers (see page 321).
• You can also apply styles to individual (X)HTML tags. For more details,
consult Applying Styles Locally on page 153.
• If you want to apply your styles to more than one Web page, you should use
an external style sheet. For more information, consult Creating an External
Style Sheet on page 148 and Linking External Style Sheets on page 149.
• The relative influence of styles applied in different ways is discussed on page
154.
• If you use a different style sheet language (like XSL), you'll have to adjust the
type attribute accordingly, e.g., text/xsl.
Within the style element (see page 151), but before any individual style rules, type @import
"external.css";, where external.css is the name of your CSS style sheet (see step 3 on page 148).
Figure 9.14. Some browsers not only don't support particular CSS features but
create something hideous instead. Such is the case of Netscape 4.x and borders.
Look how it creates those charming little boxes instead of the borders we asked
for (see Figure 9.5 on page 149). Yuck!
<head>
<meta http-equiv="content-type" content="text/html;
charset=utf-8" />
<title>La Casa Milà</title>
<style>
@import "not_for_Netscape4.css";
</style>
</head>
Figure 9.16. Since Netscape 4.x doesn't understand the @import rule, it won't
import the style rules in not_for_Netscape4.css, and won't display the border
incorrectly—or at all for that matter. (It can still link to external style sheets with
rules that it does understand.) Other browsers that do support @import, including
IE5+, Netscape 6+, and Opera 3+ will continue to display the border correctly.
Tips
1. Within the (X)HTML tag that you want to format, type style=".
2. Create a style rule without curly brackets or a selector. The selector isn't necessary since
you're placing it directly inside the desired element.
3. To create additional style definitions, type a semicolon ; and repeat step 2.
4. Type the final quote mark ".
Figure 9.17 Rules applied locally affect only a single element, in this case, the
middle img tag.
Tips
• Be careful not to confuse the equals signs with the colon. Since they both
assign values it's easy to interchange them without thinking.
• Don't forget to separate multiple property definitions with a semicolon.
• Don't forget to enclose your style definitions in straight quote marks.
• Styles applied locally take precedence over all other styles (see page 154).
• If you specify the font family in a local style declaration, you'll have to
enclose multi-word font names with single quotes in order to avoid conflict
with the style element's double quotes. Actually, the reverse is also fine.
You just can't use the same type of quotes in both places.
So, locally applied styles (see page 153) have the most precedence and will override any
conflicting styles applied earlier.
In a style element, any @import rules present will lose out to any individual style rules that
also appear in the style element (since these must follow the @import rules, by definition).
The relationship between the style element and any linked external style sheets depends on
their relative positions. If the link element comes later in the (X)HTML code, it overrides the
style element. If it comes earlier, the style element (and any imported style sheets it
contains) overrides the rules in the linked style sheet.
Figure 9.19 In this example, the style element comes last. Therefore, the rules it
contains will have precedence over rules in the base.css style sheet (as long as
the conflicting rules have the same inheritance and specificity factors).
<head>
<title>La Casa Milà</title>
<link rel="stylesheet" type="text/css" href="base.css" />
<style> img {border: dashed} </style>
</head>
Figure 9.20. The style element's dashed border wins out over the linked solid
border.
Figure 9.21 Here, the linked style sheet comes last and has precedence over rules
in the style element (all else being equal).
<head>
<title>La Casa Milà</title>
<style> img {border: dashed} </style>
<link rel="stylesheet" type="text/css" href="base.css" />
</head>
Figure 9.22. The solid border from the base.css style sheet wins out over the
internal style element's dashed border.
Figure 9.23 Comments can be used to describe style rules so that they are easier
to edit and update later on. (OK, this one isn't very complicated, but yours might
be.)
Figure 9.24 If you prefer, you can insert comments after a style rule.
Tips
The push has been to separate formatting instructions from the actual content of the page in order
to make it easier to control, update, and edit the formatting. With this in mind, the W3C decided to
gradually remove almost all of the formatting tags from (X)HTML in favor of style sheets. While
these formatting tags are still legal in the transitional and frameset flavors of (X)HTML, they are
not permitted in documents written in strict (X)HTML. They remain popular, however, so I'll
explain all about them in Chapter Chapter 21, Formatting: The Old Way.
Figure 10.1 Here is an abbreviated version of the (X)HTML code that is formatted
throughout this chapter. You can find the full file in the Examples section of my
site: http://www.cookwood.com/html5ed/examples/
<div id="toc">
</div>
<div id="gaudi">
<div class="work">
It should be noted that (X)HTML still permits a very few formatting tags: tt, i, b, big, and
small. You saw those already in Chapter 4, Basic (X)HTML Formatting.
Thankfully, styles offer many more possibilities than HTML tags and extensions ever did. Now
you can change the size, weight, slant, line height, foreground and background color, spacing, and
alignment of text, decide whether it should be underlined, overlined, struck through, or blinking,
and convert it to all uppercase, all lowercase, or small-caps. You'll learn it all in this chapter!
1. After the desired selector in your style sheet, type font-family: name, where name is
your first choice of font.
2. If desired, type , name2, where name2 is your second font choice. Separate each choice
with a comma and a space.
3. Repeat step 2 as desired.
Figure 10.2 You can specify as many choices as you like. The browser will use the
first one that it finds installed on the visitor's system.
Figure 10.3. On this system, both first choices, Arial Black and Verdana, were
available.
1. Type @font-face {
2. Type font-family: "name"; where name is the full name of the font that you wish to
embed.
3. Next, indicate where the embedded font can be found by typing src: url(font.eot), where
font.eot is the location of the embedded font on the server
4. Type } to complete the @font-face rule.
5. Use the font name from step 2 in other style rules, as desired.
Figure 10.4 To embed a font for Internet Explorer users, use @font-face . The
src URL points to a special version of the font that can be downloaded to your
visitor's system.
Figure 10.5. The headers are set in an unusual font, probably not found on many
systems. Nevertheless, it will display properly because it is embedded in the style
sheet.
• You can't just choose any font file as the source for an embedded font (in step
3). You have to use a special format of the font. Internet Explorer requires
fonts to be in the .eot format. You can convert your installed fonts into .eot
with a program called WEFT. For more information, see
www.microsoft.com/typography/web/embedding/weft3/. Unfortunately, only
Explorer supports .eot fonts.
• Bitstream has a technology called TrueDoc that allows you to embed fonts in
Web pages for viewing in Netscape 4 (but not 6) and Internet Explorer 4+ for
Windows. However, in my tests, it didn't look so great, and the limited
compatibility is a huge drawback. You can check out www.truedoc.com for
more details.
Creating Italics
Italics are often used to set off quotations, emphasized text, foreign words, magazine names and
much more.
To create italics:
1. Type font-style:.
2. Type oblique for oblique text, or italic for italic text.
To remove italics:
1. Type font-style:.
2. Type normal.
Figure 10.6 In this example, I've made the .emph class display in italics.
Figure 10.7. Any elements in the emph class (like the word never in the third full
paragraph above) will be displayed in italics.
• It used to be that the italic version of a font was created by a font designer
from scratch, while the oblique version was created by the computer, on the
fly. This distinction has blurred somewhat, but generally holds.
• If you set the font style as italic and there is no italic style available, the
browser should try to display the text as oblique.
• One reason you might want to remove italics is to emphasize some text in a
paragraph that has inherited italic formatting from a parent tag. For more
details about inheritance, consult The Cascade: When Rules Collide on page
42.
• You can also use the i or em tags in the (X)HTML code to create italics. For
details, see page 74.
• The font-style property is inherited.
1. Type font-weight:.
2. Type bold to give an average bold weight to the text.
3. Or type bolder or lighter to use a value relative to the current weight.
4. Or type a multiple of 100 between 100 and 900, where 400 represents normal or book
weight and 700 represents bold.
1. Type font-weight:.
2. Type normal.
Figure 10.8 Browsers add bold formatting to headers (like h1 and h2)
automatically. I can apply a normal font weight to remove it (since it's a bit much
on this page). I've also added bold formatting to the emph class and to new and
hovered links.
Figure 10.9. The headers are not so overbearing with the extra bold formatting
removed. New links stand out (while visited ones are less obtrusive). And the
emphasized text (the word never in the third full paragraph) is not only italic (from
the preceding page) but also bold.
• Since the way weights are defined varies from font to font, the predefined
values may not be relative from font to font. They are designed to be relative
within a given font family.
• If the font family has fewer than nine weights, or if they are concentrated on
one end of the scale, it is possible that some numeric values will correspond to
the same font weight.
• What can you remove bold formatting from? Any tag where it's been applied
automatically (b and h1 come to mind) and where it's been inherited from a
parent tag (see page 42).
• The font-weight property is inherited.
1. Type font-size:.
2. Type an exact size: say, 16px or 1em.
Or use a keyword to specify the size: xx-small, x-small, small, medium, large, x-large,
or xx-large.
Figure 10.10 Here I use pixel values to have control over the initial size of the text
(which I've decreased in size throughout, compared with most browsers' defaults).
h1 {font-size: 20px}
h2 {font-size: 14px}
#toc {font-size:12px}
Figure 10.11. The sizes I've specified are displayed in the browser, regardless of
the default size that the visitor may have chosen in their browser's Preferences
box.
1. Type font-size:.
2. Type the relative value, say 1.5em or 150%. Or use a relative keyword: larger or
smaller.
Figure 10.12 Assuming a default text size of 16 pixels, this style sheet will be
equivalent to the one shown in Figure 10.10 on page 162, but will maintain the
relative sizes even when the visitor chooses some other default size.
Figure 10.13. Some visitors might set their default text size a bit larger (here it is 20
pixels), which, with sizes defined with ems and percentages, will make everything
grow proportionally.
• There should not be any spaces between the number and the unit.
• How do you know what the parent element's size is? One way is to set it
yourself as discussed on page 162. The other way is to rely on the visitor's
browser's defaults (which the visitor may adjust however they like best).
• On most current browsers, the default size for the body element (which may
be your element's parent) is 16 pixels.
• An em is equal to the size of the font. So 1 em equals 100%.
• There's also an ex unit, which refers to the x-height of the parent element, but
it is not widely supported.
• Ems and percentages are well supported in current browsers, and quite badly
supported by earlier browsers.
• You can set font size together with other font values (see page 165).
• Use the em and percentage values when you want to give the visitor more
control over how your page looks to them, while still controlling the relative
size of the elements on your page.
1. Type line-height:.
2. Type n, where n is a number that will be multiplied by the element's font-size (see page
162) to obtain the desired line height.
Figure 10.14 The line-height of the text in p elements will be 150% of 12 pixels, or
18 pixels.
Figure 10.15. Spacing out the lines makes them easier to read.
• You can specify the line height together with the font family, size, weight,
style, and variant, as described on page 165.
• If you use a number to determine the line height, this factor is inherited by all
child items. So if a parent's font-size is 16 pixels and the line-height is 1.5, the
parent's line height will be 24 (16 x 1.5). If the child's font-size is 10, its line
height will be 15 (10 x 1.5).
1. Type font:.
2. If desired, type normal, oblique, or italic to set the font style (see page 160).
3. If desired, type normal, bold, bolder, lighter, or a multiple of 100 (up to 900) to set the
font weight (see page 160).
4. If desired, type normal or small-caps to remove or set small caps (see page 173).
5. Type the desired font size (see pages 162–163).
6. If desired, type /line-height, where line-height is the amount of space there should be
between lines (see page 162).
7. Type a space followed by the desired font family or families, in order of preference,
separated by commas, as described on page 158.
Figure 10.16 This style sheet is equivalent to the one shown in Figure 10.14 on
page 164. I've simply consolidated the font properties for the h1, h2 and p rules.
Note that I don't have to specify that the font-weight be normal for h1, h2,
since normal is the default for the font property.
#toc {font-size:12px}
Figure 10.17. This page is identical to the one shown in Figure 10.15 on page 164
(though I've displayed it in Netscape 6 for Windows instead of Explorer 6 for
Windows).
• You can also set each property separately. See the page referenced with the
desired step.
• The first three properties may be specified in any order or omitted. If you omit
them, they are set to normal—which may not be what you expected.
• The size and family properties must always be explicitly specified, first the
size, then the family.
• The line height, which is optional, must come directly after the size and the
slash.
1. Type color:.
2. Type colorname, where colorname is one of the 16 predefined colors (see page 46 and
the inside back cover).
Or type rgb(r, g, b) where r, g, and b are integers from 0–255 that specify the amount of
red, green, or blue, respectively, in the desired color.
Or type rgb(r%, g%, b%) where r, g, and b give the percentage of red, green, and blue,
respectively, in the desired color.
Figure 10.18 You can use color names, hexadecimals, or even rgb values to define
your colors. I've separated the link rules in order to keep them in their proper order
so that they don't override each other (see page 141). Note that the second color
(#909) uses the abbreviation discussed in the third tip.
Figure 10.19. The headers are navy blue, the text is light purple, and the links are
pink, but turn blue when hovered on.
• If you type a value for r, g, or b higher than 255 it will be replaced with 255.
Similarly a percentage higher than 100% will be replaced with 100%.
• You can use the color property to change the color of any (X)HTML
element. For more information, consult Changing the Foreground Color on
page 184.
• You can also use #rgb to set the color where the hex values are repeated
digits. So you could write #FF0099 as #F09. (Don't do this in (X)HTML.)
• The hex number should not be enclosed in double quotes (as it is when used in
an (X)HTML tag as described on page 344.)
• The color property is inherited.
• The inside back cover of this book offers sample colors and their hex values.
1. Type background:.
2. Type transparent or color, where color is a color name or hex color (see page 166).
3. If desired, type url(image.gif), to use an image for the background.
If desired, type repeat to tile the image both horizontally and vertically, repeat-x to tile
the image only horizontally, repeat-y to tile the image only vertically, and no-repeat to
not tile the image.
If desired, type fixed or scroll to determine whether the background should scroll along
with the canvas.
If desired, type x y to set the position of the background image, where x and y can be
expressed as a percentage or an absolute distance from the top-left corner. Or use values
of top, center, or bottom for x and left, center, and right for y.
Figure 10.20 It's a good idea to set the background color for every element that
you've set a foreground color for. Setting the background color of the body
element, covers the background of all of its child elements.
body {background:#9cf}
h1, h2 {font: 20px "Arial Black", "Helvetica Bold", sans-
serif; color:navy}
h2 {font-size: 14px}
p {font: 12px/150% "Verdana", "Helvetica", sansserif;
color:#909}
.emph {font-style: italic; font-weight:bold}
a:link {font-weight:bold; color:#cc00ff}
a:visited {font-weight:normal}
a:hover {font-weight:bold; color: #0000ff}
#toc {font-size:12px; color:#cc00ff; background:#ccc}
Figure 10.21. The background of the body element is light blue. The background of
the table of contents is gray.
• You can specify both a color and an image's URL for the background. The
color will be used until the image is loaded—or if it can't be loaded for any
reason—and will be seen through any transparent portions of the image.
• Create enough contrast between the background and the foreground so that
your visitors can actually read the text.
• The background property is not inherited.
Controlling Spacing
You can add or reduce space between words (tracking) or between letters (kerning).
To specify tracking:
1. Type word-spacing:.
To specify kerning:
1. Type letter-spacing:.
2. Type length, where length is a number with units, as in 0.4em or 5px.
Figure 10.22 Here I've added .4em of extra space between letters (which at a font-
size of 20px will mean an additional 5 pixels between each letter).
• You may use negative values for word and letter spacing, although the actual
display always depends on the browser's capabilities.
• Word and letter spacing values may also be affected by your choice of
alignment.
• Use a value of normal or 0 to set the letter and word spacing to their defaults
(that is, to add no extra space).
• If you use an em value, only the resulting size (or "computed value") is
inherited. So, a parent at 16 pixels with .1em of extra word-spacing, will have
1.6 pixels of extra space between each word. And all child elements will also
have 1.6 pixels of extra space between words, regardless of their font size. Set
the extra spacing explicitly for the child elements if you need to override such
a value.
• Both the word-spacing and letter-spacing properties are
inherited.
To add indents:
1. Type text-indent:.
2. Type length, where length is a number with units, as in 1.5em or 18px.
Figure 10.24 I added a 1.5 em indent to the p elements (which, since their font-size
is 12 pixels, will be an indent of 18 pixels).
• A positive value creates a typical paragraph indent and serves as a visual clue
as to where new paragraphs begin.
• A negative value creates a hanging indent. You may need to increase the
padding (see page 188) or margins (see page 189) around a text box with a
hanging indent in order to accommodate the overhanging text.
• Em values, as usual, are calculated with respect to the element's font-size.
Percentages are calculated with respect to the width of the parent element.
• The text-indent property is inherited.
• If you use a percentage or an em value, only the resulting size (or "computed
value") is inherited. So, if the parent is 300 pixels wide, a text-indent of 10%
will be 30 pixels. And all child elements will also have their first lines
indented 30 pixels, regardless of the width of their respective parents.
1. Type white-space:.
2. Type pre to have browsers display all the spaces and returns in the original text.
Figure 10.26 The nowrap value for white-space treats spaces as non-breaking.
Figure 10.27. The table of contents line won't wrap, even when the browser window
is too narrow to display the entire line.
• The value of pre for the white-space property gets its name from the
pre tag, which is an old-fashioned HTML tag that displays text in a
monospace font while maintaining all of its spaces and returns. The pre tag,
in turn, got its name from the word "pre-formatted". You can find more
information about the pre tag on page 77.
• Note that the pre value for the white-space property has no effect on
an element's font (in contrast with the pre tag, which changes the display to a
monospace font).
• You may use the br tag to manually create line breaks in an element styled
with white-space:nowrap . For details about the br tag, consult
Creating a Line Break on page 70.
• IE versions earlier than 6 don't support the pre value for white-space .
To align text:
1. Type text-align:.
2. Type left to align the text to the left.
Or type justify to align the text on both the right and left.
Figure 10.29. The table of contents and headers are centered while the paragraph
text is justified.
• If you choose to justify the text, be aware that the word spacing and letter
spacing may be adversely affected. For more information, consult Controlling
Spacing on page 168.
• Note that the text-align property can only be applied to block-level
elements. If you want to align inline content, you must place that inline
content within a block-level element like p or div to which you've applied
the text-align property. Also see pages 190–191.
• The text-align property is inherited. Its default value is supposed to
depend on the document's language and writing system, but in most cases it's
indiscriminately set to left.
1. Type text-transform:.
2. Type capitalize to put the first character of each word in uppercase.
Or type none to leave the text as is (possibly canceling out an inherited value).
Figure 10.30 I've decided to display the level 1 header in all uppercase letters for
emphasis.
1. Type font-variant:.
2. Type small-caps.
1. Type font-variant:.
2. Type none.
Tips
• Small caps are not quite as heavy as uppercase letters that have been simply
reduced in size.
• Not all fonts have a corresponding small caps design. If the browser can't find
such a design, it has a few choices. It can fake small caps by simply reducing
the size of uppercase letters (which tends to make them look a bit squat), it can
forget about small caps altogether and display the text in all uppercase (similar
to text-transform: uppercase as described on page 172), or,
theoretically, it can choose the next font in the list to see if it has a small caps
design (though I've never seen this happen).
• IE 6 for Windows has a rather strange small-caps style (Figure 10.33). IE5.5
for Windows and earlier didn't even do that well and used uppercase letters
instead.
Decorating Text
Style sheets let you adorn your text with underlines, overlining, lines through the text (perhaps to
indicate changes), and even blinking text.
1. Type text-decoration:.
2. To underline text, type underline.
1. Type text-decoration:.
2. Type none.
Figure 10.34 You don't have to restrict underlining, or other text decorations to link
elements, as I have done here. They can be applied to any element.
Figure 10.35. I've removed the underlining from both new and visited links. (Visited
links—like the word celebrates in the third full paragraph—lose the bold formatting
so as to not call so much attention to themselves as the unvisited ones do.)
Finally, I added underlining to links that are being hovered over to help visitors
know that they are links.
• You can eliminate decorations from elements that normally have them (like a,
strike, or ins) or from elements that inherit decorations from their
parents.
• Many graphic designers hate underlining and consider it a relic from the
typewriter age. While it's perfectly fine to remove underlining from link
elements, you'll have to identify the links some other way or nobody will
know to click on them.
• The blink value has a troubled past. Originally designed by Netscape to add
pizzazz to Web pages and get an edge over its competition, it was soon
scorned by both graphic designers and Internet Explorer, which never deigned
to support it. Netscape 6 no longer supports it either (Opera 6 for Windows
does).
The principal disadvantage of CSS, especially for layout, is that older browsers either don't
understand it or understand it badly. Netscape 4.x, in particular, has notoriously bad CSS layout
support. And even current browsers get some things wrong or have different opinions about what
is right. There are strategies you can use to provide styled content to users of older browsers and
to accommodate buggy current browsers, as we saw in Chapter 9, Applying Styles.
Figure 11.1. This page was laid out with CSS. It is explained step-by-step
throughout this chapter.
1. Divide logical sections of your document into div elements. In our example, we have a
navigation division, that will hold the links to other pages on the site, a bg division that
will contain a background image for the navigational area, and a content division that will
contain the principal text and images. There is also a calendar division that will serve as a
floating sidebar of upcoming events.
2. Put your div elements in an order that would make sense even if the CSS was not used,
for example, a title at the top, followed by a table of contents, followed by the main
content. While you can change the position of each element with CSS, the content will
always be intelligible, regardless of the CSS. (The order depends on the situation,
audience, and other factors. Think about how to keep the page useful even if the CSS
layout is not used.)
3. Use header elements (h1, h2, etc.) consistently to identify and prioritize information on
your page.
4. Use comments to identify different areas of your page and what they should contain.
Figure 11.2 This is the document I use throughout this chapter. Notice that there
are three main divisions: navigation, bg, and content. You can find the complete
file on my Web site (see page 24).
<body>
<div id="navigation">
<h1>Catalonia</h1>
<a href="index.html">Home</a>
<a href="barcelona.html">Barcelona</a>
<a href="buildings.html">Famous Buildings </a>
<a href="language.html">Language</a>
<a href="festivals.html">Festivals</a>
<a href="castle.html" class="current">Castle Makers</a>
</div>
<div id="bg">
<img alt="" src="img/nearthetop_b.jpg" width="100" />
</div>
<div id="content">
<h2>Castle Makers</h2>
<p>If you've ever marveled at the amazing
Figure 11.3. Here's what our example looks like with no styles at all (in Netscape 4
for Windows). Thanks to its decent structure, it is perfectly intelligible in older
browsers like this one, if perhaps a bit spartan.
You can use CSS to determine both the appearance and the position of each element's box, and in
so doing, have considerable control over the layout of your Web page.
As we discussed earlier (see page 28), an element's box may be block-level (thereby generating a
new paragraph) or inline (not generating a new paragraph). This trait governs the initial layout of
the Web page: by default, elements are displayed in the order that the (X)HTML flows from top to
bottom, with line breaks at the beginning and end of each block-level element's box.
There are four principal ways to position an element box: you can leave the box in the flow (the
default, also called static), you can remove the box from the flow and specify its exact coordinates
with respect to either its parent element (absolute) or the browser window (fixed), or you can
move the box with respect to its default position in the flow (relative). In addition, if boxes
overlap one another, you can specify the order in which they should do so (z-index).
Once you've determined where the box should go, you can control its appearance, including its
padding, border, margins, size, alignment, color, and more. We'll discuss all of these properties in
this chapter.
Figure 11.4. Each element's box has four important properties that determine its
size: in order from the center to the outside, they are the content area, the padding,
the border, and the margin. You can control each property (and even parts of each
of these properties) individually.
Figure 11.5. Each element has its own box. In this example, the block-level
elements are the divisions (outlined), and there are various headers (medium
shading) and paragraphs (light shading) as well as the navigational links ("Home",
"Barcelona", etc.), which, while normally inline, have been set to block-level here.
Notice the inline a element ("barn raising"), and em elements ("Castellers" and
"colla") that do not generate new paragraphs.
1. Type display:.
2. Type none to hide the given element.
Or type block to display the element as block-level (thus starting a new paragraph).
Or type inline to display the element as inline (not starting a new paragraph).
Or type list-item to display the element as if you had used the li tag (see pages 203–
212).
Figure 11.6 We'll use the display property to change the navigation division's a
elements to block-level so that each is displayed on its own line. Notice that
I'm only changing the display property of the a elements found in the navigation
division. The a elements in other divisions will not be affected.
Figure 11.7. The a elements are now displayed on individual lines. Notice that the a
element on the first line of the last paragraph shown ("barn raising'), is still
displayed inline (as it should be).
Tips
1. Type position: absolute; (don't forget the semicolon; the space is optional).
2. Type top, right, bottom, or left.
3. Type :v, where v is the desired distance that you want to offset the element from its parent
element, either expressed as an absolute or relative value (10px, or 2em, for example), or
as a percentage of the parent element.
4. If desired, repeat steps 2 and 3 for additional directions separating each property/value
pair with a semicolon as usual.
Figure 11.8 While you must say—with offsets—exactly where you want an
absolutely positioned element to appear (with respect to the parent element) you
can use percentages in order to keep the design flexible for different size
monitors.
Figure 11.9. The page quickly snaps into shape. The content division (starting with
"Castle Makers'" begins at a distance of 30% of the browser window from the left
side, no matter how wide the window becomes. The navigation area, meanwhile,
starts 10 pixels from the top and only 2% from the left. The bg area is temporarily
placed below the navigation area.
• Remember that an element is positioned with respect to its parent element. For
more information on parent elements, see page 28.
• Use percentages for liquid designs that adapt to your visitors' monitor size.
• Because absolutely positioned elements are taken out of the flow of the
document, they can overlap each other. (This is not always bad.)
• If you don't specify an offset for an absolutely positioned item, the item
appears in its natural position, but does not affect the flow of subsequent
items.
• Positioning is not inherited.
Figure 11.10 The only difference between these style rules and the ones shown in
Figure 11.8 on page 179 is the fixed value for position in the bg and navigation
areas.
Figure 11.11. At first glance, this page looks identical to the one shown in Figure
11.9 on page 179.
Tips
• Remember that the offsets of a fixed element are relative to the browser
window, while the offsets of an element positioned absolutely are relative to
that element's parent.
• If fixed positioning were more universally supported, it would be an ideal
substitute for frames.
Figure 11.13 This bit of code positions the h2 and h3 elements 25 pixels to the left
of where they would have been without this rule.
Figure 11.14. The h2 and h3 headers actually stick out beyond the left edge of
their containing division. That doesn't matter—they're offset with respect to their
original position, no matter where they end up.
1. Type background-color:
2. Type transparent (to let the parent element's background show through) or color, where
color is a color name or rgb color (see page 46 and the inside back cover).
body {background-color:#fff;}
#bg {position: absolute; top: 250px; left: 2%;
background-color:black}
h1 {background-color: #339}
Figure 11.16. Perhaps the least obvious of our changes is setting the
background of the content area to white. Nevertheless, it is a crucial step
for our layout (as we'll see later on pages 190–192).
1. Type background-image:
h1 {background-color: #339}
Figure 11.18. Despite being repeated horizontally, the white background of the
content area (which has higher specificity because it's an id) covers the body's
background image. Note that the image starts in the bottom-left corner of the
entire page, not just the screen (as IE 5 for Macintosh erroneously does).
Type background-repeat: direction, where direction is either repeat (to tile the image both
horizontally and vertically), repeat-x (to tile the image only horizontally), repeat-y (to
tile the image only vertically), or no-repeat (to not tile the image at all).
1. Type background-attachment:.
2. Then type fixed to stick the background image to the browser window or scroll to let it
move when the visitor scrolls.
Tips
1. Type color:.
2. Type colorname, where colorname is one of the 16 predefined colors (see page 46 and
the inside back cover).
Or type #rrggbb, where rrggbb is the hexadecimal representation of the desired color
(see page 46 and the inside back cover).
Or type rgb(r, g, b), where r, g, and b are integers from 0–255 that specify the amount of
red, green, or blue, respectively, in the desired color.
Or type rgb(r%, g%, b%), where r, g, and b specify the percentage of red, green, and
blue, respectively, in the desired color.
Figure 11.19 We change the default color for all text to black (in the body element).
Text in the navigation box, however, will be white (to offset it from the upcoming
background that we'll adjust on pages 190–192). The current page's link in the
navigation area (so that it doesn't look like a link), should always stay the same
pale yellow (#339). The other links, however, should turn blue when hovered over
(against the white background we set on page 182).
Figure 11.20. Now that the navigation links are white, we can't see them unless we
hover over them (or place the background on pages 190–192).
Tips
• If you type a value for r, g, or b higher than 255 it will be replaced with 255.
Similarly a percentage higher than 100% will be replaced with 100%.
1. Type cursor:.
2. Type pointer for the cursor that usually appears over links ( ), default for an arrow ( ),
crosshair (+), move ( ), wait ( ), help ( ), or text ( ).
Or type x-resize to get a double-sided arrow, where x is the cardinal direction one of the
arrows should point—that is, n (north), nw (northwest), e (east), etc. For example, the
e-resize cursor might look like this: .
Figure 11.21 I add the cursor property to the selector that chooses only those
links in the current class that belong to the element whose id is navigation, and
who are being hovered over. Quite a selector, no?
Figure 11.22. Now, when someone points to the link to the current page, it doesn't
look like a link (although the status bar still shows the destination and the link still
works).
• IE 5.x for Windows recognizes the hand value, but not the standard
pointer value (for ). To please do-it-their-own-way Microsoft as well as
standards-supporting browsers like Netscape and IE 6, use both:
cursor:pointer;cursor:hand; . The order is significant since IE
5.x for Windows will choke on pointer if it's last. (Thanks to Eric Meyer
for this tip.)
• The illustrations shown above are from IE 6 on Windows 98. The cursors vary
slightly from browser to browser and system to system. For example, the
wait cursor on a Mac is the familiar watch: ..
• I find the names confusing. The default isn't the default, but instead is an
arrow, which I would call a pointer, but pointer means a hand, while
hand is a non-standard value created by Microsoft. Ugh.
Type border-width: n, where n is the desired width, including abbreviated units (for example
4px).
Type border-color: color, where color is a color name or rgb color (see page 46 and the inside
back cover).
Figure 11.23 You can set all three border properties to just the left side of the
element with the border-left shortcut.
Figure 11.24. Here is a simple 1 pixel-wide solid border. Notice that the text needs
some space between it and the border. We'll get to that shortly (see page 188).
1. Type border.
2. If desired, type -top, -right, -bottom, or -left to limit the affect to a single side.
3. If desired, type -property, where property is one of style, width, or color, to
limit the affect to a single property.
4. Type :.
5. Type the appropriate values (as described in the first three techniques above). If you've
skipped step 3, you can specify any or all of the three types of border properties (e.g.,
border:1px solid or border-right:2px dashed green ). If you
have specified a property type in step 3, use an accepted value for just that property (e.g.,
border-right-style:dotted ).
Figure 11.25 I set the color for all four sides of the border with the single border-
color property. Then I set individual widths for each side with border-width ,
starting with the top (2px) and moving clockwise around the box. Finally, I create
classes for each style, and apply the style to one or more sides of the division.
Figure 11.26. Notice how the different shortcuts work. For example, border-
style:dotted (the first example) creates a dotted border on all four sides, while
border-style:dashed none creates a dashed border on the top and bottom
and no border on the right and left sides. Browsers (IE 6 on left, Netscape 6 on
right) interpret border styles slightly differently.
Type padding:. x, where x is the amount of desired space to be added, expressed in units (10px)
or as a percentage of the width of the parent element (20%).
Figure 11.27 It's not a bad idea to set the body padding to 0 since browsers have
varying defaults for padding for different elements. Note that the last two padding
styles (for #navigation a and h1 respectively) are equivalent.
Figure 11.28. The content looks much better when there is some empty space
between it and the border. Notice that the background of the header ("Catalonia")
is enlarged when padding is added.
Tips
• If you use one value in step, the specified padding is applied to all four sides
equally. If you use two values, the first value applies to the top and bottom
and the second value applies to the right and left. If you use three values, the
first applies to the top, the second to the right and left, and the third to the
bottom. If you use four values, they are applied to the top, right, bottom, and
left, in clockwise order.
• You can also add one of the following suffixes to the padding property to
apply padding to a single side: -top, -bottom, -left, or -right.
There should be no space between the word padding and the suffix.
• Padding is not inherited.
Type margin: x, where x is the amount of desired space to be added, expressed as a length, a
percentage of the width of the parent element, or auto.
Figure 11.29 We could also have written the margin for the h3 element as
margin-top:15px .
#navigation [snip]
Figure 11.30. The text in the content area looks much better with less space
between headers and paragraphs. Remember that the margin is the space between
element boxes, which themselves are determined by such varied factors as
content, line-height, the height property, and more. Finally, note that the margin
between the h3 and p elements is 15 pixels (the greater of the touching margins)
and not 20 pixels (the sum of the touching margins).
• You can use from one to four values for margin. See the first tip in the
padding section for details (see page 188).
• You can also add one of the following suffixes to the margin property to
apply a margin to a single side: -top, -bottom, -left, or -right.
There shouldn't be any space after margin (e.g., margin-top: 10px ).
• The margin property's auto value depends on the value of the width
property (see page 190). Given a width of auto, if you set one margin to
auto, it is set to the highest value possible. If you set both the right and left
margins to auto, they are set to the highest possible equal values. You can
use this fact to center an element.
• If one element is placed above another, only the greater of the two touching
margins is used. The other one is said to collapse. Left and right margins don't
collapse.
• Margins are not inherited.
Figure 11.31 Remember that in the (X)HTML code, we set the width of the image in
the bg area to 100 pixels.
<div id="bg">
<img alt="" src="img/nearthetop_b.jpg" width="100" />
</div>
Figure 11.32 I set the desired size of the image for the bg division with the width
property (and override the (X)HTML attribute in Figure 11.31 above). Note I've also
adjusted the top and left offsets of the bg div, and used a negative left margin to
center on the parts of the photo I'm interested in.
Figure 11.33. Note that the content area overlaps the bg division, starting at 30%
from the left side. Since the content area is white, the part of the image that
extends behind it is hidden. Notice, as well, that our navigation area is also hidden.
We'll fix that shortly.
• If you don't explicitly set the width, auto is used (see page 191).
• Remember that the percentage value is relative to the width of the parent element—
not the original width of the element itself.
• The padding, borders, and margin are not included in the value of width (except
in IE 5.x for Windows, which quite erroneously considers the width to be the sum
of the content area, borders, and padding—see next page).
• Widths and heights are not inherited.
• There are also min-width , min-height , max-width and max-height
properties but they are currently supported rather erratically.
For most block-level elements, the auto value for width is set to the width of the containing
block minus the padding, borders, and margins. The containing block is the width that the element
gets from its parent and is sometimes confusingly called the inherited width, even though it has
nothing to do with normal CSS inheritance.
Elements with images and objects (replaced elements) have an auto width equal to their
intrinsic value, that is, the actual dimensions of the external file. Floated elements have an auto
width of 0. Non-floated inline elements ignore the width property altogether.
Figure 11.34 I've set the width of the parent div to 300 pixels. This will be our
containing block. Then, both paragraphs have 10 pixel margins, 5 pixel padding
and 5 pixel borders on all sides. The first paragraph has the width set
automatically, the second is set at 200 px.
Figure 11.35. If the width (pink shaded background) is auto, as in the top
paragraph, its value is derived from the width of the containing block (the gray
shaded background) minus the margins, padding, and border. If the width is set
manually (as in the bottom paragraph), the right margin is usually adjusted to pick
up the slack.
Now those are the rules, for what they're worth. Unfortunately, IE 5 (and IE 6 in Quirks mode)
thinks that when you set the width, you're setting the sum of the content area, the borders, and the
padding, instead of just the content area as it should be. And IE 6 lets the margins and replaced
elements of a child element affect the width of the containing block while asserting in their
documentation that this should not be allowed. As if this weren't all complex enough!
Positioning Elements in 3D
Once you start using relative and absolute positioning, it's quite possible to find that your elements
have overlapped. You can choose which element should be on top.
1. Type z-index:.
2. Type n, where n is a number that indicates the element's level in the stack of objects.
Figure 11.36 The content and navigation z-index values could conceivably be
interchanged as long as both remain higher than the bg's z-index of 1. (The
content area must have a higher z-index than bg because its white background
conceals the extended parts of the image in the bg area.)
Figure 11.37. Now the navigation area is on top of the bg division, and you can
finally see why we made the links white!
• The higher the value of the z-index property, the higher up the element will be
in the stack. You can think of the z-index property as a measure of elevation,
with the visitors in an airplane looking down, seeing the elements on the tops of
mountains first.
• You can use both positive and negative values for z-index.
• If you have nested items within an element that has a certain z-index , all those
nested items are first ordered according to their own individual z-indexes, and then,
as a group, ordered in the larger context. So imagine A has a z-index of 10, and B
has a z-index of 20, and C has a z-index of 30. B contains two children: bb, with a
z-index of 35 and bbb with a z-index of 5. The four items will be displayed in the
following order, from top to bottom: C (with the highest z-index of its level), B
(with the 2nd highest z-index of its level), followed by its children, bb and bbb, in
that order), and then finally A, whose z-index was lower than B's.
• The z-index property is not inherited.
1. Type overflow:.
2. Type visible to expand the element box so that its contents fit. This is the default option.
Or type hidden to hide any contents that don't fit in the element box.
Or type scroll to always add scroll bars to the element so that the visitor can access the
overflow if they so desire.
Figure 11.38 First, I format the calendar div so that it looks pretty.
#calendar h3 {margin:0;color:white}
Figure 11.39. The calendar looks nice down here at the end of our Web page, but
it's too long, in my opinion.
Figure 11.40 I set the width and height of the dates paragraph within the
calendar explicitly so I know just how big the resulting paragraph will be. Then I
add the overflow property to deal with the parts that don't fit in the resulting size
paragraph.
Figure 11.41. Now the dates paragraph measures precisely 150 pixels wide by 2.5
ems tall, and scroll bars appear so that visitors can reach the rest of the data.
Tips
• Note that IE 6 doesn't think you know what you're doing when you make a child
bigger than its parent and will incorrectly extend the parent to be as big as the child.
The only exception is if you set the overflow property to any value except
visible (the default), in which case the parent will shrink down to its normal
size and let the overflow property do its job.
• The default value for overflow is visible. The overflow property is not
inherited.
1. Type float:.
2. Type left if you want the element on the left and the rest of the content to flow to its right.
Or type right if you want the element on the right and the rest of the content to flow to its
left.
3. Use the width property (see page 190) to explicitly set the width of the element.
Figure 11.43. The text that follows the calendar division flows around the calendar
to the left.
Tips
• Remember, the direction you choose applies to the element you're floating, not to
the elements that flow around it. When you float: left, the rest of the page flows to
the right, and vice-versa.
• The trick to making content flow between elements is to always put the image
directly before the content that should flow next to it.
• For an old-fashioned, deprecated, and yet universally supported way of flowing text
between images, consult Making Images Float on page 110.
• If you float more than one element in the same direction, the first element floated is
placed farthest in that direction, the second element is the second farthest, and so on
(Figures 11.44 and 11.45).
Figure 11.44 Now imagine we had another image before the calendar div
and float it to the right as well.
Figure 11.45. Since the little image comes first in the (X)HTML, it gets
floated farthest to the right.
1. Type clear:.
2. Type left to keep elements from floating to the left of the element you're styling.
Or type right to keep elements from floating to the right of the element you're styling.
Or type both to keep elements from floating to either side of the element you're styling.
Or type none to let elements flow to either side of the element you're styling.
Figure 11.46 You add the clear property to the element whose sides should be
free of floating elements. In this case, we want the right side of the calendar
division to be clear so we apply the clear:right property to it.
#calendar h3 {margin:0;color:white}
.dates {width:150px;height:2.5em;overflow:auto}
.icon {margin-top:7px;float:right}
Figure 11.47. The calendar division won't display until the right side is completely
clear (that is, until below the little floating image).
Tips
• The clear property stops the affected element (the one to which the clear
property is applied) from displaying until the designated side is free of floating
elements.
• You add the clear property to the element whose sides you want to be clear of
floating objects. So, if you want an element not to be displayed until the right side is
clear of floating elements, add clear:right to it (and not to the floating
elements).
• The use of the clear property is similar to the br tag with the (alas, deprecated)
clear attribute (see page 112).
1. Type vertical-align:
2. Type baseline to align the element's baseline with the parent's baseline.
Or type middle to align the middle of the element with the middle of the parent.
Or type text-top to align the top of the element with the top of the parent.
Or type text-bottom to align the bottom of the element with the bottom of the parent.
Or type top to align the top of the element with the top of the tallest element on the line.
Or type bottom to align the bottom of the element to the bottom of the lowest element on
the line.
Or type a percentage of the line height of the element, which may be positive or negative.
Figure 11.48 We apply the top vertical alignment only to the images that have the
line class.
Figure 11.49. The top edges of the three line class images are aligned.
Add media="output" to the opening link or style tags, where output is one or more of the
following: all, print, or screen (Figure 12.1). Separate multiple values with commas.
Figure 12.1 In this (X)HTML document I've linked to the screen.css style sheet for
the styles that will be used when displaying the page onscreen and the print.css
style sheet for the styles that should be used when printing.
<head>
</head>
<body>
<div id="story">
Or, in an @import rule, add output, where output has the same values as above, after the URL
but before the semicolon (Figure 12.2). Again, separate multiple values with commas.
Figure 12.2 In this example, which should have the same effect in current
browsers, I've linked to the screen.css style sheet but imported the print.css style
sheet.
<head>
<style type="text/css">
</style>
</head>
<body>
<div id="story">
Tips
• There are actually ten possible output types: all, aural, braille,
embossed, handheld, print, projection , screen, tty, and tv.
Current desktop computer browsers will (properly) ignore style sheets designated as
anything but screen, print, or all.
• The default value for the media attribute is all.
• There is also an @media rule, though it is less well supported than the options
described above.
• For more information on linking and importing style sheets, Chapter 9, Applying
Styles
• Use appropriate fonts and font sizes, using points rather than pixels, since the former
work best for printing. For more details, consult A Property's Value on page 44 as well as
pages 158–165.
• Hide sections like sidebars or ads that need not be printed (using the display property
described on page 178).
• Remove background colors and images and use colors that print reasonably in black and
white (see pages 182–184).
• Adjust margins, if necessary (see page 189).
• Control page breaks and other print-specific properties (see pages 200–202).
• Explain to your visitors how and why the print version will be different from what they
see on screen.
Figure 12.4. When the document is printed, you can get rid of the sidebar and the
ads, and use a serif font for added legibility. Note that the exact same (X)HTML
code was used in both cases. The browser automatically selects the appropriate
style sheet.
• The page break and other print-specific CSS properties suffer from average to
middling support. However, there are still many things that are worth changing that
all browsers will understand.
• As you test style sheets for printed output, be sure to take advantage of your
browser or system's Print Preview option, if it has one. Print Preview (typically in
the File menu and sometimes in the Print dialog box itself) lets you see how the
page will be printed without having to waste paper.
In the style rule, type page-break-before: when or page-break-after:when, where when is one
of always (so that page breaks always occur before/after the selected elements), avoid (so
that page breaks only occur before/after the selected elements when absolutely necessary), or
auto (to let the browser decide).
Figure 12.5 I don't want paragraphs to be divided between pages so I use page-
break-inside:avoid . So that each second level header starts on its own page,
I add page-break-before:always to the h2 tags.
#toc {display:none}
h2 {page-break-before:always}
Figure 12.6. By putting a page break before each h2 element (like The Storm), I
ensure that they start on a a fresh page. Notice also the extra space at the bottom
of the page since the paragraph that followed was too big to fit in its entirety (and
"page breaks inside" were to be avoided). Instead the entire next paragraph will be
printed in full on the following page.
If you've named your page definition (as described in step 2 on page 201), you can then
request that certain elements be printed only on that particular kind of page.
Figure 12.7 Here I've defined three types of pages. For left pages, there will be a
slightly larger right margin (to allow for binding). For the same reason, right pages
will have a slightly larger left margin. The named toc page will have a hefty top
margin of 3 inches to set its contents in the middle of the page.
@page :left {size: 8in 10in; margin: 1in 1in .5in .5in;
marks: crop cross}
@page :right {size: 8in 10in; margin: .1in .5in .5in 1in;
marks: crop cross}
@page toc {size: 8in 10in; margin:3in .5in .5in 1in; marks:
none}
In the style rule for the desired element, type page: name;, where name is the identifying label
you used in step 2 on page 201.
One or two lines of a longer paragraph look unsightly when displayed alone at the beginning or
end of a page. These stranded lines of text are called widows and orphans, respectively. CSS lets
you specify the minimum number of lines of an element that can appear alone.
• If desired, in the style rule, type orphans: n;, where n is the minimum number of lines
that should appear at the bottom of a page.
Figure 12.8 The toc division will be printed on toc type pages (that is, the one I
defined in Figure 12.7 on page 201).
Figure 12.9 The p elements will be allowed to split across pages, but at least four
lines should appear at the bottom of the page and four lines must appear at the top
of the page.
Tips
All lists are formed by a principal code to specify what sort of list you want to create (ol for
ordered list, dl for definition list, etc.) and a secondary code to specify what sort of items you
want to create (li for list item, dt for definition term, etc.).
Although the W3C does not recommend the use of list elements for simply indenting paragraphs,
they are rather handy in this regard. You can find more information about that in Chapter 22,
Layout: The Old Way, under Creating Indents (with Lists) on page 362.
Unordered lists are probably the most widely used lists on the Web. Use them to list any series of
items that have no particular order, such as hot Web sites or names.
Figure 13.1 There is no official way to format a list's title. You can use a regular
header (see page 65).
<ol>
<li>Make sure you have unplugged the lamp from the wall
socket.</li>
</ol>
</body>
Tips
• Unless you specify otherwise (see page 206), items in ordered lists will be
numbered with Arabic numerals (1, 2, 3, etc.) (Figure 13.2).
Figure 13.2. This list uses the default Arabic numerals to create a numbered
list.
Figure 13.3 The list items of unordered lists are identical to those for
ordered lists. Only the ul tag is different.
<ul>
</ul>
• Items in unordered lists have solid round bullets by default (Figure 13.4). You can
choose different bullets (see page 206) or even create your own (see page 208).
In the style sheet rule, type list-style-type: marker, where marker is one of the following values:
disc (•), circle ( ), square( ), decimal (1,2,3, ...), upper-alpha (A, B, C, ...),
lower-alpha (a, b, c, ...), upper-roman (I, II, III, IV, ...), or lower-roman (i, ii, iii,
iv, ...).
Figure 13.5 Here is our simple ordered list, to which we will apply capital Roman
numerals (upper-roman ).
<body>
<ol>
<li>Introduction</li>
<li>Development</li>
<li>Climax</li>
<li>Denouement</li>
<li>Epilogue</li>
</body>
Figure 13.6 You can apply the list-style-type property to any list item. If you
had two lists on this page, one of which was unordered, you could apply capital
Roman letters to just the ordered one by changing the selector in this example to
ol li.
li {list-style-type:upper-roman}
Figure 13.7. Now the ordered list has capital Roman numerals. Note that most
browsers align numeric markers to the right.
Tips
• You can also use the deprecated type attribute in the ul or ol tag and in
individual li items to specify a marker style for the entire list or for individual list
items, respectively. In unordered lists, the acceptable values are disc (for a solid
round bullet), circle (for an empty round bullet), or square. In ordered lists,
the acceptable values are A, a, I, i, and 1, which indicate the kind of numeration
to be used.
• A type attribute in an li tag overrides one in a ol or ul tag.
• By default, unordered lists use discs for the first level, circles for the first nested
level, and squares for the third and subsequent level lists.
• The disc, circle, and square bullets vary slightly in size and appearance from one
browser to another.
Within the ol tag, type start="n", where n represents the initial value for the list.
In the desired li item, type value="n", where n represents the value for this list item. The
value is always specified numerically and is converted automatically by the browser to the type
of marker specified with CSS or with the type attribute (see page 206).
Figure 13.8 In this example, I've omitted some steps but want to maintain the
original numbering. So I start the whole list at 2 (with start="2" ) and then set
the value of the third item to 5 (with value="5" ).
<body>
<ol start="2">
</ol>
</body>
Figure 13.9. Notice that not only are the first and third items numbered as we've
specified, but the third item ("Plug in the lamp") is also affected.
1. In the style sheet rule for the desired list or list item, type list-style-image:.
2. Then type url(image.gif), where image.gif is the image you'd like to use for the list item's
markers.
Figure 13.10 I want to add a special marker for the new features in my list.
<ul>
</ul>
Figure 13.11 It's a good idea to use absolute URLs for specifying the location of
the marker image to ensure that all browsers will understand.
Figure 13.12. It can be tricky mixing custom markers with default ones. You have
to make sure the custom markers aren't too big.
Tips
• By default, you've got about a 15 by 15 pixel square space for the marker.
• If your image is larger than the line height of the list items, some browsers overlap
them. You can adjust a list-item's margins (see page 189) if necessary.
• There should be no space between url and the opening parentheses. Quotes around
the URL are optional.
• Note that relative URLs are relative to the location of the style sheet, not the Web
page, except in Netscape 4 which (incorrectly) does the opposite. You can avoid
problems by using absolute URLs.
• Most browsers align custom markers to the right. IE for Windows (all versions) is
the notable and annoying exception.
• The list-style-image property overrides list-style-type . But, if
for some reason the image can not be loaded, the marker specified with list-
style-type is used.
• The custom markers are inherited.
1. In the style sheet rule for the desired list or list item, type list-style-position:.
2. Then type inside to display the markers flush with the list item text, or outside to display
the markers to the left of the list item text.
Figure 13.13 I've added a bit more text to the first "new" feature so that the effect of
hanging markers inside is more obvious.
Figure 13.14 I've added the inside list-style position to the style sheet rule shown
in Figure 13.11 on page 208.
li.new {
list-style-
image:url(http://www.cookwood.com/html5ed/examples/lists/rig
htarrow.gif);
list-style-position:inside
}
Figure 13.15. The markers for the "new" features begin at the left margin of the list
item, instead of outside it to the left.
1. Type list-style:
2. If desired, specify the kind of markers that should appear next to the list items, if any (as
described on page 206).
Figure 13.16 This style rule is equivalent to setting the list-style-image to the
rightarrow.gif file, the list-style-position to inside and the list-
style-type to square. It's just shorter.
Figure 13.17. As long as the image is available, the result is the same as in Figure
13.15 on page 209.
Figure 13.19 Each entry word is labeled with the dt tag, while the definition itself is
labeled with a dd tag.
<dl>
<dt>Present</dt>
<dt>Future</dt>
<dt>Aorist</dt>
</dl>
Figure 13.20 You may want to add formatting to your definition term to help it
stand out.
dt {font-weight:bold}
.example {font-style:italic}
Figure 13.21. By default, the defined word (the dt) is aligned to the left and the
definition (dd) is indented.
• Browsers generally indent definitions on a new line below the definition term.
• You can create more than one dl line or more than one dt line to accommodate
multiple words or multiple definitions.
Figure 13.22 There are four nested lists here, one in the Introduction list item, one
in the Development item, one in the Climax item and one, highlighted and in bold
face, inside the Boy gives Girl ultimatum item (which is inside the Climax item).
Figure 13.23 You can format each level of nested list separately. If you use
percentages for list text, be sure to add the li li {font-size:100%} so that
it doesn't disappear on you (see last tip).
ol li {list-style-type:upper-roman;font-size:75%}
ol ol li {list-style-type:upper-alpha}
ol ol ol li {list-style-type:decimal}
li li {font-size:100%}
Tips
• Your selectors should reflect the types of nested lists in your document, that is, you
might need something like ul ul ol li.
• Ordered lists always use Arabic numerals (1, 2, 3) by default, regardless of their
nesting position. Use list-style-type to specify other numbering schemes
(see page 206). According to The Chicago Manual of Style, the correct nesting
order for lists is I, A, 1, a, 1.
• By default, the first level of an unordered list will have solid round bullets, the next
will have empty round bullets and the third and subsequent levels will have square
bullets. Again, use list-style-type to specify the type of bullets you want
(see page 206).
• Since list items (li elements) can be nested within other list items, you have to be a
bit careful with font sizes specified in relative values. If you use something like li
{font-size: 75%} , the font size of the outermost list item will be 75% of its
parent element, which, if the parent is a default 16 pixels high, will be 12 pixels, and
not a problem. However, the font size of the first nested list item will be 75% of its
parent (the first list item, which is 12 pixels), and thus will be only 9 pixels high.
Each level gets quickly worse. One solution is to add li li {font-
size:100%}. Now nested list items will always be the same size as top level
ones. (Thanks to Eric Meyer.)
Now that CSS is here and well supported, you can create beautiful layouts without tables (see
page 175). However, those layouts will degrade, and sometimes not very gracefully, in older
browsers. If you're not ready to give up on the 10% of the population who aren't using browsers
with decent CSS support—some 50 million people (according to Nua, http://www.nua.com/)—use
tables for layout.
And there's a middle road. As this chapter will illustrate, you can use tables for the basic structure
of your page, but use CSS for all the text formatting, and much of the layout formatting (beyond
the table itself). It will be that much easier to make the leap to full CSS when you (and your
visitors) are ready.
One of the nice things about tables is that you can use them to create liquid design—design that
expands and contracts proportionately to your visitor's browser window. The key is to use
percentages instead of pixel-based widths and learn to let go of the need to control every last
space.
Finally, if you want to use tables for tabular data, you still can. And CSS will help you make those
tables shine.
Figure 14.1. Tables let you create fancy professional-looking layouts that will wow
your visitors and be compatible with most older browsers.
Figure 14.2. Here's a map of the main example used in this chapter. I use one table
for the top set of ads and logo and one table for the lower navigational bar and
content area section. Note that there is a third table floating in the content text.
Tip
• One good way to get ideas for table structure is to look at how others do it (see page
57). However, there are some very complicated setups out there. One way to get a
handle on what's going on in someone else's page is to download the source code
and then change the background color of each nested table (see page 228) so you
can better see which parts of the layout belong to which table.
Figure 14.3 This very simple table has two rows, each of which has only one cell.
Notice that I've added extra size formatting to the caption to keep it unobtrusive.
</table>
Figure 14.4 The style sheet contains only pure text formatting; nothing that would
affect the table per se.
.caption {font-size:.8em;font-style:italic;
fontfamily:"verdana", sans-serif}
Figure 14.5. Notice that by default, the table extends almost as far as the edge of
the browser window.
Tips
• The </table> tag is not optional. Netscape won't display tables without it.
• There is also a th tag for creating header cells. But, all it does is center the contents
of a cell and format it in boldface. If you're mostly using tables to help lay out your
Adding a Border
A border helps distinguish your table from the rest of the page. However, if you're laying out your
page with tables, you may not want to call so much attention to the border.
1. In your style sheet, type table or td, or whichever selector denotes the part of the table
that you want to apply a border to.
2. Type {border: value}, where border is the border property that you wish to apply and
value is the type of border you want. For more details on the border property, consult
Setting the Border on page 186.
Figure 14.7 In this example, we set a 10 pixel wide border for the outside of the
table. As long as you set the border attribute, regardless of its value, the cell
borders are always 1 pixel wide.
</table>
Figure 14.8. Although borders are not usually shown in tables used for layout, they
are often temporarily useful for showing exactly what's happening with a table.
Here we can see we've got two rows and each row contains a single cell. The
(X)HTML border attribute turns on borders around tables and cells
indiscriminately.
.caption {font-size:.8em;font-style:italic;font-
family:"verdana", sans-serif}
Figure 14.10. This page is the result of the (X)HTML shown in Figure 14.7 and the
CSS in Figure 14.9. Because we've applied the CSS border property only to the
table element, the borders around cells are not affected at all. CSS borders are
much more flexible and powerful than (X)HTML.
Figure 14.12 Here is the CSS that we'll use with respect to borders in the rest of
our example. So there!
table, td {border:0}
Tips
• The CSS border property is discussed in detail (and there are a lot of details) on
page 186. This page focuses on how the border property interacts with the (non-
deprecated) (X)HTML border attribute.
• The border attribute applies to both the table and the cells it contains. The CSS
border property, in contrast, is not inherited. So, if you omit the border
attribute but apply a CSS border to the table, the cells will have no borders.
Conversely, if you use the border attribute but use table {border:
none}, the cells will have borders, but the table won't.
• If you use the border attribute with no value (border alone, or
border="border" to be XHTML compliant) but no CSS border, you get a
1 pixel outset border.
• The border attribute only controls whether or not the border exists in the absence
of the CSS border-style property. If border-style is set to none,
either explicitly ({border-style:none} ) or implicitly ({border:red
2px} since none is the default style), there will be no border, regardless of the
border attribute (except in IE for Windows which incorrectly lets the border
attribute, if it's present, override the border-style default of none).
• If you don't set a border width with CSS, IE 5 for Mac uses the attribute value (if it's
absent, that means no border), IE 6 for Windows uses the attribute value (but if it's
absent, it uses a CSS default of medium which it interprets as 4 pixels), and Opera
5 and Netscape 6 use the CSS default of medium (which they interpret as 3 pixels)
regardless of the attribute value. Conclusion: you should set the width explicitly if
you want it to be consistent across browsers. (See next tip.)
• If you set the border-width in CSS, it overrides the (X)HTML border
attribute.
• A border's default color is the color of the element itself (as specified with the CSS
color property). Only IE for Mac and Netscape get that right. (Other browsers
change only the color of the table's or cell's content.)
• Tables naturally expand to the edge of the elements they contain or to the edge of
the browser window, whichever comes first. That's sometimes hard to see unless
you view the border.
• It's not a bad idea to create a border while you're constructing your table and then
banish it once you have everything in place.
Instead of relying on the browser's sometimes unusual algorithms for determining table width, you
can specify the width of the table or of individual cells manually, either in pixels or as a
percentage of window size. For example, when designing liquid layouts with tables, it's very
common to specify a table width of 100% in order to force the table to expand to the size of the
It's important to note that no browser will let you make a table or cell narrower than its images. It
will simply stretch the cell or table as necessary to make the image fit, adjusting the rest of your
table as best it can.
In the td or table tag, type width="n", where n is the desired width of the cell or of the entire
table, in pixels.
Or type width="n%", where n is the portion of the browser window that the table should occupy.
In the style sheet, type width: value where value is the desired width (for more details, see page
190).
Figure 14.13 This table has a 200 pixel wide image with no borders. We set the
width of the table to 200 pixels to keep the text from stretching out.
</table>
Figure 14.14 You can use either the CSS, the (X)HTML or both. The CSS overrides
the (X)HTML (though in this example, they're the same, so it doesn't matter.)
table, td {border:0}
.caption {font-size:.8em;font-
style:italic;fontfamily:"verdana", sans-serif}
Figure 14.15. The CSS width property is well supported. You can feel comfortable
using it instead of the width attribute in the (X)HTML.
Figure 14.17. The image (200px) overrides the width property and/or attribute (set
to 100px). You can't make a table or cell too small for its images!
Figure 14.19. Of course, you can make a table bigger than its contents. In that
case, the text stretches out to fill the space.
Tips
• The CSS width property is described in detail on page 190. This page focuses on
how the width property interacts with the (X)HTML width attribute (which has
not been deprecated).
• A table sized with percentages will adjust as the browser window is resized. Tables
sized with pixels will not.
• You can't make the table too small for its contents; the browser will just ignore you.
• You can keep a cell open to a certain width by putting a transparent pixel spacer
inside it of the proper width (see page 364).
• If you make the table too wide, visitors with smaller monitors (or visitors who don't
use the entire screen for their browser) may have to scroll to see some parts of your
table. If you must use a non-flexible layout, I don't recommend making tables any
wider than 600 pixels.
• In IE 5.x for Windows the value of width is the sum of the content, cellspacing,
cellpadding and borders. In browsers that properly follow the specifications (like IE
6, Netscape 6, and Opera)—in standards mode, see page 39—the value of the
width property (or attribute) does not include padding or borders.
• The widest cell in the column determines the width of the entire column.
• You don't necessarily have to specify a width for every column.
• There is also a height attribute but it is non-standard, and not well supported.
1. Make sure you've specified the width of the table (see page 220).
2. Add margin-right: auto and margin-left: auto to the table's style rule.
Figure 14.20 The simplest way to center a table is to add the deprecated (but still
well supported) center value to the align attribute.
Figure 14.21 Setting the right and left margins to auto makes them equal—which
is the essence of centering.
table, td {border:0}
.rightsidebar {width:200px; marginright:auto;margin-
left:auto}
.caption {font-size:.8em;font-style:italic;
fontfamily:"verdana", sans-serif}
Figure 14.22. Because support is so sketchy for centering with CSS, I recommend
continuing to use the (X)HTML method (in addition to or instead of CSS, as you
prefer).
• Centering the table with CSS by setting the right and left margins to auto does not
work in IE 5.5 or earlier or in Netscape 4.x or earlier.
• You can also use the CSS text-align property in a surrounding div to center
tables, but it seems a bit of a hack to me (see page 171).
• The center value for the align attribute has been deprecated by the W3C,
though it continues to enjoy broad support.
• You could also center the table by enclosing the entire table in opening and closing
center tags (see page 356), although they've also been deprecated.
• You could conceivably center one table within another. For more information,
consult Combining Tables on page 224.
• You can also wrap text to the right or left of a table (see page 223).
• You can't align a table to the top or middle line of text as you can with images.
1. In the table tag, either type align="left" to align the table to the left of the screen
while the text flows to the right, or type align="right" to align the table to the right of
the browser window while the text flows on the left side of the table.
2. After the closing </table> tag, type the text that should flow around the table.
Figure 14.23 When you align a table to the right, the text flows to the left. Notice
also that in the markup, the table comes before the text that flows around it.
</table>
Figure 14.24 You must specify a width when using the float property.
table, td {border:0}
.caption {font-size:.8em;font-
style:italic;fontfamily:"verdana", sans-serif}
Figure 14.25. Since the table is floated to the right, the text wraps around the left
side.
Tips
Combining Tables
For more complex layouts, you may wish to combine tables. You can place combinations of tables
and text in another table, you can nest tables within a specific cell of a larger table, or you can use
multiple tables.
1. Create the inner table and any text or other elements that should accompany it.
2. Create the outer table. Determine which cell of the outer table will hold the inner table
and type placeholder (or some other easily identifiable text) there as a placeholder.
3. Test both tables separately to make sure they look the way you want them to.
4. Replace the word placeholder with the inner table content by copying and pasting.
The more complicated your tables become, the longer it will take for a browser to
calculate their proper widths and display them. One way to simplify your code is to divide
your layout into multiple tables that sit one on top of the next.
Figure 14.26 Here I've created an outer table with a single row. The left column is
devoted to a navigation bar and the right column contains the main content (what
we've worked on so far in this chapter—which contains its own wrapped table).
</table>
<p>It's hard to tell what goes through a [snip]
</td>
</tr></table>
Figure 14.27. Here I've combined the main content with the left navigation by
placing them in a table in separate cells. I've added the border so you can see
what's happening.
Figure 14.28 Instead of creating a new table to combine the logo bar and the table
from Figure 14.27, the code will be cleaner, leaner, and faster if I create two
<table width="100%">
<table width="100%">
<tr>
<p><a href="lions.html">Lions</a>
Figure 14.29. The new table sits right above the old one. Since the first columns
have the same width, they look like part of the same layout.
• Creating the tables separately before combining them helps pinpoint where
problems may lie, should they occur.
• Only nest tables where it's absolutely necessary. They can slow down a browser
considerably or even make it crash. Whenever possible, use multiple tables as an
alternative.
• Use in any cell that should remain empty. Otherwise, it may not display at
all.
• Use background colors (see pages 182 and 228) to decipher which cells belong to
which tables.
• Make sure to close each table with its own closing </table> tag, even if you
usually scoff at XHTML. Otherwise, your table will be invisible in Netscape.
• You can keep a column open to a certain minimum by inserting a transparent spacer
gif (see page 364) and setting its width to the desired width of the column.
Otherwise, browsers will try to make the column as narrow as the text will allow.
1. Place the cursor in the initial tag for the cell, row, or section, after the name of the tag but
before the final >.
2. If desired, type align="direction", where direction is left, center, or right.
3. Type valign="direction", where direction is either top, middle, bottom, or
baseline.
1. In the desired rule, add text-align: direction, where direction is left, right,
center, or justify.
2. And/or add vertical-align: position, where position is baseline, top, bottom, or
middle.
Figure 14.30 We need the middle image in the logo bar to stay centered and the
right image to stay to the right regardless of the browser window size. The left
navigation items should be at the top of their cell, not the middle, which is the
default.
<table width="100%">
<tr>
<p><a href="lions.html">Lions</a>
Figure 14.31 For the caption to the elephant photograph and the left navigation
bar, I just added the alignment properties to the existing classes. For the other
cells, I had to create special classes to do the alignment (which frankly, seems like
a bit of trouble).
.rightsidebar {width:200px;float:right}
.caption {font-size:.8em;font-style:italic;
fontfamily:"verdana", sans-serif; text-align:
center}
[snip]
.center {text-align:center}
.right {text-align:right}
.top {vertical-align:top}
Figure 14.32. Immediately obvious are the left navigation bar, which now sits at the
top of its cell, and the caption to the photograph, which is nicely centered. Less
obvious are the second and third cells of the logo bar table. But look what
happens when the window is wider (Figure 14.33 below).
• Although the align attribute has been deprecated for other properties, it is still
valid for all table elements (except table itself). The valign attribute is also
still valid. Both are well supported.
• The CSS text-align and vertical-align properties are very well
supported. (Only version 3 browsers have trouble with them.)
• You can align all of the cells in a row by applying the text-align or
vertical-align property to (or inserting the align or valign attribute
in) the tr tag.
• The default value for align is left. The default for valign is middle.
• Note that you can justify a cell's contents with CSS but not with (X)HTML. In fact,
the justify value exists for the align attribute, but I've never seen it working.
• Theoretically, you can align the contents with respect to any character you choose,
for example to align monetary amounts with respect to the decimal point. In the
(X)HTML, you'd use align="char" char="x" , where x is the character
around which to align. In CSS, use text-align:x , again, where x is the
desired alignment character. Unfortunately, no browser I've seen supports either
method.
• The baseline value aligns the contents of each cell with the baseline of the first
line of text that it contains. Baseline is the same as top when there are several lines
of text and no images. Baseline is the same as bottom when the cells contain both
images and text.
• The vertical-align property accepts a few other values (like text-top ,
text-bottom , sub, and sup) but these don't make sense with table cells, and
so baseline is used in their place.
• For more information about text-align , see page 171. For more information
about vertical-align , see page 196.
Within the desired tag, type bgcolor= "color", where color is either a name or a hex color (see
page 46 and inside back cover).
Within the desired tag, add background = "image.url", where image.url is the image that should
be displayed in the background.
In the desired rule, type background: value, where value is described in detail on pages pages
182–183.
Figure 14.34 You can add the bgcolor attribute to any part of the table. Here I've
matched the background of the logo bar to the color of the middle image so that it
<table width="100%">
<tr>
Figure 14.35. You can see the yellow background around and between the images
in the logo bar. Notice that the green background also surrounds the nested table
and serves as the background for its text (that I've made white).
[snip]
.logobar {background:#ffff66}
Tips
CSS on the other hand lets you use the now familiar padding property (see page 188) to
control space on every side of a cell, as well as between paragraphs and other elements. It is a
welcome substitute for cellpadding .
Unfortunately, the border-spacing property, which could stand in very well for cell-
spacing, is supported by Netscape 6 but not yet by Explorer (as of version 6).
In the table tag, type cellpadding="n", where n is the number of pixels that should appear
between the contents of a cell and its border.
In the table tag, type cellspacing="n", where n is the number of pixels that should appear
between one cell border and the next.
In the desired rule, type padding: value, where value is a length in pixels or a percentage of the
parent element.
In the desired rule, type border-spacing: value, where value is a length in pixels or a percentage
of the parent element.
Figure 14.38. Cell spacing adds space between cells. Cell padding adds space
between a cell's contents and its border.
Figure 14.40. Finally, the extra spaces between the cells disappear (especially in
the logo bar) and the table appears seamless.
Figure 14.41 One way to make spaces on a single side of a cell or group of cells is
to add a cell filled with non-breaking spaces (in our example, between the left
navigation bar and the main content).
<td> </td>
<td class="top">
Figure 14.42. The extra space cell appears as requested. Of course, it will be
invisible, not pink.
table, td {border-spacing:0}
.caption {font-size:.8em;font-style:italic;font-family:
Figure 14.45 The lower table now has two rows. The first row contains the left
navigation cell, the non-breaking spaces cell, and the main content cell. The
second row (highlighted) contains a single cell with copyright information that
spans the three columns.
<td> </td>
<td class="top">
[snip]
</table>
Tips
• The default value for cell padding is 1. The default value for cell spacing is 2.
• When using tables for layout, it's perhaps easiest to set both the cellpadding
and cellspacing to zero and then selectively add padding with CSS.
• Sometimes it's just simpler to create an empty cell and fill it with non-breaking
spaces. It's a bit of a hack, but it's fast and easy (Figures 14.41 and 14.42).
1. When you get to the point in which you need to define the cell that spans more than one
column, type <td.
2. Type colspan="n">, where n equals the number of columns the cell should span.
3. Type the cell's contents.
4. Type </td>.
5. Complete the rest of the table. If you create a cell that spans 2 columns, you will need to
define one less cell in that row. If you create a cell that spans 3 columns, you will define
two less cells for the row. And so on.
Figure 14.47 I can make the left navigational bar span both rows, but then I have to
adjust the second row's cell so that it only spans the second and third columns.
<td> </td>
<td class="top">
[snip]
Figure 14.48. Now the left navigational bar spans both rows and the copyright row
only needs to span two columns.
Tips
• Each row in a table must have the same number of cells defined. Cells that span
across columns count for as many cells as the value of their colspan attribute.
• Writing the HTML code for a table from scratch is, uh, challenging—especially
when you start spanning columns and rows. It helps to sketch it out on paper first, as
described on page 216, to get a handle on which information goes in which row and
column. Or you can cheat and use a Web page authoring program like FrontPage or
Dreamweaver to get started. You can always open the file and edit the (X)HTML by
hand later.
• There is no CSS alternative for colspan .
1. When you get to the point in which you need to define the cell that spans more than one
row, type <td.
2. Type rowspan="n">, where n equals the number of rows the cell should span.
3. Type the cell's contents.
4. Type </td>.
5. Complete the rest of the table. If you define a cell with a rowspan of 2, you will not need
to define the corresponding cell in the next row. If you define a cell with a rowspan of 3,
you will not need to define the corresponding cells in the next two rows.
Figure 14.49 I can make the left navigational bar span both rows, but then I have to
adjust the second row's cell so that it only spans the second and third columns.
<tr>
<td> </td>
<td>Babies</td>
Figure 14.50. The colgroup element makes it easy to select all of the cells in a
column and apply formatting to them in one fell swoop. Here we've applied a font,
size, and right alignment to the column with the city names, and center alignment
to the other three columns.
Tips
• Each column in a table must have the same number of cells defined. Cells that span
across rows count for as many cells as the value of their rowspan attribute.
• There is no CSS alternative for rowspan .
Figure 14.52 Now I divide the second column group into two separate non-
structural column groups (with col) so that I can format an entire column at a time
without affecting how rules are drawn (see page 238).
<col span="2"/>
</colgroup>
<tr>
<td> </td>
<td>Babies</td>
Figure 14.53. I've used the non-structural column group to format the last column
in bold type—without affecting where interior rules will be drawn.
Figure 14.55 Once the first row is in a thead section, I can define a class of styles
for it which will be applied to each cell in the thead.
<thead class="titles">
<tr>
<td> </td>
<td>Babies</td>
<tbody><tr>
<td>Northampton</td>
Figure 14.56. All of the elements in the thead section are formatted and they will
be considered together when the interior borders are drawn.
Figure 14.57. Notice that Netscape does understand the horizontal section
elements.
Tips
1. Before the first tr tag of the section you want to create, type <thead, <tbody, or <tfoot.
2. If desired, define the desired attributes for the section.
3. Type >.
4. If necessary, create the section's contents.
5. Close the section with </thead>, </tbody>, or </tfoot>.
Figure 14.58 Add the frame attribute within the table tag.
<thead class="titles">
<tr>
<td> </td>
<td>Babies</td>
Figure 14.60. Netscape gets frame right, showing only the external vertical sides.
(Unfortunately it drops the ball with rules on the next page.)
Tips
• You can apply CSS (or indeed, formatting attributes) to horizontal sections of cells.
• Horizontal section tags go after column group tags (see page 235).
• At least one tbody tag is required in every table. Both XHTML, as long as it is
served as an HTML file (e.g., with the .html extension) and HTML will create an
implicit tbody if you omit it. XHTML served as XML (with the .xml extension)
requires an explicit tbody element.
• You can only have one thead and one tfoot.
• In HTML, the closing tags are optional. A section is automatically closed when you
begin the next.
In the table tag, type frame="location", where location is one of the values listed below:
In the table tag, type rules="area", where area is one of the following values:
Figure 14.61 The rules attribute determines which internal borders should
be displayed. In this example, we will show the column borders.
• groups, for rules between column groups (created with the colgroup element
described on pages 235–236) and horizontal sections as defined by the tags described on
pages 235–237 (Figure 14.64)
Figure 14.65. Imagine a table with several words in a column that you don't want
split among several lines, no matter how narrow the browser window gets.
Figure 14.66 Just add the nowrap attribute to the td cell that should not be
broken into multiple lines.
<tr>
<td>7</td>
<td>12</td></tr></tbody>
Figure 14.67. No matter how narrow the window and the table get, the cell's
contents will stay on a single line, even if it means some of the table extends
beyond the window.
Tips
• It is the groups value for rules that illustrates the difference between
colgroup and col. The colgroup element defines what is considered a
column group and therefore where lines are drawn with the groups value. The
col element does not.
• It is also the groups value which makes this whole technique worthwhile.
Otherwise, you can use the CSS border property to get much more control over
borders (see page 218).
Tips
• Keep tables as small as possible. Where you can, divide large tables into smaller ones.
• Specify the width of the table in pixels (see page 220).
• Use absolute values (in pixels) or percentages for determining cell width.
• Only specify proportional widths for cells, columns, and horizontal sections when you've
already set a fixed width in pixels for the entire table.
• Divide your table into column groups.
• Add table-layout:fixed to your table element's style rule (Figure 14.68).
This instructs browsers (IE 5+ and Netscape 6+) to look only at the first row of a table in
order to determine the widths of the columns, instead of worrying about every cell in
every row. While the contents of some cells may not fit (their display is governed by the
overflow property—see page 193), the table renders much more quickly.
The beauty of having several Web pages open on a screen at a time lies in the ability to interrelate
the information in each of the pages. For example, you can have a stationary banner frame across
the top of the window that includes your company name and logo. Meanwhile, a dynamic frame
on the left side of the window can include a table of contents. Finally, the main area of the
window will be devoted to the contents frame, whose data changes each time your visitor clicks
on a new topic in the table of contents.
Frames do have some disadvantages. They can be hard to navigate, their scroll bars can hog
precious screen real estate, they can be hard to get indexed in a search engine like Google, and
once indexed they may appear independently without benefit of their surrounding and supporting
frames.
In fact, the W3C discourages the use of frames. Instead, they recommend embedding content on a
page through fixed positioning (see page 180) and the use of the object element (see page
261).
First, you'll create a simple frameset with three horizontal rows all in the same column.
Figure 15.1 The frameset page has no actual content. Instead, it defines the
frames and links them with the pages that hold the initial content. Notice
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Frames in Rows</title>
</head>
<frameset rows="65,*,60">
</frameset>
</html>
11. Create the pages that will be displayed initially in the frames, that is, those referenced by
the src tag in step 8 (Figures 15.2 and 15.3). This is the "landscape" behind the
window.
Figure 15.2. Once you've created a frameset, the next step is to create the
pages that will appear within the frames.
• You should use the Frameset DOCTYPE for frameset pages (see page 38).
• Create a title in each framed page so that they are indexed by search engines (see
page 426).
• Don't forget the closing </frameset> tag! If you do, older versions of Netscape
will display a blank page.
• The name you define in step 7 is used when you're targeting links to this frame. For
more details, see page 255.
• Use an asterisk (*) to allocate to a frame whatever leftover space there is available
in the window.
• You can use more than one asterisk at a time. The remaining space will be divided
equally among the frames marked with an asterisk. To divide the remaining space
unequally, add a number to the asterisk, e.g., 2*. In this case, two thirds of the
remaining space will go to the frame marked 2* and the last third will go to the
frame marked with just a plain asterisk.
• The body element is only used when offering alternatives to frames (see page
260).
1. Type <frameset after the </head > tag in the frameset page.
2. Type cols="a, b"> where a and b (and any others) represent the width of the
corresponding column, as a percentage, number of pixels, or variable (*).
3. Type <frame to define the leftmost frame/column.
4. Type name="name" where name is a word that identifies this particular frame's use, like
banner, index, or contents.
5. Type src="content.html"> where content.html is the URL of the page that you want to
be displayed in this frame when the visitor initially navigates to this frameset.
6. Repeat steps 3–5 for each frame/column.
7. Type </frameset>.
8. Create the Web pages that will be shown initially in the frameset page.
Figure 15.5 To create a page with frames in columns, use the cols attribute
instead of rows.
</head>
<frameset cols="110,*,100">
<frame name="banner" src="bannercols.html" />
<frame name="photos" src="openingpagecols.html" />
<frame name="buttons" src="buttonscols.html" />
</frameset>
Figure 15.6. Don't forget to create the content for the frames. Although these pages
are very similar to the ones shown in Figure 15.2, they have been adjusted slightly
to fit better vertically.
• Consult the tips on page 243 for details on allocating the space among frames with
variables (*).
• A frame's name is used when you're targeting links to appear in the frame. For
details, consult Targeting Links to Particular Frames on page 255.
Figure 15.9. Notice that the first and last rows and first and last columns of frames
are set to take up all the leftover space not used up by the photos. Then I set each
of those frames to display an empty page with a white background. No matter what
size window my visitors look at this page with, the outside frames will expand or
contract, but the photo filled frames will stay the same size.
• Defining rows and columns in this way limits you to the same number of frames in
each row or column. To create one row with two frames and another row with three,
you'll have to combine multiple framesets (see page 246).
• There is more about this technique (and this particular example) on my Web site
(see page 24).
Combining Framesets
One of the most common layouts for frames you'll see on the Web is to have one row at the top
that spans the width of the browser, and then a second row divided into two frames. This effect is
achieved by inserting an additional frameset in the second row.
1. Make a sketch of your frameset and determine how many rows and columns you will
need.
2. Type <frameset to begin.
3. Type rows="a, b"> where a and b (and any others) represent the height of the
corresponding rows.
4. In the example in Figure 15.10, the first and third rows are a single frame while the
second row is divided into columns. For a row with just a single frame, type <frame
name="name" src="contents.html"> in the usual way.
Figure 15.10 First create the outer frameset. Then define each row from top
to bottom. For rows that will be divided, use an inner frameset. The
highlighted area here (the inner frameset) corresponds to the second row of
the outer frameset.
5. For the second row, which is divided into columns in this example, type <frameset
cols="a, b"> where a and b (and any others) represent the width of each column in the
row.
6. Type <frame name="name" src="contents.html"> where name is the reference for the
frame and contents.html is the page that will be initially shown in that frame.
7. Repeat step 6 for each column in the frameset. (In this example, there are two columns, so
you'll have to define two frames in the inner frameset.)
8. When you've finished defining the frames/columns in the divided row, type </frameset>.
9. Continue defining each row individually. For a row with just one frame (i.e., just one
column), just use a frame tag. For rows divided into multiple columns, repeat steps 5–8.
10. Type </frameset> to complete the outer frameset.
Figure 15.11. In this example, the first and third rows are simple frames while the
second row is a frameset divided into two columns.
• It's absolutely crucial that you add a closing </frameset> tag for each opening
<frameset> that you create. Otherwise, Netscape 4.x won't show anything at
all.
• Although I've defined the rows first and then the columns in this example, you can
define the columns first if it works better for your particular layout. In fact, when
adjusting the borders, both methods have distinct advantages (see the tips on page
253).
• It is important to stress that not every row need be divided into columns. For rows
with a single frame (i.e., that span the entire window from left to right), just use a
frame tag. For rows divided into columns, use an inner frameset.
• If you want to create the same number of frames in each row and each column, you
don't need to combine multiple framesets. For details, consult Creating Frames in
Rows and Columns on page 245.
• You can use combined framesets to change more than one frame at a time. For more
information, consult Changing Multiple Frames with One Link on page 326.
1. In the container page, type <iframe src="frame.url", where frame.url is the page that
should be initially displayed in the inline frame.
2. Type name="name", where name is a word that identifies this inline frame.
3. Type width="x" height="y" where x and y represent the width and height, respectively,
of the inline frame in pixels.
4. Type >.
5. Type the text that should appear if the browser can't display the frame.
6. Type </iframe>.
Figure 15.12 Specify at least the width of your inline frames in pixels (and not a
percentage) so that Netscape 6 can view them properly.
Figure 15.13. Floating frames function similarly to images, flowing with the rest of
the content on the page.
• You can also use the frameborder (see page 253), hspace/vspace (see
page 113), scrolling (see page 250), and
marginwidth/marginheight (see page 249) attributes with inline frames.
• You can use the deprecated align attribute (see page 110) or the CSS float
property (see page 194) to wrap text around an inline frame.
• Netscape 4.x and Opera 5 for Mac do not support inline frames.
• For Explorer, you can also specify the height and width as a percentage of the
parent window. Netscape 6.x can deal with a percentage width but flips out if you
specify a percentage height.
Figure 15.14. Note how the contents of each frame with default margins begins
slightly down and to the right.
1. In the desired frame tag, before the final >, type marginwidth="w" where w is the
desired amount of space, in pixels, between the left and right edges of the frame and the
frame's contents (Figure 15.15).
</head>
<frameset rows="65,*,60">
<frame name="banner" src="banner.html"
marginheight="0" marginwidth="0" />
<frameset cols="120,*">
<frame name="index" src="indexcity.html"
marginheight="0" marginwidth="0" />
<frame name="photos" src="openingpage.html"
marginheight="0" marginwidth="0" />
</frameset>
2. Type marginheight="h" where h is the desired amount of space, in pixels, between the
top and bottom edges of the frame and the frame's contents.
Tips
• The margin is transparent and thus always appears to be the same color as the
background of the page displayed in the frame.
• While these two attributes have yet to be deprecated, you can also adjust the margin
of the individual pages with the CSS margin property. For more information,
consult Setting the Margins around an Element on page 189.
In the frame tag of the particular frame for which you wish to show the scroll bar, type
scrolling="yes".
In the frame tag of the particular frame for which you wish to hide the scroll bar, type
scrolling="no".
Figure 15.18 So that the top and bottom frames never display scroll bars, add
scrolling="no" to their frame tags.
<frameset rows="65,*,60">
<frameset cols="120,*">
Figure 15.19. Eliminating scroll bars from certain areas makes the information
much clearer and more attractive. But be careful not to take away scroll bars from
areas that need them. Remember, you can't control the size of your visitor's
window.
• The default is for scroll bars to appear only when necessary, that is, when there is
more information than can fit in the frame. To use the default, you can type
scrolling="auto" or, more simply, don't type any scrolling tag at all.
• There are few things more frustrating than jumping to a frameset page with tiny
little frames that make it impossible to view the entire contents. Even worse is when
you cannot scroll around (or make the frame bigger—see page 254) to make the
hidden information visible. To avoid frustrating your visitors, make sure you test
your frameset page in a small window and ensure that all the frames without scroll
bars are big enough to display their entire contents.
Inside the topmost frameset tag before the final >, type bordercolor="color", where color is
either one of the sixteen predefined colors or a hexadecimal color (see page 46 or the inside back
cover).
</frameset>
Inside the topmost frameset tag, before the final >, type border="n" where n is the desired
width of the space between frames, in pixels.
Figure 15.22 Add the border tag to any frameset or frame tag to adjust its
borders' thickness. Here, I've added the tag to the topmost frameset tag so that
all the frames are affected.
<frameset cols="120,*">
Figure 15.23. Thick, colored borders can help divide information into
understandable chunks.
• The border attribute is not standard (X)HTML, but is still well supported.
• IE supports the CSS border attribute when applied to frames and framesets,
though that use is non-standard.
• You can use border="0" to make the borders completely disappear.
• The default border width is 5 pixels.
• You cannot set the thickness for individual frames.
• Explorer won't show borders between 1 and 5 pixels wide. Instead, it shows nothing
but an empty space.
• The best way to make frames jut right up next to each other is to use
border="0" and frameborder="0" (see page 253).
• You can change the color of the borders (or the space between the frames) as well.
For details, consult Adjusting the Color of the Borders on page 251.
• Explorer also supports a framespacing attribute which works essentially like
the border attribute (which Explorer didn't support until version 4).
Type frameborder="0" inside the topmost frameset tag, before the final >.
Figure 15.26. To have each frame right up next to the adjacent one, use
frameborder="0" border="0" .
Figure 15.29 Add the noresize tag to any frames that you don't want the visitor
to be able to resize. Here, I've modified the top and bottom frames and left the
middle frames flexible.
<frameset cols="120,*">
</frameset>
Figure 15.30. Once you've restricted the resizability, the pointer will not turn into a
double-pointed arrow and the visitor can't change the size of the frame. (In
Netscape, the hash mark disappears also.)
• Netscape 4 displays resizable frames with a small hash mark in the middle of the
border. The mark disappears if you've used the noresize attribute. Explorer
displays both resizable and non-resizable borders exactly the same way.
• If you use very small pixel values for your frames and the visitor views the frameset
page in a very large window, the width of the frames will probably not be quite as
you wished. The entire frameset is always stretched to fill the window.
• If you set the border width to 0 with the border attribute (see page 252), visitors
won't be able to resize the frames at all. (The same goes for the frameborder
and framespacing attributes.)
• In Explorer, if you set the border width to less than 5, the borders disappear, and
again visitors won't be able to resize frames at all, regardless of whether you use the
noresize attribute or not.
1. Make sure the target frame has a name (Figure 15.31). For more information, consult
Creating a Simple Frameset on page 242.
<frameset cols="120,*">
2. On the page where the link should appear, type <a href="page.html" where page.html is
the file that should be displayed in the target frame.
3. Type target="name" where name is the reference given to the target frame within the
frame tag (Figure 15.32).
Figure 15.32 In the link, specify the name of the frame in which the
destination page should open.
4. Add any other attributes as desired to the link and then type the final >. For more
information on creating links, see Chapter 7, Links.
Figure 15.33. The original contents of the photos frame is the Welcome page. But
when the visitor clicks the Les Rambles link (which is targeted to appear in the
photos frame)...
Figure 15.35 This link goes to another Web site and should not appear within my
site's frames. Therefore, I use target="_top" to break out of frames and show
this link in the entire browser window.
Tips
• By default, that is, without a specified target, a link will open in the same frame that
contains the link.
• For some special targets, page 257.
• The frame must have a name to be targeted. For more information on naming
frames, consult Creating a Simple Frameset on page 242.
• Frame names are case sensitive and must begin with an alphanumeric character
(except the ones described on page 257).
1. Type <a href="contents.html" where contents.html is the page that you wish to be
displayed in the special spot.
2. Type target="_blank" to have the link open in a new, blank window. This is the ideal
targeting for links to other sites which may not fit very well inside your frames.
Or type target="_self" to open the link in the same frame that contains the link. The
information in the frame (including the link itself) will be replaced by the contents.html
file specified in step 1.
Or type target="_top" to use the entire current window for the link, thus breaking out of
frames altogether (Figures 15.36 and 15.37).
Figure 15.36. When the visitor clicks a link that is targeted to the _top...
Figure 15.37. ...the link is displayed in the full window without any frames.
Figure 15.38 In the original document, I've set the target for each link individually.
<title>Buttons</title>
</head>
<body bgcolor="white">
<title>Buttons</title>
<base target="photos"/>
</head>
<body bgcolor="white">
Tip
• So, use target="_top" if you want to break out of a frameset or stop using
framesets, so to speak. The link will appear in the entire window.
1. In the head section of the page that contains the links, type <base.
2. Type target="name", where name is the word that identifies the frame or window in
which you want the links to appear, by default.
3. Type /> to complete the base tag.
Tips
• You can override the target specified in the base tag by choosing a target in the
link itself (see page 255).
• As ever, you can leave off the / at the end of the tag in HTML, but not in
XHTML.
To nest framesets:
Figure 15.40 The frameset shown has two columns. The first column will
contain a simple index page, while the second column will contain a
distinct frameset (in fact, the one used in most of the previous examples in
this chapter).
<frameset cols="*,4*">
</frameset>
Figure 15.41. In this example, the Barcelona tour is easily integrated into a larger
group of topics just by nesting its frameset into the larger one.
• You can target a link to open in the parent frame of a frameset (in this example, the
right column is the parent frame of the Barcelona tour frameset). For more
information, consult Targeting Links to Special Spots on page 257.
• You can't nest a frameset inside a frame that is in that same frameset. Hey, and why
would you want to?
• You can use nested framesets to change two frames with one link (a common
desire). Simply create a special frameset that references the two pages that you want
to appear. Then point the link at the new frameset. It's a bit slower than the
JavaScript way, but it's pure (X)HTML and relatively straight-forward. (For the
JavaScript way, consult Changing Multiple Frames with One Link on page 326.)
1. Type <noframes><body> just before the last </frameset> tag (Figure 15.42).
Figure 15.42 The noframes tags come after all of the framesets and frames
have been defined.
<frameset rows="65,*,60">
<frameset cols="120,*">
</frameset>
<frame name="buttons" src="buttons.html"
noresize="noresize" scrolling="no" />
<noframes><body>
</frameset>
2. Create the content that you want to appear if the frames do not.
3. When you've finished the alternate content, type </body></noframes>.
Tips
• You can put a link in your noframes section that leads to a non-framed version
of your site (see page 263).
• The noframes section will not be shown in browsers that can interpret frames,
like Netscape (Figure 15.43) and Internet Explorer. Instead, the frames will be
shown.
Figure 15.43. Most browsers always display frames, and thus never show
the noframes information.
• Although this example is rather simple, don't be misled: you can put practically
anything in the noframes section.
• Some visitors set up Explorer so that it doesn't view frames (by unchecking Frames
in the Web Content preferences). They will see the noframes content.
• If you don't create a noframes section, beware! When visitors jump to your page
with a browser that can't read frames, instead of an error message, they simply won't
see anything! If nothing else, the noframes section can be used to explain what
the problem is (Figure 15.44).
Figure 15.45 You can embed one (X)HTML page in another by using the object
element.
<body bgcolor="#FFFFFF">
<h1>Barcelona Tours</h1>
<hr />
</body>
Figure 15.46. The referenced page is embedded on our Web page as if it were a
frame. The links work and everything!
<body bgcolor="#FFFFFF">
<h1>Barcelona Tours</h1>
<hr />
<object type="text/html"
data="openingpage.html" width="500"
height="450" >
</object>
</object>
Figure 15.48. The browser doesn't yet support the unsup/fake MIME type (since I
made it up), and so shows the second object instead.
<frameset rows="65,*,60">
<frameset cols="120,*">
</frameset>
<noframes><body>
</body></noframes></frameset>
</html>
Figure 15.50 The longdesc attribute links to an external document (like the
(X)HTML document shown above) that provides additional information about how
the site works.
Tips
1. Add the title attribute to each frame tag in order to identify the contents of the
frame.
2. Provide more complete information about what each frame is for. For example, within the
frame tag, type longdesc="info.url", where info.url is the location on the server of a
Web page that explains the purpose of this frame.
3. Add links to the noframes tag that describe the individual frames' functions.
4. Provide a full non-frame version of the frame-based site.
Tip
• Many of the world's governments, including the U.S. (with Section 508 of the
Rehabilitation Act), have drawn up legislation requiring federal or state Web sites to
be accessible to people with disabilities, including the blind. You can find more
details at the W3C Web Accessibility Initiative site: http://www.w3.org/WAI/. The
United States government has an interesting site outlining the requirements of
Section 508 at http://www.section508.gov/
There are two basic parts of a form: the structure or shell, that consists of fields, labels, and
buttons that the visitor sees on a page and hopefully fills out, and the processing script that takes
that information and converts it into a format that you can read or tally.
Constructing a form's shell is straightforward and similar to creating any other part of the Web
page. You can create text boxes, special password boxes, radio buttons, checkboxes, drop-down
menus, larger text areas, and even clickable images. You will give each element a name that will
serve as a label to identify the data once it is processed. Constructing forms is discussed on pages
269–286.
Processing the data from a form is a bit more complicated. The principal tool, the CGI script, is
typically written in Perl or some other programming language. Although Perl programming is
beyond the scope of this book, and even explaining how to use existing Perl scripts stretches the
limits a bit, I've added a few simple ready-made Perl CGI scripts for your use to get you started
(see page 267).
If this all seems a bit daunting, or if your ISP doesn't allow you to run CGI scripts, you might
decide to have visitors submit form data via e-mail (see page 270) or use a public form host (see
page 271).
CGI, which stands for Common Gateway Interface, is simply a standardized way for sending
information between the server and the script. So, to resume, a CGI script is a program (usually
written in a programming language called Perl) that communicates with the server in a standard
(CGI-like) way.
Perl is the most common language used for CGI scripts, partly because it's easily ported from one
platform to another, partly because it's great for massaging data into understandable information,
You can use other programming languages, like C++, tcl, Visual Basic, PHP, or even Apple-Script
to create CGI scripts. My advice is that if you know one of these languages, you should use it;
otherwise, use Perl.
One extra nice thing about Perl programmers is that they often like to share. You can find tons of
ready-to-use CGI scripts written in Perl all over the Web (see page 266). Many are free, many are
not.
Each element on your form will have a name and a value associated with it. The name identifies
the data that is being sent. It might be something like visitor_name. The value is the data (say,
Cookie), and can either come from you, the Web page designer, or from the visitor who types it in
a field (Figures 16.1 and 16.2). When a visitor clicks the submit button (or an active image—see
page 286), each form element's name-value pair is sent to the server (for example, it might look
like visitor_name=Cookie).
Figure 16.1. Here's your basic form. There are two text fields, one set of radio
buttons and a submit button. The words Name, E-Mail, Computer, Macintosh, and
Windows are all labels. They do not affect the data that is collected in any way.
Figure 16.2 Here's the (X)HTML code that is behind the form in Figure 16.1. Just
focus on the name and value attributes for now. (You'll learn how to create form
elements later on in the chapter.) First, notice how each form element has a name
attribute, but only some have a value. The value attribute determines the data
that is sent to the server for that element. Some form elements allow the visitor to
type in any value (like text boxes) while others do not (like radio buttons). Form
elements that work by checking or selecting must have the value specified in the
value attribute.
</form>
Figure 16.3. When the visitor enters information in the text fields and chooses a
radio button, the name-value pairs are set. Clicking the submit button (labeled here
"Send info") will send the name-value pairs to the CGI script on the server.
Figure 16.4 These are the actual name-value pairs that will be sent when the visitor
clicks the submit button in Figure 16.3. Be sure not to confuse label with name.
Also, notice that the values for the first two fields correspond to what the visitor
has typed. The value for the radio button—Mac (not Macintosh, which is the
label)—was set by me, the author of this Web page (see Figure 16.2) since the
visitor can only click the button (and not type).
Figure 16.5 This is what the data that is sent to the CGI script looks like. Notice
that each name is linked with its value with an equals sign (=). An ampersand (&)
separates each name-value pair and spaces are replaced with plus signs.
CGI scripts generally have two functions. The first is to take all those name-value pairs and
separate them out into individual intelligible pieces. The second is to actually do something with
that data—like print it out, multiply fields together, send an e-mail confirmation, store it on a
server, or whatever. There are CGI scripts that create guestbooks, bulletin boards, chat areas,
counters, games, postcard senders, image randomizers, scripts that work with databases, let you
edit Web pages, and many, many more.
Security
Before you get too excited, you should know that CGI scripts can leave your server wide open to
invaders. That's one reason some ISPs do not allow their users to use CGI scripts. If this is your
case, one alternative is to use a form hosting service, as described on page 271.
If your ISP does allow you to run CGI-scripts, you should still read up on security issues. You
might start with http://www.w3.org/Security/Faq/ and in particular
http://www.w3.org/Security/Faq/wwwsf4.html for more information on how CGI scripts can make
you vulnerable, and how you can protect yourself.
Getting a Script
If your ISP okays your use of CGI scripts, your next step is to get your hands on one. You might
start with the scripts included with this book (see page 267). Or you can either write your own or
adapt one of the hundreds of scripts available on the Web. Some of these scripts are free, others
require some sort of compensation to the programmer. While you can find scripts all over the
Web, I've found four particularly good places to look.
CPAN
The Comprehensive Perl Archive Network (CPAN) is the official Perl script repository. You can
find it at www.cpan.org (Fig. 16.6).
Figure 16.6. The Comprehensive Perl Archive Network is the official Perl script
repository.
The CGI Resource Index lists hundreds of links to Perl CGI scripts, documentation, books,
magazine articles, programmers, and jobs. It's at www.cgi-resources.com.
Extropia.com
Another famous source for free Perl CGI scripts is Extropia.com, created by Selena Sol and
Gunther Birznieks. Extropia offers many useful scripts that its authors have generously released to
While not the biggest or perhaps the most popular, Darryl Burgdorf's site houses what I think is
the best documented and easiest to implement collection of Perl CGI scripts.(I use his excellent
WebBBS for my Question and Answer forums.) You can find The WebScripts Archive at:
www.awsd.com/scripts.
Figure 16.7 This is an extremely simple script that uses CGI.pm to parse incoming
form data and then prints out the results to the screen. It neither saves the form
data, nor sends it anywhere. Its only use is to see how forms interact with scripts.
#!/usr/local/bin/perl
use strict;
Tips
If you're using a Perl script that you've downloaded from someone else, you'll have to open it up
and see what variables and path names it uses. You will have to change these to reflect your
particular situation.
The next step is to copy the script to the server, generally with an FTP program like WS_FTP (see
page 408) or Fetch (see page 410). Make sure you upload them in ASCII mode, not binary. Some
servers require that all CGI scripts be located in a central cgibin directory. Others provide a
personal cgibin directory for each user. Still others let you store CGI scripts wherever you want, as
long as you add a particular extension to them for identification. You'll have to ask your ISP.
Permissions
If your page is on a Unix server, you will have to use a program called chmod to make the CGI
script accessible and executable. For more details type man chmod at the Unix prompt. Some
FTP programs (like Fetch, for instance) let you change permissions as well.
So you've got your CGI script on your server, ready to go. The only thing left is to add it to your
form (see page 269).
Creating a Form
A form has three important parts: the form tag, which includes the URL of the CGI script that
will process the form; the form elements, like fields and menus; and the submit button which
sends the data to the CGI script on the server.
To create a form:
Figure 16.8 Every form has three parts: the form tag, the actual form elements
where the visitor enters information, and the submit button (or active image) that
sends the collected information to the server.
<hr />
</form>
Figure 16.9. A form gives you a great way to get information and feedback from
your visitors.
Tips
• In order for your visitor to send you the data on the form, you'll need either a submit
button (if your form contains fields, buttons, and other elements that your visitors
will fill in) or an active image. For more on submit buttons, consult Creating the
Submit Button on page 282. For details on active images, consult Using an Image to
Submit Data on page 286.
• You can use CSS (see page 175) or tables (see page 215) to lay out your form
elements more precisely.
Figure 16.10 One way to get around the complications of CGI scripts is to have the
data that is submitted with the form sent to your e-mail address.
Figure 16.11. Forms that will be submitted via e-mail look precisely the same as
those that are processed with a CGI script.
Of course, it doesn't matter which browser or e-mail client you use, it only matters which
ones your visitors use.
• When the visitor clicks the submit button, an alert appears warning them that their
e-mail address will be submitted along with the data and that the data will not be
encrypted. They have to click OK to continue submitting the data.
• The From field's value depends on what the visitor has entered in their
browser's preferences. It may or may not be truthful.
Tips
• Most form hosting services send you the gathered data in an e-mail message.
• Not all form hosting services are the same. Although they generally all process
forms in exchange for advertising, some ads are not as intrusive as others.
1. If desired, type the label that will identify the text box to your visitor (for
example,Name:).
2. Type <input type="text".
3. Type name="name", where name is the text that will identify the input data to the server
(and your script).
4. If desired, type value="value", where value is the data that will initially be shown in the
field and that will be sent to the server if the visitor doesn't type something else.
5. If desired, define the size of the box on your form by typing size="n", replacing n with
the desired width of the box, measured in characters.
6. If desired, type maxlength="n", where n is the maximum number of characters that can
be entered in the box.
7. Finish the text box by typing a final />.
Figure 16.16 While it's essential to set the name attribute for each text box, you
only have to set the value attribute when you want to add default values for a text
box.
Figure 16.17. Text boxes can be different sizes to accommodate different types of
fields.
Tips
1. If desired, type the label that will identify the password box to your visitor (for example,
Enter password:).
2. Type <input type="password".
3. Type name="name", where name is the text that will identify the input data to the server
(and your script).
4. If desired, define the size of the box on your form by typing size="n", replacing n with
the desired width of the box, measured in characters.
5. If desired, type maxlength="n", where n is the maximum number of characters that can
be entered in the box.
6. Finish the text box by typing a final />.
Figure 16.19 The name attribute identifies the password when you compile the
data.
Figure 16.20. When the visitor enters a password in a form, the password is hidden
with bullets.
Tips
1. If desired, type the introductory text for your radio buttons. You might use something like
Select one of the following.
2. Type <input type="radio".
3. Type name="radioset", where radioset both identifies the data sent to the script and also
links the radio buttons together, ensuring that only one per set can be checked.
4. Type value="data", where data is the text that will be sent to the server if the radio
button is checked, either by you (in step 5) or by the visitor.
5. If desired, type checked="checked" to make the radio button active by default when the
page is opened. You can only do this to one radio button in the set. (The ="checked" is
optional in HTML.)
6. Type the final />.
7. Type the text that identifies the radio button to the visitor. This is often the same as
value, but doesn't have to be.
8. Repeat steps 2–7 for each radio button in the set.
Figure 16.22 The name attribute serves a dual purpose for radio buttons: it links
the radio buttons in a given set and it identifies the value when it is sent to the
script. The value attribute is crucial since the visitor has no way of typing a value.
<b>Size:</b>
Figure 16.23. The radio buttons themselves are created with the (X)HTML tags. The
labels (King, Queen, etc.) are created with plain text alongside the (X)HTML tags.
Tip
Creating Checkboxes
While radio buttons can accept only one answer per set, a visitor can check as many checkboxes in
a set as they like. Like radio buttons, checkboxes are linked by the value of the name attribute.
To create checkboxes:
1. If desired, type the introductory text (something like Select one or more of the
following) for your checkboxes.
2. Type <input type="checkbox". (Notice there is no space in the word checkbox.)
3. Type name="boxset", where boxset both identifies the data sent to the script and also
links the checkboxes together.
4. Type value="value" to define a value for each checkbox. The value will be sent to the
server if the checkbox is checked (either by the visitor, or by you as described in step 5).
5. Type checked="checked" to make the checkbox checked by default when the page is
opened. You (or the visitor) may check as many checkboxes as desired.
Figure 16.25 Notice how the label text (not highlighted) does not need to match the
value attribute. That's because the label text identifies the checkboxes to the
visitor in the browser while the value identifies the data to the script.
<p><b>Extras:</b>
Figure 16.26. The visitor can check as many boxes as necessary. Each
corresponding value will be sent to the script, together with the checkbox set's
name.
Tip
Creating Menus
Menus are perfect for offering your visitors a choice from a given set of options.
To create menus:
6. Type >.
7. Type <option.
8. Type selected="selected" if you want the option to be selected by default. (The
="selected" is optional in HTML.)
9. Type value="value", where value specifies the data that will be sent to the server if the
option is selected.
10. If desired, type label="name", where name is the word that should appear in the menu.
11. Type >.
12. Type the option name as you wish it to appear in the menu.
13. Type </option>.
14. Repeat steps 7–11 for each option.
15. Type </select>.
Figure 16.28 Menus are made up of two HTML tags: select and option. You set
the common name attribute in the select tag and the individual value attribute
in each of the option tags.
<b>Type of wood:</b>
<select name="woodtype">
<option value="Mahogany">Mahogany</option>
<option value="Pine">Pine</option>
<option value="Cherry">Cherry</option>
</select>
Figure 16.29. There's no way for a visitor to select nothing in a menu unless you
set the size attribute. The default selection is either the first option in the menu or
the one you've set as selected in step 8.
If you have a particularly large menu with many options, you may want to group the options into
categories.
Figure 16.31 Each submenu has a title, specified in the label attribute of the
optgroup tag, and a series of options (defined with option tags and regular
text).
<b>Type of wood:</b>
<select name="woodtype" >
<option value="Pine">Pine</option>
<option value="Fir">Fir</option>
</optgroup></select>
Figure 16.32. IE 5 for Mac is the only browser that displays optgroup elements as
true submenus. Snazzy!
Tips
1. If desired, type the explanatory text that will identify the text area.
2. Type <textarea.
3. Type name="name", where name is the text that will identify the input data to the server
(and your script).
4. If desired, type rows="n", where n is the height of the text area in rows. The default
value is 4.
5. If desired, type cols="n", where n is the width of the text area in characters. The default
value is 40.
6. Type >.
7. Type the default text, if any, for the text area. No formatting is allowed here.
8. Type </textarea> to complete the text area.
Figure 16.34 The value attribute is not used with the textarea tag. Default
values are set by adding text between the opening and closing tags (as in
"Comments?" here).
Figure 16.35. The visitor can override the default text simply by typing over it.
Tips
The enctype attribute ensures that the file is uploaded in the proper format.
3. Type the caption for the file upload area so your visitors know what to do. Something like
What file would you like to upload? would work well.
4. Type <input type="file" to create a file upload box and a Browse button.
5. Type name="title", where title identifies to the server the files being uploaded.
6. If desired, type size="n", where n is the width, in characters, of the field in which the
visitor will enter the path and file name.
7. Type the final />.
8. Complete the form as usual, including the submit button and final </form> tag.
Figure 16.37 To allow visitors to upload files, you must make sure to set the proper
enctype attribute, as well as create the file type input element.
</form>
Figure 16.38. When you create a file upload area, both a field where the visitor can
type the path to the file and a Browse button (so the visitor can use an Open dialog
box to choose the file) automatically appear on your page.
Tips
• The size attribute is optional, but since most paths and file names are pretty long,
it's a good idea to set it at 40 or 50. The default is 20.
• You can't use the get method for forms that allow uploading.
Imagine, for example, that on the first page, you ask for a visitor's name, address, and telephone
number. You then want to send them to your catalog page where they can choose which piece of
furniture they wish to order. Instead of asking them for their personal data a second time, you can
use a CGI script to collect the data from the first form and then generate the hidden fields that will
contain this data in the second form. Then, when you go to process the data from the second form,
all of the fields, including both the items ordered and the personal data, will be analyzed.
Figure 16.40 An excerpt from the (X)HTML file used to create the form shows the
syntax for hidden elements. It doesn't make much sense to write such code
yourself and thus I'm reluctant to create such an example. Instead, your CGI script
should generate this code.
Tips
• It doesn't matter where the hidden fields appear in your form since they won't
appear in the browser anyway. As long as they are within the opening and closing
form tags, you're OK.
• In HTML, you don't have to use the quotation marks around the name and value if
the name and value are comprised of only alphanumeric characters—that is, no
spaces and no funny symbols. Since quotation marks have a special meaning in a
Perl script and will thus need to be backslashed to get rid of that special meaning,
it's often simpler to leave them out altogether where possible. (In XHTML, of
course, you always have to use quotes around attribute values.)
• To create an element that will be submitted with the rest of the data when the visitor
clicks the submit button but that is also visible to the visitor, create a regular form
element and use the readonly attribute (see page 292).
Figure 16.41 If you leave out the name attribute, the name-value pair for the submit
button will not be passed to the script. Since you usually don't need this
information, that's a good thing.
Figure 16.42. The most important function of the submit button is to activate the
script that will collect the data from the other fields. You can personalize the
button's contents with the value attribute. (The phrase Order Bed is clearer for
your visitors than the default Submit Query).
Figure 16.43. If there is no name attribute specified for the submit button, not even
the submit button's value attribute will be gathered by the script. But, hey, what
do you need it for anyway?
• If you leave out the value attribute, the submit button will be labeled Submit
Query, by default.
• The name-value pair for the submit button is only sent to the script if you set the
name attribute. Therefore, if you omit the name attribute, you won't have to deal
with the extra, usually superfluous submit data.
• On the other hand, you can create multiple submit buttons (with both the name and
value attributes) and then write your CGI script to react according to which
submit button the visitor presses.
(X)HTML includes several tags that let you create prettier submit buttons. You can add an image,
change the font, or even change the background color. That'll get them to submit that form!
Figure 16.45. The (X)HTML code for a submit button with an image is a little more
complicated, but looks so good. (Although it would help if I could actually draw.)
• You can also use the button tag to create a submit button without an image. Just
skip steps 4–6.
• You can use CSS to style buttons.
• For information on creating buttons with scripts, consult Creating a Button that
Executes a Script on page 318.
• Current browsers support the button tag quite well. Older browsers do not,
despite it being a standard part of (X)HTML.
Figure 16.46 You can use the value attribute to set any text you wish for the reset
button.
Tip
You can add images, font choices, and even a background color to your reset button.
Figure 16.48 Make sure you set the type to reset. Otherwise, the button won't
actually do anything at all.
Figure 16.49. Now both the submit and reset buttons really stand out. (It really
works, by the way. Try it on my Web site—see page 24.)
Tips
• You can also use the button tag to create a reset button without an image. Just
skip steps 4–6.
• For information on creating buttons with scripts, consult Creating a Button that
Executes a Script on page 318.
• Current browsers support the button tag quite well. Older browsers do not,
despite it being a standard part of (X)HTML.
Figure 16.50 If you use an active image, you don't need a submit button.
Figure 16.51. You can have both regular form elements (like the radio buttons) and
an image map in the same form. When the visitor clicks the map, all of the data is
sent to the script.
• Setting the value attribute has no effect. The values are set to the mouse
coordinates automatically.
• All the form data is sent when the visitor clicks the active image (Figure 16.52).
Therefore, it's a good idea to explain how to use the active image and to place the
image at the end of the form so that the visitor completes the other necessary form
elements before clicking the image and sending the data.
Figure 16.52. The browser appends a period and an x to the name attribute
(coord) and uses this name (coord.x) to identify the x coordinate of the
location where the visitor clicked. The same thing happens with the y
coordinate. Notice that the information from the radio button is also
collected.
1. Below the form tag but above any form elements that you wish to have contained in the
first group, type <fieldset>.
2. Type <legend.
3. If desired, type align="direction" where direction is left or right.
4. Type >.
5. Type the text for the legend.
6. Type </legend> to complete the legend.
7. Create the form elements that should belong in the first group. For more information, see
pages 272–286.
8. Type </fieldset> to complete the first group of form elements.
9. Repeat steps 1–8 for each group of form elements.
Figure 16.53 The fieldset tag is ideal for separating your form into smaller,
more easily understood chunks.
<fieldset><legend>Personal Information</legend>
<fieldset>
</textarea></fieldset>
Figure 16.54. By default, in Explorer, the fieldsets are outlined with a thin line. The
legend appears at the top right or top left. Of course, you can apply CSS to them to
create practically whatever look you want.
Tips
• You don't have to create a legend. To omit it, skip steps 2–6. In fact, you don't have
to organize your form into groups at all. While it is a useful tool, it's completely
optional.
1. Type <label.
2. If desired, type for="idname">, where idname is the value of the id attribute in the
corresponding form element.
3. Type the contents of the label.
4. Type </label>.
Figure 16.55 You link a label to its form element with the for and id attributes.
You can also label an element without a for attribute (as with E-mail) in which
case you can also skip the id attribute or not label a field at all (as with the
Comments).
<fieldset><legend>Personal Information</legend>
<p><label for="name">Name:</label>
<input type="text" name="firstname" size="15" id="name"/><br
/>
<label>E-mail:</label>
<input type="text" name="email" size="25" /></p>
</fieldset>
</textarea></fieldset>
Figure 16.56. There's no outward difference in appearance when you use labels—
unless you style them with CSS.
• If you use the for attribute, you must also add the id attribute to the associated
form element's tag in order to mark it with a label. (Otherwise, the document
will not validate.) For more details about the id attribute, consult Naming Elements
on page 67.
• If you omit the for attribute, no id attribute is required in the element being
labeled. The label and the element, in that case, are then associated by proximity, or
perhaps by being placed in a common div element.
• You can use CSS to format your labels.
• Another labeling technique is to use the title attribute. For more information,
consult Labeling Elements in a Web Page on page 72.
In the form element's tag, type tabindex="n", where n is the number that indicates the tab order.
Figure 16.57 You can add the tabindex attribute to links, form elements, and
client-side image maps.
Figure 16.58. With forms on a page that begins with a link, you may want to change
the tab order so that the first tab takes you to the first field, not the first link.
Tips
• Getting the focus means the form element is selected but not activated. Activation
requires pressing the Return key (or a keyboard shortcut—see page 290).
• The value for tabindex can be any number between 0 and 32767.
• By default, the tab order depends on the order of the elements in the (X)HTML
code. When you change the tab order, the lower numbered elements get the focus
first, followed by higher numbered elements.
• In a form, you can assign tab order to text fields, password fields, checkboxes, radio
buttons, text areas, menus, and buttons.
Figure 16.59 Add keyboard shortcuts to your form elements with the accesskey
attribute.
Tips
• On Windows systems, to invoke the keyboard shortcut, visitors use the Alt key plus
the letter you've assigned. On Macs, visitors use the Control key.
• Explorer for Windows has supported keyboard shortcuts since version 4. IE5 for
Mac and Netscape 6 also support them now. Opera has its own keyboard navigation
system and will ignore yours.
• When a visitor uses a keyboard shortcut it not only gives the element the focus, but
actually activates it. In the case of radio buttons and checkboxes, this means the
item is selected. If it's a text box, the cursor is placed inside (after any existing text).
If it's a button, the button is activated.
Figure 16.61 You can use the (X)HTML disabled attribute to make the submit
button inaccessible until other options are selected. Here, I've added a bit of very
simple JavaScript to each option so that when something is selected, the submit
button is enabled.
[snip]
</p>
Figure 16.62. When the visitor first views the form, nothing is selected and the
submit button is disabled.
Tips
• In HTML, you can just use disabled by itself. XHTML requires the redundant
value.
• You can change the contents of a disabled form element with a script. For more
information on scripting, consult Chapter 18, Scripts. You'll also need some
JavaScript expertise. The very simple way I've added here is to add
onclick="document.vote.submit.disabled=false" to each radio button (where vote
is the value of the form's name attribute, submit is the value of the disabled button's
name attribute, and disabled is the attribute in that button whose value I want to
change to false). So when one of the radio buttons is clicked, the Vote button will be
enabled.
• If you disable a form element, its keyboard shortcut is also disabled. For more
information on keyboard shortcuts, consult Adding Keyboard Shortcuts on page
290.
Figure 16.64 Add the readonly attribute to any form element that you want to
show to visitors but that you don't want them to change.
Figure 16.65. In this example, the visitor's prior votes are displayed in the read-
only text area. They can be viewed by the visitor and then submitted with the new
vote.
• In HTML, you can just use readonly by itself. XHTML requires the redundant
value.
• You can use the readonly attribute in text boxes, password boxes, checkboxes,
radio buttons, and text areas.
• Setting the readonly attribute is something like using a hidden field without
making it hidden. For more information on hidden fields, consult About Hidden
Fields on page 280.
Multimedia files, however, continue to be very large, and as technology improves, they seem to
get bigger still. Ten seconds of medium quality sound take up more than 200K, which will take
your average visitor about a minute to download. A ten second file of a movie displayed in a tiny
2" x 3" window would be about three times as big.
In addition, since the Web population is diverse, and uses many different kinds of computers, you
have to make sure that the files you provide can be viewed and heard by your visitors (or the
largest number of them possible). The fact that the developers of multimedia technologies can't
seem to agree on standards doesn't help in the least.
Please note that this chapter is meant to be an introduction to multimedia Web files, with a strong
emphasis on the (X)HTML code you need. It does not teach you how to create Flash animations or
QuickTime movies, only how to make them available to your visitors.
Netscape also created the embed element—that together with a specialized application called a
plugin—enables a browser to show multimedia and other types of files right in a Web page. Other
browsers, including, Microsoft, with a mere 25% of the market back then, followed Netscape's
lead and supported the embed tag.
The W3C meanwhile, perhaps annoyed with Netscape's non-standard, albeit innovative approach,
ignored the success of the embed tag and instead created the object element, which it thought was
a more generic and thus more powerful tool for embedding diverse types of files in a Web page.
While Netscape floundered in success, clever Microsoft started to support the newly standard
object element, but in a non-standard way—together with its proprietary ActiveX controls which it
does not share with other software companies. And with version 5.5, Explorer for Windows (but
not Mac) stopped supporting Netscape's embed tag.
Netscape 6, for its part, now fully supports the object element—actually better than Explorer—and
continues to support the embed tag for backward compatibility.
So, simple, if both major browsers support the object tag, that's what we should use, right?
Unfortunately, not quite yet. Explorer only supports the object element when used with its
proprietary ActiveX controls. But those same controls, off limits to Netscape and other browsers,
make Netscape ignore the non-standard implementation of the object element.
Figure 17.1 The first object tag uses Explorer's proprietary ActiveX controls, the
second (highlighted) uses standard MIME types and extensions to determine the
proper plugin.
codebase="http://www.apple.com/qtactivex/qtplugin.cab ">
</object>
</object>
Figure 17.2. Explorer fails to ignore the standardly coded object tag that it doesn't
understand, instead displaying a big, ugly, empty box.
In fact the only way to offer embedded multimedia files for both Explorer 5.5+ for Windows and
the other browsers, including Netscape and Opera on both platforms as well as Explorer for
Macintosh, is to combine the object element with the non-standard embed tag (Figure 17.4).
Explorer happily ignores the embed element since it has its ActiveXlaced object element (Figure
17.5), while standards-supporting browsers ignore the non-standard use of object in favor of the
familiar, if also non-standard embed tag (Figure 17.6). I explain this technique throughout this
chapter.
Figure 17.4 Here I use the ActiveX-controlled object element together with the
non-standard embed element. It is the most universal—yet least standard—
solution.
</embed>
</object>
Figure 17.5. Explorer is happy when fed just its object element with ActiveX
controls. It ignores the embed element.
Figure 17.6. Netscape ignores the ActiveX controlled object as usual, but
supports the embed tag just fine.
On Explorer for Windows, the ActiveX control can automatically install the appropriate plugin
without making the visitor close and restart their browser. It is perhaps its major positive feature.
Other browsers will alert your visitor that a new player is required and will direct them to the
proper page (as specified by you) where the necessary plugin or player can be found.
There are two important pieces here. First, it's a good idea to use standard formats (and versions of
those formats) for which it's likely your visitors will already have an appropriate plugin or player
installed. That way, they don't need to do anything special to see your multimedia files. Second,
you might want to add explanatory information on your Web page about which player is required
to properly view your multimedia files and even where users need to go to download them.
Visitors can also customize their browsers to open particular types of files (identified by their
extension, and thus their MIME type) with the program of their choice. On Netscape, they must
choose Preferences > Navigator > Helper Applications. In Explorer for Windows, from a folder on
the Desktop, they should choose Tools > Folder Options > File Types. And on Explorer for Mac,
they should select Preferences > Receiving Files > File Helpers.
Figure 17.7. With Internet Explorer 5.5+ for Windows, when the visitor goes to view
a multimedia file that requires a player that's not already on the visitor's system,
the ActiveX control asks whether the appropriate player should be downloaded
and installed. Since such actions could be a security risk, the wording of the
dialog box can be a little scary: "Security Warning".
Figure 17.9. ...they are immediately directed to the Web page where they can
download the necessary software and then install it themselves.
With the advent of digital camcorders, getting video on the Web has gotten easier and easier. On
the Mac you have the unbeatable and free iMovie which lets you input digital video via the
incorporated Firewire port, add special effects and transitions, and then automatically convert it to
QuickTime format which is easily embedded on a Web page (see page 298). Folks with Windows
ME can use Windows Movie Maker (though they'll also have to get the appropriate hardware for
connecting their digital camcorder since most PCs don't have Firewire ports).
You can also find some free sounds and movies on the Web, although you should read their
license agreements carefully. (For more information about copyrights and Web files, see
http://www.ivanhoffman.com.)
But don't limit yourself to sounds and video. You can also embed PDF files (created with Adobe
Acrobat), playable sheet music (with Sibelius Scorch), Java applets (with Sun's Java), Flash
animations (with Macromedia Flash) and much more.
One limitation to multimedia madness is your visitors' willingness to download and install plugins
or players for viewing unfamiliar formats. While you may have all the latest and greatest
multimedia helper applications, your visitors may not. Leaving your page to download a viewer
may distract them so much that they never come back.
1. Create a movie (perhaps with iMovie) and save it in QuickTime format with the .mov
extension.
2. In your Web page, start by inserting the endless number that calls Explorer's ActiveX
control for QuickTime, by typing <object classid= "clsid:02bf25d5-8c17-4b23-bc80-
d3488abddc6b" codebase= "http://www.apple.com/qtactivex/qtplugin.cab".
3. Next, without closing the initial object tag yet, type width="w" height="h", where w
and h are the desired width and height, respectively, in pixels, of the box that will hold the
movie.
4. Type > to complete the initial object tag.
5. Next, type <param name="src" value="filename.mov">, where filename.mov is the
name of your movie file.
6. Type <param name="autoplay" value="true">, to make the movie start playing
automatically when the visitor jumps to this page (or use a value of false to keep the
movie from starting automatically).
7. If you want control buttons to appear under the movie, type <param name=
"controller" value="true">. Or use a value of false to hide the controls (in which case
you better use true in step 6).
8. For browsers besides IE5.5+, type <embed src="filename.mov" width="w"
height="h" autoplay="true" controller= "true" pluginspage=
"http://www.apple.com/quicktime/download/"> </embed>, where filename.mov, w, h,
and the values for autoplay and controller have the same values as you specified in steps
2–7.
9. Finally, type </object>.
Figure 17.10 The object tag is used by Internet Explorer 5.5+ for Windows, which
no longer supports the embed tag. The embed tag is used by all other browsers.
<p>Here's my movie:</p>
<object classid="clsid:02bf25d5-8c17-4b23-bc80-d3488abddc6b"
codebase="http://www.apple.com/qtactivex/qtplugin.cab "
width="240"height="196">
</embed>
Figure 17.11. The movie shows up in the big two browsers on both platforms. No
small feat.
<p>Here's my movie:</p>
<object classid="clsid:02bf25d5-8c17-4b23-bc80-d3488abddc6b"
codebase="http://www.apple.com/qtactivex/qtplugin.cab "
width="480"height="392">
</embed>
</object>
Figure 17.13. The movie appears at twice its original size. Note that I also made the
movie's box twice its original size so that the movie itself wouldn't be cropped.
• You can download a template file from my Web site in order to save yourself from
typing that incredible classid. What were they thinking?
• You can find the size of the movie in the QuickTime player by choosing Window >
Show Movie Info (and clicking the triangle, if necessary).
• The height and width determine the size of the box that contains the movie. If the
box is too small, the movie will be cropped (or scaled if you've set a scale factor—
page 301). If the box is too big, there will be empty space around it.
• You should include an additional 16 pixels in the height to allow for the control
box.
• The default value for autoplay is defined by the visitor in their QuickTime settings.
The default value for controller is true.
• Explorer 5.5+ for Windows will use the information in the object tag while other
browsers (including Explorer for Mac) will use the information in the embed tag.
While the values of the two elements should probably match, it's not absolutely
required. You could even combine the object element for the Windows Media
Player (see page 305) with the embed tag for the QuickTime player.
Tofit, if you want the movie to be reduced or expanded to fit its box.
Or aspect, if you want the movie to be reduced or expanded to fit its box while
maintaining its original proportions.
Or n, where n is the number with which the original height and width of the movie will be
multiplied to get the final height and width.
2. Next, in the embed element add scale="value", where value is the same as the value you
used in step 1.
Figure 17.14 Don't forget to add both the param element within the object
element as well as the loop attribute to the embed tag.
<p>Here's my movie:</p>
<object classid="clsid:02bf25d5-8c17-4b23-bc80-d3488abddc6b"
codebase="http://www.apple.com/qtactivex/qtplugin.cab "
width="480"height="392">
</embed>
</object>
Figure 17.15. With a loop value of true, the movie automatically starts over when
it reaches the end.
• You may wish to also adjust the height and width of the movie's box (see page 298).
• The scale parameter changes the size of the movie, not the size of the movie's box,
which you specified in step 3 and step 8 on page 299. If you use a numerical scale
factor and the box is too small or too big, the movie will be cropped, or empty space
will appear around the movie.
• If you make the box smaller than the movie, the scale parameter gives you control
over how the movie should be adjusted to fit. If you don't specify the scale
parameter, the movie is simply cropped.
1. After the initial object tag (step 2 on page 298), type <param name="loop"
value="option">, where option is true if you want the movie to loop continuously, false
if you want the movie to play just once and palindrome if you want the movie to play
forwards and then backwards, continuously.
<object classid="clsid:02bf25d5-8c17-4b23-bc80-d3488abddc6b"
width="240" height="16"
codebase="http://www.apple.com/qtactivex/qtpl ugin.cab">
1. Follow the instructions for putting regular QuickTime movies on a page (see page 298).
2. Use a value of 16 for the height and a width of 240 for the sound-only controller.
Figure 17.18 You can also hide the controller altogether if you want a background
sound.
Tip
1. Follow the instructions for putting regular QuickTime movies on a page (see page 298).
2. Hide the control buttons altogether, thus creating a background sound, by typing after the
initial object tag, <param name="hidden" value="true"> and adding the stand-alone
attribute hidden to the embed tag.
Figure 17.19 Here's the code for embedding the Windows Media Player.
<object id="MediaPlayer1"
classid="CLSID:22D6F312-B0F6-11D0-94AB-0080C74C7E95"
codebase="http://activex.microsoft.com/activex/controls/mpla
yer/en/nsmp2inf.cab#Version=6,
4,5,715"
<embed type="application/x-mplayer2"
pluginspage="http://www.microsoft.com/Windows/
MediaPlayer/" src="madmax.avi" width="240" height="252"
autostart="0" showcontrols="1"
showstatusbar="1"></embed>
Tips
• Explorer will hide the controller if you use the hidden parameter, but it leaves an
empty space for it. (Thanks a lot!) Since Apple cautions against using a height less
than 2 pixels due to problems in some browsers, my recommendation would be to
either use a value of 3 pixels (!) or put the hidden sound at the end of your
(X)HTML page where it won't mess up your layout.
• It's probably a good idea to keep background sounds at the end of your code in all
cases. That way, your visitors can look at your page while they're waiting for the
sound to download.
• I might note that I hate background sounds. There is little more annoying to me than
jumping to a page and having to actually wait while it downloads some tinny
rendition of a song I'm embarrassed to admit that I might like in other
circumstances. They're even more awkward and annoying in office environments.
Figure 17.21. However, the ActiveX control doesn't work on the systems that are
most likely not to have Windows Media Player already installed, like folks who use
Netscape and/or Macintosh. These visitors have to click the broken link and then
manually download the plugin from the page that appears.
Figure 17.23. If Windows Media Player is not installed and the ActiveX control is
not functioning, some browsers, including Internet Explorer for Macintosh shown
here, will simply display the movie with whatever player is available (in this case
the QuickTime player).
<object codetype="application/java"
</object>
Figure 17.25. Applets you create interactive, multimedia effects on your page
without having to know how to program or script.
Figure 17.26. Go the player manufacturer's home page and search for "embed".
Tips
To insert an applet:
<head>
<title>MadMax Movie</title>
</head>
<body>
</body> </html>
Figure 17.31. ...an independent QuickTime player appears. It is not within the
browser window.
• You can get more information about Java applets at: http://java.sun.com/applets/.
• You don't need to know Java to be able to use applets on your page.
• You can also use the deprecated, but still well-supported applet element to
embed Java applets on a page: <applet code="applet.class" width="w" height=
"h"><param name="param_name" value="param_value" /></applet>, where
applet.class is the name of the applet to be embedded and the other values are the
same as described above.
1. Go to the Web site of the company that develops the player for the multimedia files you
want to embed. For example, for Flash, go to Macromedia's site
(http://www.macromedia.com).
2. Look for developer information on the Web site or search for "embedding files". Most
sites offer information about the exact value of the classid that you'll need for
embedding multimedia for IE5.5 for Windows as well as the MIME types you'll need for
embedding those same files for all other browsers.
3. Create an outer object tag with the proper classid that calls the appropriate
ActiveX control.
4. Create the param elements that control the appearance of the embedded player.
5. Create an inner embed tag with the MIME types and other information needed by
browsers that don't support Windows' proprietary ActiveX controls.
6. Close the embed element and then the object element.
Figure 17.32 The meta tag must be in the head section. It won't work if you place
it anywhere else.
<head>
<style> p {width:200px}</style>
</head>
<body>
Figure 17.33. The first page loads as usual. But wait five seconds, and...
Tip
• If you can't find information on the site, try looking at the source code of a page that
contains an embedded player. You should be able to find the value of the
classid attribute there, as well as other attributes for controlling the player.
Figure 17.35 Notice that there's not much point in adding a DOCTYPE since this
document contains proprietary tags that are not part of any specifications.
<head>
<title>Untitled</title>
</head>
<body>
</marquee>
</body></html>
Figure 17.36. With the direction set to left and behavior to scroll, the text
starts at the right and moves toward the left before disappearing off the page.
Tips
• You may wish to also include information about the player with which they should
view the file as well as a link to that player's download page.
• On most browsers, if the visitor has an appropriate plugin installed, the multimedia
file will be opened in a new browser window with an embedded player. If the visitor
does not have an appropriate plugin but does have a player, the linked file is opened
in the external player. And, if there is neither a plugin nor a player available, most
browsers will let visitors download the file and/or choose another program with
which to open it. Finally, some browsers give visitors choices along the way.
• The important point is that the browser won't load the multimedia file unless the
visitor expressly requests it.
1. In the first page, within the head section, type <meta http-equiv="refresh". (That's a
regular hyphen between http and equiv.)
2. Type content="n; where n is the number of seconds the current page should display on
the screen.
3. Type url=nextpage.html" /> where nextpage.html is the URL of the next page that you
want the visitor to jump to automatically.
4. Repeat these steps for each page in the series.
Figure 17.38 Again, there's not much point in using the DOCTYPE with non-
standard, proprietary tags.
<body>
<h1>Dakota</h1>
</p>
</body>
</html>
Figure 17.39. Woof, woof. You can't see sound, but trust me, if you play it loud
enough, your cats will disappear.
• Omit the meta tag in the last page of the series if you don't want to cycle around
again to the beginning.
• Make sure you use a display time long enough for all of your pages to appear on
screen.
• This is a great way to show a portfolio or other series of images without having to
create a lot of links and buttons.
• Be careful with the quotation marks. Notice that there is one set before content
and the closing set after the URL.
Creating a Marquee
A marquee is text that starts at one part of the screen and floats across to the left, rather like the
messages that advertise sales in the window of a 24-hour gas station. Internet Explorer for both
Mac and Windows lets you put marquees on your Web page.
To create a marquee:
1. Type <marquee.
If desired, type behavior="type" where type is scroll, for text that starts at one side
of the screen and disappears off the other, slide for text that starts at one side of the
screen and stops when it reaches the other, or alternate for text that starts at one side
of the screen and bounces back when it reaches the other side.
Tips
• I include this technique only for its historical value. This is a non-standard,
proprietary tag with little support among non-Explorer browsers. It can be easily
duplicated with the standard object tag (see page 303).
• Don't use a really obnoxious, annoying, or long sound (or even a particularly loud
one) if you want people to come back to your page with any regularity.
• The bgsound tag recognizes WAV, AU, MP3, or MIDI formatted sounds.
Most scripts are written in JavaScript, since JavaScript is the scripting language that is supported
by most browsers, including Netscape and Explorer.
Of course, there are entire books written about JavaScript—and some very fine ones indeed,
including JavaScript for the World Wide Web: Visual QuickStart Guide by Dori Smith and Tom
Negrino. In this chapter, rather than talking about how to write scripts, I'll stick to explaining how
to insert those scripts, once created, into your (X)HTML documents.
For a look at a few important scripts that you can use in your pages, consult Chapter 19,
JavaScript Essentials.
Figure 18.1 A script may appear anywhere in your (X)HTML document, however,
where it appears determines when it will be executed.
<head>
<meta http-equiv="content-type" content="text/html;
charset=iso-8859-1" />
<title>Simple Scripts</title>
</head>
<body>
<script type="text/javascript" language="JavaScript">
document.write("Visca Catalunya!")
</script>
Figure 18.2. This simple JavaScript script is output to the browser window itself.
Other scripts send their results elsewhere.
Tips
1. Type <script.
2. Type type="text/language-name", where language-name identifies the scripting
language you're using: javascript, vbscript, etc.
3. Type language="script", where script is the name of the scripting language you'll be
using: JavaScript, VBScript, etc.
4. Type src="script.url", where script.url is the location on the server of the external
script.
5. If desired, type charset="code" , where code is the official name for the set of
characters used in the external script.
6. Type >.
7. Type </script>.
Figure 18.3 Here I've created an independent text file with the same script as in
Figure 18.1. I can reference this external script from inside any (X)HTML file.
document.write("Visca Catalunya!")
Figure 18.4 The src attribute not only references the script, it also automatically
hides it from browsers that don't recognize the script tag.
<head>
<meta http-equiv="content-type" content="text/html;
charset=iso-8859-1" />
<title>Accessing external scripts</title>
</head>
<body>
<script type="text/javascript"
language="JavaScript" src="extscript.txt">
</script>
Figure 18.5. External scripts work the same way as internal ones. But they are
often much more convenient.
• Using external scripts is a great way to keep older browsers from displaying your
scripts as text. Since they don't understand the script tag, they ignore it (and the
src attribute) completely. Use noscript to give those visitors using the older
browsers an idea of what they're missing (see page 319).
• The language attribute is deprecated. Nevertheless it is often used to maintain
compatibility with older browsers.
Triggering a Script
Sometimes you won't want a script to run until the visitor does something to trigger it. For
example, perhaps you want to run a script when the visitor mouses over a particular picture or
link, or when a page is loaded. These actions—mousing over or loading a page—are called
intrinsic events. There are currently 18 predefined intrinsic events. You use them as triggers to
determine when a script will run.
To trigger a script:
1. Create the (X)HTML tag that the intrinsic event depends on (Figure 18.6).
Figure 18.6 First, create the (X)HTML tag that the intrinsic event depends
on. In this case, I want the script to occur when a visitor clicks the link.
Therefore, I have to start with the link tag.
<head>
<meta http-equiv="content-type" content="text/html;
charset=iso-8859-1" />
<title>Triggering scripts</title> </head>
<body>
<p>What <a href="time.html">time</a> is it?</p>
Figure 18.7 The event name and the script itself go right inside the (X)HTML
tag. Make sure to enclose the script in double quotation marks.
<head>
<meta http-equiv="content-type" content="text/html;
charset=iso-8859-1" />
<title>Triggering scripts</title>
</head>
<body>
<p>What <a href="time.html" onclick="alert('Today is
'+ Date())">time</a> is it?</p>
onload occurs when a browser loads a page or frameset. onunload occurs when it
unloads. They can be used in the body or frameset tags.
onclick occurs when the visitor clicks an element. ondblclick occurs when they double
click it.
onmousedown occurs when the visitor points at an (X)HTML element and presses the
mouse button down. onmouseup occurs when they let go.
onmouseover occurs when the visitor points at an element. onmousemove occurs when
the visitor moves the pointer that is already over an element. onmouseout occurs when
the visitor moves the pointer away from the element.
onselect occurs when the visitor selects some text in a form element.
onfocus occurs when the visitor selects or tabs to an element. onblur occurs when the
visitor leaves an element that was "in focus".
onkeypress occurs when the visitor types any character in a form element. onkeydown
occurs even before the visitor lets go of the key and onkeyup waits until the visitor lets
go of the key. As you might imagine, these only work with form elements that you can
type in.
onsubmit occurs when the visitor clicks the submit button in a form (see page 282).
onreset occurs when the visitor resets the form (see page 284).
onchange occurs when the visitor has changed the form element's value and has left that
element (by tabbing out or selecting another).
3. Next, type ="script", where script is the actual script that should run when the event
occurs.
Figure 18.8. A triggered script doesn't run until the visitor completes the required
action. In this case, they have to click the link.
Tips
• If your script requires quotation marks, use single quotation marks so that they're
not confused with the quotation marks that enclose the entire script (in step 3).
• If you need to use quotes within text that is already enclosed in single quotation
marks, you can backslash them. So, you could use onclick="alert('Here is today\'s
date:' + Date())". Without the backslash, the apostrophe in today's would mess up
the script.
• For a complete listing of which intrinsic events work with which (X)HTML tags,
consult the table on page 448.
• Also see Setting the Default Scripting Language on page 322.
Figure 18.10 Notice that the script is the same as the one used in the example in
Figure 18.7. The style information here is optional, but it does make the button
stand out. I also could have added an image.
Figure 18.11. Although the button tag is a standard part of (X)HTML, only current
browsers support it (with or without scripts).
Tips
• You can use other intrinsic events with buttons, but onclick makes the most
sense.
• You can also add images to buttons. Simply insert the image between the opening
and closing button tags (that is, after step 5 or 6).
• You can also use buttons with forms (see pages 283 and 285).
• Although button is standard (X)HTML, only current browsers support it.
1. Type <noscript>.
2. Type the alternate information.
3. Type </noscript>.
</script>
</head>
<body>
<noscript>Your browser isn't running scripts, so you can't
see what Llumi's thinking.</
noscript>
<p>Point at Llumi to see what she's thinking. <a
href="llumipage.html"
onmouseover="document.catpic.src = bigcat.src"
Figure 18.14. If your visitor uses a browser that doesn't support scripts (like
Mosaic, shown here), they'll get a message explaining what's missing.
Tips
• If a browser doesn't understand the script tag, what hope is there that it will
understand noscript ? Actually it won't. It will completely ignore it and treat its
contents as regular text—which, curiously, is exactly what you want. Only the
browsers that understand script (and thus can run the script) will understand
noscript as well. And as long as they've got JavaScript on, they'll ignore the
contents of the noscript tag—which is also what you want. Clever, indeed.
Figure 18.15. Or if your visitor has turned off JavaScript support (in
Communicator here), the noscript text will clue them in to the problem.
• The noscript tag will not help if the browser doesn't support the scripting
language or if there is a problem with the script.
Figure 18.16. This is Mosaic 1. Because it doesn't understand the script tag, it
ignores it and prints out the script as if it were regular text. Ugly!
</script>
</head>
<body>
Point at Llumi to see what she's thinking. <a
href="llumipage.html" onmouseover=
"document.catpic.src =bigcat.src"
onmouseout="document.catpic.src=littlecat.src"><i mg
src="real.jpg" name="catpic" width="143" height="83"
alt="The Real Llumi" /></a>
Figure 18.18. By commenting out the script, it is hidden from old browsers like this
one. (Hey, it may not handle scripts, but this old version of Mosaic displays normal
pages without trouble and runs on less than 1Mb of RAM.)
• The code in step 1 and in step 5 is for hiding the script from the browsers. The code
in step 3 is for keeping the final --> from being processed as part of the script, and
thus must be specific to the particular scripting language you're using.
• I have to admit I had a hard time finding a browser old enough not to understand
scripts. Hiding scripts from browsers is a good idea, but I'm not sure it's essential.
• External scripts (see page 315) are automatically hidden from old browsers. They
simply don't follow the URL.
Figure 18.19 This JavaScript script is adapted from Figure 19.1 on page 324. The
CDATA section removes the special meaning from the characters in the script,
essentially hiding them from the XML parser.
<body>
<script type="text/javascript" language="javascript">
<![CDATA[document.write("<p
align='right'><i>"+Date()+"<\/i><\/p>") ]]>
</script>
<h1>The Big Ben Home Page</h1>
<!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">
<head>
<meta http-equiv="content-type" content="text/html;
charset=utf-8" />
<title>Triggering scripts</title>
<meta http-equiv="Content-Script-Type"
content="text/javascript" />
</head>
<body>
<p>What <a href="time.html" onclick="alert('Today is '+
Date())">time</a> is it?</p>
<p>Here's the rest of the page.</p>
</body>
</html>
Tips
• This is only necessary for XHTML documents with internal scripts. External scripts
are automatically hidden from XML parsers.
• You can also hide internal style sheets in a CDATA section (see page 151).
Tips
• The Content-Script-Type value sets the default scripting language for all
of the scripts in a page, including the intrinsic events, internal scripts, and external
scripts.
This chapter, in contrast with the rest of this book, is not meant to teach you how, why, and when
to do something. Instead, I want to give you some simple scripts that you can easily paste into
your pages in order to create a few cool effects. Please note that there are probably much more
elegant methods of achieving these effects that make the script more flexible and more powerful.
But that would require a level of JavaScript that would not fit in a book about (X)HTML. If you'd
like to find out more about what you can do with JavaScript, you might try the latest edition of
JavaScript for the World Wide Web: Visual QuickStart Guide, by Tom Negrino and Dori Smith
(http://www.javascriptworld.com).
There are a couple of things to keep in mind while writing JavaScript. You should be very careful
with spaces, returns, and all the funny punctuation. If you have trouble typing the scripts in
yourself, feel free to download these examples from my Web site (see page 24). I've personally
tested these scripts—and they work fine—on Explorer 4.5 and 5 for Mac, Explorer 5 and 6 for
Windows, and Netscape 4.6 and 6.2 for both Mac and Windows.
document.write("<p
align='right'><i>"+Date()+"<\/i><\/p>")
6. Save the document as text only, using the file name time.js.
7. In your (X)HTML document, place the cursor where the time should appear.
8. Type <script type="text/javascript" language="javascript" src="time.js"> </script>
to call the script from that location (Figure 19.2).
Figure 19.2 Put the script element in the place in your (X)HTML document
where you'd like the time to appear. Note that the language attribute is
deprecated and thus only valid in (X)HTML transitional (see page 315).
<body>
<script type="text/javascript" language="javascript"
src="time.js"></script>
<h1>The Big Ben Home Page</h1>
<img src="bigben.gif" alt="A very rudimentary picture
of Big Ben" width="75" height="133"
align="left" /> <br />
Tip
• When you know more JavaScript, you can format the date, add the full name of the
week and month, and change the order of the elements to better suit the situation at
hand.
Figure 19.3. The illustration is amateurish but the current time in the upper right-
hand corner makes up for everything.
1. Create the link as usual. For more details, consult Chapter 7, Links.
2. In the link tag, type onmouseover ="window.status='. (First double quotes, then a single
one.)
3. Type the text that you want to appear in the status area of the browser window when the
visitor points at the link.
4. Type '; return true". (That's a single quote, semicolon, and then the rest.)
Tips
• If there are quotation marks (single or double) or apostrophes in the text entered in
step 3, you must precede them with a backslash (Figure 19.4). Otherwise, the
browser will probably confuse them with the quotation marks that delimit the script
itself (in steps 2 and 4).
Figure 19.4 Note that the highlighted lines above are all on one line with no
returns.
Figure 19.5. Adding the onmouseover line to links gives visitors extra
information before they actually click the link.
• Make sure you don't add any returns to the status label text. They'll break the script.
• Current browsers also support the use of the onmouseover attribute to add
labels to images. Simply add the line to the img tag (Figure 19.6). For some
reason, Netscape 4 doesn't support it.
Figure 19.6. You can also use this technique to add information to images.
1. First, set up your frameset as described in Chapter 15, Frames. Make sure each of the
frames has a name (see step 7 on page 242).
2. Type <a href=" to begin the link.
3. Type javascript:location='url.html', where url.html is the page that you want to appear
in the frame that contains the link. (If you don't want this frame to change, use the URL of
the page that is currently in the frame.)
4. Type ; (a semicolon) to separate this first statement from the next.
5. Type parent.framename.location= 'newpage.html', where framename is the name of
the frame that will contain the page specified by newpage.html.
6. Repeat steps 4 and 5 for each additional frame whose contents you wish to change.
7. Type "> to complete the link tag.
8. Type the clickable text.
9. Type </a>.
Figure 19.7 There are no spaces or returns in the JavaScript lines. The file shown
here is called "toc.html" and is referenced in the first part of the script so that
when the visitor clicks the link, this TOC remains visible in the left frame (while the
two right hand frames are updated).
Figure 19.8. When the visitor clicks the Cats link in the left-hand frame...
Figure 19.9. ...both the top-right and bottom-right frames are updated while the left-
hand frame remains constant.
• If you don't feel like messing with JavaScript, you can get this effect by creating a
special frameset that holds the right-hand frames and then set the link to open that
frameset. (It's not as fast, but it works.)
Figure 19.10 Here's the keepinframes.js file. In the requested page (geese.html) we
check to see if this same page is being displayed in the wildanimals frameset or in
the wildanimals_geese frameset. If it's not in one of those, we'll display the
wildanimals_geese frameset instead of the geese.html page which was requested.
Note that there are only two lines in this script (It is wrapped to fit in the column.)
Figure 19.11 Call the script from the head section of your (X)HTML page.
<title>Geese</title>
<script type="text/javascript" language= "javascript"
src="keepinframe.js"></script>
</head>
Figure 19.12. The visitor types the URL of the desired page...
Figure 19.13. ...and instead of displaying the geese.html page, the browser shows
the wildanimals_geese.html page (which is the frameset that contains the
geese.html page).
Tip
• This script says "if the requested page isn't displayed in one of the allowed
framesets, display this frameset instead".
1. Type <a href="page.html", where page.html is the page that will be displayed if the
visitor actually clicks the link (as opposed to just pointing at it).
2. Type onmouseover="document. imgname.src=, where imgname is the value of the
img tag's name attribute (see step 11, below). Note that there are no spaces before or
after the periods.
3. Type 'image-in.jpg' where image-in.jpg, is the name and extension of the image file that
should be displayed when the visitor points at the image.
4. Type " to complete the attribute.
5. Type onmouseout="document. imgname.src=, where imgname is the value of the img
tag's name attribute (see step 11, below). Note that there are no spaces before or after the
periods.
6. Type 'image-out.jpg', where imageout.jpg is the name and extension of the image file
that should be displayed when the visitor points away from the image.
7. Type " to complete the attribute.
8. Add other link attributes as desired (see Chapter 7, Links).
9. Type > to finish the link.
10. Type <img src="initialimage.jpg", where initialimage.jpg is the file name for the image
that should appear before the visitor even picks up their mouse.
Figure 19.15. The image that appears initially is the one specified by the img tag.
Figure 19.16. When the visitor passes the mouse over the image (which is also a
link—notice the status bar), the image referenced by the onmouseover attribute
is revealed.
Figure 19.17. When the visitor points the mouse away from the image, the image
referenced by the onmouseout attribute is displayed (in this case, it's the same as
the original image specified by the img tag).
• The images should be the same size. If they're not, the second one will be
shoehorned in to fit.
• Note that the img element's name attribute is used in both step 2 and step 5. That's
because the name attribute identifies the space (the particular img element) that
will be replaced with both of the other images. The name must match exactly,
including case.
• If you don't want the image to be part of the link, after step 9, type some clickable
text, then do step 16 before completing steps 10–15.
• You can preload the images involved in a rollover so that the effect is immediate.
For more details, consult Loading Images into Cache on page 331.
1. In a separate text document, on the first line, type label=, where label is a word that
identifies the image.
2. Type new Image(h,w), where h and w are the image's height and width, in pixels.
3. On the next line, type label, where label matches the label used in step 1.
4. Directly following the name in step 3 (i.e., with no extra spaces), type .src="image.url",
where image.url is the location of the image on the server.
5. Repeat steps 1–4 for each image you wish to load into cache (Figure 19.18).
Figure 19.18 Here's the loadimages.js file that I use to load the cat images
into cache in order to make the rollover effect appear more fluidly. You can
preload as many images as you'd like. There should be two lines for each
image—one to create the image space and one to fill it with the
corresponding URL
littlecat.src = "real.jpg"
bigcat.src = "dream.jpg"
Figure 19.19 Notice that the scripts in the body of the page (explained on
page 329) now references the bigcat.src and littlecat.src objects.
You don't need to enclose these labels in quotes, as you do with the actual
file names (step 3 on page 329).
Figure 19.20 The file name of the document shown here is hawthorne.html. The
first part of the JavaScript statement says "keep displaying the hawthorne.html
document right where it is". The second part of the JavaScript code says "and
then open a window labeled characters that's 150 pixels by 150 pixels, with
scrollbars, and display the hester.html file in it".
Figure 19.22. ...the link is displayed in the new window. Contrast this example with
the one shown in Figure 7.13 on page 122.
Tip
• To open a new window automatically as the main page loads (with no link at all),
type onload="javascript: and then follow steps 2–8 above within the body tag of
your main page's (X)HTML code. Then open other links in the new window by
using target="label", where label matches step 3. For details, see page 122.
Fortunately, (X)HTML is designed to support every symbol and character in every language in the
world. When creating a Web page that will contain symbols and non-English characters, it's
important to take into account the file's encoding (that is, the system used to convert the characters
on the screen into the computer's internal system), the browser's support for such encodings
(generally good in current browsers from versions 4 on) and the fonts that your visitors will have
available.
Special thanks to Alan Wood for his help understanding how multilingual Web pages work. His
site (http://www.alanwood.net/unicode/) is an excellent resource.
In non-English speaking countries, ASCII is clearly insufficient. Instead, they use slightly larger
encodings sometimes encompassing more than one language. In order to maintain compatibility
with English, these encodings treat the first 128 characters in the same way as ASCII and assign
128 new characters to positions 129–256. The only problem is that each regional encoding does it
in a different way. So, for example, if you want to write in Spanish, you might use the ISO-8859-1
encoding but if you want to write in Cyrillic, you need the ISO-8859-5 encoding. And if you want
to write Spanish and Cyrillic together, or send a Spanish document to a Russian computer, it's a
big problem.
A more definitive solution is Unicode. Unicode is designed to be a universal system for encoding
all of the characters in all of the world's languages. By assigning each character in each language a
unique code, Unicode lets you include in a document any character from any language, and indeed
multiple characters from multiple languages, without fear that it (or they) will be misinterpreted.
Figure 20.1 Each of these characters has the same code (E4) in its respective local
encoding, which makes it impossible, for example, to have both a Greek sigma and
a Hebrew hay.
Figure 20.2 In Unicode, each character has a unique code, and thus they may all
appear in the same document without confusion (as long as that document is
encoded with UTF-8).
The form of Unicode used in HTML and XHTML is called UTF-8, which has the added
advantage of encoding ASCII characters in the same way that ASCII does. That means that older
browsers that may not recognize UTF-8 will still understand the English portion of the page, and
indeed any character numbered 1–128. Its principal disadvantage is that pages written in double-
byte languages (like Chinese, Japanese, and Korean) take up almost twice as much file space as
they would with a local, more limited encoding.
As a Web page designer, you must choose a proper encoding that encompasses all of the
characters in your document, declare that encoding in the (X)HTML code (Figure 20.3), and
specify the encoding when you save your file (Figure 20.4). If you've never specified an encoding
before, your text editor selected one for you—probably the default encoding for your operating
system. For example, most text editors on Windows in the U.S. will save "text-only" files in the
Western ANSI encoding, whose official name is windows-1252.
Figure 20.3. Here's part of an XHTML document that contains both English and
Japanese. Since I'm going to save it in the shift-jis encoding, I declare that
encoding with the meta tag (details on page 339).
Once you've done your part, your visitors still need a browser that recognizes the encoding you've
used as well as a font that includes the characters in your page (Figure 20.5). Most current
browsers, including IE and Netscape for both Mac and Windows from version 4 on, support UTF-
Figure 20.5. When the visitor goes to this page, their browser will see the meta tag
and automatically view the page with the proper encoding (shift-jis).
You may want to suggest that your visitors go to Alan Wood's excellent Unicode Resources site
(http://www.alanwood.net/unicode/) which includes information about getting the appropriate
language kits and fonts, as well as how your visitors should set up their browsers to use such fonts,
once they've been downloaded.
Figure 20.6. In Microsoft Word, first choose Encoded Text in the Save as type box,
then enter the file name (with the .html extension). Finally, click Save.
1. When you go to save your document, choose the appropriate option for selecting an
encoding.
In Word, it's called Encoded Text, and you'll find it in the Save as type box.
2. Choose the desired encoding from the list or options that appear (Figures 20.7 and 20.8).
Figure 20.7. Choose the desired encoding from the list that appears. In
Word (shown), this dialog box appears after clicking Save in the Save As
dialog box shown in Figure 20.6 and insisting in the next alert that appears
that you really, really want to encode your text.
Tips
• Which is the proper encoding? My first choice would be UTF-8. My second choice
would be the regional encoding for the main language used on your page. For a list
of common encodings, see http://www.w3.org/International/O-charset-lang.html.
• Once you've saved your file with the proper encoding, you must declare that
encoding in the code with the meta tag (see page 339).
In Word, choose Encoded Text from the Files of type box (and note tip below).
In BBEdit, choose the proper encoding from the Read as pop-up menu.
3. Depending on the program, you may have to select the desired encoding from a list that
appears.
4. Then choose your file and click Open.
Figure 20.9. When you go to open a file for editing, choose Encoded Text in the
Files of type box, and then type the name of the file in the File name box. (Or make
all your (X)HTML files appear by typing *.html in the File name box, and then click
the desired file.)
Figure 20.10. Text editors (including Word) can't tell which encoding a file is in. If
they guess incorrectly and use the wrong encoding (like here), the characters look
pretty awful.
Figure 20.12. In the head section of your Web page, create a meta tag that
describes the encoding you used to save the file.
• You have to make Word ask you for the proper encoding—choose Tools > Options,
click the General tab, and check "Confirm Conversion at Open"—otherwise it uses
your system's default encoding.
• BBEdit comes with a handy AppleScript (in the BBEdit Utilities folder) that you
can drop files on in order to open them as UTF-8. I've got it on my OS X Dock.
• If you open the file and see garbage, close it without saving and try again.
Figure 20.13. When you tell the browser what encoding to expect, and as long as it
supports that encoding and the visitor's system has an appropriate font, the
characters display properly.
Figure 20.14. If you don't tell the browser what to expect, it makes an attempt, but
often doesn't know how to display the characters properly. The result is not pretty.
• The encoding you declare must match the encoding with which your page was
saved. Otherwise, characters that differ between the encodings will display
incorrectly.
• If you have saved your files without explicitly choosing an encoding, your text
editor probably used the default encoding for your system. You must still declare
the encoding using the meta tag as described above. On Windows in the U.S. and
Western Europe, the default encoding is windows-1252 . On Macintosh in the
U.S. and Western Europe, it's x-mac-roman .
• Fetch, the most popular FTP program for Macintosh, changes the encoding from
MacRoman to ISO-8859-1 by default upon uploading (see page 411). Therefore,
unless you change that setting, you should declare the files to be ISO-8859-1 even if
you save them as MacRoman with your text editor (which is the default for most
Mac text editors).
• If you don't specify your page's encoding, the browser (and search engines) will
guess, based on the visitor's preferences, information from the server (see next tip),
the charset attribute (see last tip), or by examining the document. You have a
better chance of the browser getting it right if you just make its life easy and tell it.
• Apache server users can add a line to their .htaccess file that indicates the default
encoding of files with a particular extension. The line should look like AddType
text/html;charset=code.html, where code is the character encoding that files with
the .html extension should be assumed to have. See page 370 for another example of
changing the .htaccess file. Thanks to Don Tobias:
http://webtips.dantobias.com/char.html
• To write a page in a different language from that of your operating system, you'll
also need keyboard layouts (or possibly an IME, input method editor) that let you
input the characters, and a text editor that supports the desired languages and that
can save the page in the proper encoding. If the text editor can at least save the file
A character reference can represent any character in the Universal Character Set (UCS) by giving
the character's unique code within that set. A character's code can be represented as either a
regular (base 10) number or as a hexadecimal number. Some characters also have associated
entities, that is, unique identifying words, that you can use instead of the number.
You can find a character's code, in hexadecimal form (which is the most common), at the Unicode
site: http://www.unicode.org/charts/. You can find the complete list of characters that have
associated entities in Appendix D or at my site: www.cookwood.com/entities/
Or type #n, where n is the base 10 number for your character (Figure 20.16).
Figure 20.18 You can use any combination of named, numeric, or hexadecimal
references in your document. It doesn't matter which encoding the document is in.
Figure 20.19. The characters display properly. Note that the visitor's browser must
have an appropriate font for the characters.
Figure 20.21. Internet Explorer for Mac displays guillemet quotes when the
language specified is French but curly quotes if the language is English.
• In general, you only need to use character references for characters that are not part
of the document's character encoding.
• The only exception to the first tip is the & symbol. In XHTML documents, when
used as text (as in AT&T), you must use its character reference (&).
• The greater than, less than, and double quotation mark symbols also have special
meaning in (X)HTML. You may use their character references—>, <, and
", respectively—where they might otherwise be misconstrued (as in the
case of showing (X)HTML code on a Web page).
• While using references for characters like é and £ is valid, using the proper
encoding (e.g., ISO 8859-1 ) is much faster for large chunks of text.
• The most common default encodings, in-cluding windows-1252 and x-mac-
roman lack several useful symbols. You can use character references to create
these symbols without touching the default encoding.
• If you're using a hexadecimal or numeric reference, don't forget the # between the
ampersand and the number. And if you're using a hexadecimal, don't forget the
lowercase letter x, that indicates that the hexadecimal is coming.
• While there are hex and numeric references for every character in Unicode, there are
named entity references for only 252 of them. They are case-sensitive. See
Appendix D for a complete listing.
• Your visitors will only be able to view the characters for which they have adequate
fonts installed. While you can specify a particular font (see page 158), it's not
required; in its absence browsers should search the available fonts for one that
includes the characters in question.
• You may also insert small quantities of special characters by using gif images (see
page 104).
Tips
Still, it has been a bit like locking the chicken coop after the fox has gotten inside; most of the
pages on the Web today already use one or more of the deprecated tags. While CSS is more
powerful, more efficient, and easier to update, for most people, (X)HTML is still easier to
understand and is often easier to use as well. Further, while CSS support has increased
dramatically, it still doesn't rival the universal support enjoyed by almost all (X)HTML tags.
Note that the formatting tags, despite being deprecated, continue to be a valid and legal part of the
transitional flavor of both HTML 4 and XHTML 1.0 (see page 38). And while some might say
that using deprecated tags is akin to heresy, there are so many pages that already use them, that it's
important to at least know how they work. And if you decide to use one here or there in new work,
well, I won't tell.
Figure 21.1 The basefont element should come directly after the opening body
tag.
</body>
Figure 21.2. In Internet Explorer 4+, on both Mac and Windows, the basefont tag
sets the default size (5), color (this is red), and font face (Trebuchet MS) of the text.
Note that the headers gain only the color and font, but are unaffected by the
basefont element's size value.
Figure 21.4. Netscape 4.x supports only the size attribute for basefont, but
ignores the color and face attributes.
</body>
Figure 21.6. IE 4+ supports the font element. Note that the initial B is two sizes
larger than the basefont size of 5, not the default text size.
Tips
• The size attribute is required. You may omit both the color and face
attributes.
• The value you choose for the size attribute is always relative to the text's default
size set in the visitor's browser. A value of 3 will display text at the same size as the
browser's default size, 1 and 2 will be smaller than the default and 4–7 will be
larger. If the visitor changes the size of the text, either with the View > Text Size
option or with Preferences, the basefont values are adjusted accordingly.
• On older browsers, text appears larger on Windows than on a Mac. In current
browsers on both platforms, browsers are set up by default to display at 96 pixels
per inch, making text more uniform across platforms.
1. Type <font
2. If desired, type size="n", where n is a number from 1 to 7.
Or, you may use a relative value, as in +2 or -3, with respect to the default size.
Figure 21.7. The support on Explorer for Mac is the same, but notice how the first
choice font is used, since it was available on this Mac, while the third choice was
used on the PC in Figure 21.6.
</body>
Figure 21.10. The text attribute is almost universally supported. Shown are
Netscape 6 (above) and Explorer 6 (below), both for Windows.
• You may specify all three attributes, or any combination thereof. None is required.
• The font tag has been deprecated. For information on using style sheets to control
font usage (and to download fonts for your visitors), see page 158.
• A value of 3 for the size attribute represents the browser's default size for text—
usually Times at 16 pixels. The tricky part is that every visitor can change their own
browser's default text by tweaking the preferences or by choosing the View > Text
Size (or Text Zoom) option.
• Relative sizes are calculated with respect to the basefont element, or to the
default of 3 in basefont's absence.
• The font element overrides the basefont element. The font element also
overrides any formatting applied with style sheets.
• See page 46 and the inside back cover for a listing of common colors and for
instructions for creating your own.
• You can also set the color of all of the body text with the text attribute in the
body element. The color attribute of the font element overrides the text
attribute in the body element.
• The font tag can change a link's size and the face, but its color. To change a link's
color, see page 350, or better yet, use styles (see page 166).
Figure 21.11 You can change the color of new links, visited links, and active links.
</body>
Figure 21.12. The link, vlink , and alink attributes are all well supported.
Making them obvious in a two-color book is another thing. You can view this
example—and indeed all of the examples—online at my Web site (see page 24).
• The body tag's text attribute works the same way as the basefont tag's
color attribute. However the text attribute is supported by all major browsers
(and probably most minor ones), in contrast with basefont/color , which is
not supported by Netscape (including 6).
• Both basefont and font override the text attribute.
• See the inside back cover for a listing of hexadecimal values and common color
representations.
• You can also specify the color of the background (see page 354) and of links (see
page 350). Make sure all the colors work well together.
• The text attribute is deprecated. For details on changing text color with styles, see
page 166.
• Most browsers allow users to override the colors that you might specify for the Web
page.
To change the color of links that have already been visited, type vlink.
To change the color of a link when the user clicks on it, type alink.
3. Type ="color", where color is a hex color or color name (see page 46 and inside back
cover).
4. Repeat steps 2–3 for each kind of link.
</body>
Tips
• See page 46 and the inside back cover for a list of common colors and instructions
for creating your own.
1. Type <strike> or <u> for strike out text and underlining, respectively.
2. Type the text that should appear with a line through or under it.
3. Type </strike> or </u>.
<h1>Famous Catalans</h1>
</body>
Figure 21.16. Blinking text appears normal (top), then disappears (bottom), then
reappears.
Tips
Another way to make text stand out is to make it blink. You can apply the blink tag to
anchors, links, or any important text that you have on the page.
1. Type <blink>.
2. Type the text that you want to blink.
3. Type </blink>.
Tips
• The blink element is not a valid part of (X)HTML, but it is so infamous, I had to
mention it. Honestly, I think it helped get people excited about the Web in its own
garish, annoying way.
• You should omit the DOCTYPE if you're going to use the non-standard blink.
• Blinking text—and other high contrast images on your page—can provoke seizures
in folks with epilepsy. It's also considered a bit gauche in the sophisticated world of
Web design. You might want to be careful where and how much you use it.
• You can include an image in your blinking definition, but it won't blink.
• You may not use blinking text in the title.
• Internet Explorer does not recognize the blink tag and probably never will. Could
it be because the blink tag was one of the driving factors behind arch-rival
Netscape's rise to fame?
• You can use styles to create valid blinking text. For more information, consult
Decorating Text on page 174.
Included among these features are setting margins and columns, controlling the spacing between
the elements on a page, changing the background color for the entire page, dividing a page into
Note that all of the elements discussed in this chapter are either deprecated (see page 343) or non-
standard and should be avoided in favor of styles. In each section, I'll point you to the page that
discusses the standard method for achieving the effect.
In the body tag, after the word body but before the final >, type bgcolor="color", where color
is either one of the standard color names or is a hex color (see page 46 and the inside back cover).
Figure 22.1 Add the bgcolor attribute to the body tag to set the background
color for the page.
<body bgcolor="#FF00FF">
users can still read the text on top of it. That is the
point, right?
</body>
Figure 22.2. Changing the background color is an easy way to give your pages a
distinctive flavor. Beware though of visitors who view pages with their own colors
(see Figure 22.3 below)—especially if the color of your text depends on your
background color.
Tips
• See the inside back cover for a list of the 16 predefined colors as well as a selection
of other colors together with their hexadecimal values. For more information about
creating your own colors, see page 46.
• The bgcolor attribute has been deprecated. I recommend using styles to control
the background (see page 182).
Figure 22.4. In this example, I've created a background image that is 68 pixels high
and 600 pixels wide. It compresses beautifully to less than 2K, but since browsers
automatically tile images smaller than the window, it will fill the background as
completely as any bigger image.
<tr>
<td valign="top">
<p><a href="calendar.html">Calendar</a></p>
Tips
• Take advantage of the fact that browsers automatically tile smaller images when
creating your background (Figure 22.6).
Figure 22.6. Because the image is so wide, it does not repeat horizontally
(and leaves room for text that is easy to read).
1. Type <center>.
2. Create the element that you wish to center.
3. Type </center>.
Figure 22.7 The center element can contain block-level elements, inline
elements, or both.
</body>
Figure 22.8. Centering a bit of text is a good way to call attention to it. The center
tag is supported by practically all browsers (despite having been deprecated by
the W3C) and is sorely missed by standards advocates.
• For information on using styles to center text, consult Aligning Text on page 171.
• You can use the center tag with almost every kind of (X)HTML element,
including paragraphs, headers, images, and forms.
• For more details on aligning paragraphs, consult Starting a New Paragraph on page
66. For more information on aligning headers, consult Creating Section Headers on
page 65.
• For information on aligning images with text, consult Aligning Images on page 114.
• For details on dividing your document into sections that you can then align, consult
Breaking up a Page into Divisions on page 68.
1. For your Internet Explorer users, in the body tag, after the word body but
before the final >, type leftmargin="x" topmargin="y", where x is the width in pixels
of the space between the left border of the window and the contents of the page and y is
the height in pixels between the top of the window and the contents of the page.
2. For Netscape folks, in the body tag, after the word body but before the >, type
marginwidth="x", marginheight="y", where x and y are the same values as in step 1.
Figure 22.9 Inside the body tag, set values for both Netscape's and Explorer's
attributes.
</body>
Figure 22.10. Each browser ignores the other one's particular attributes so you
have to use all four to have the browsers display the margins correctly.
</body>
Figure 22.12. Explorer goes back to displaying default margins (top) while
Netscape is still happy with just the marginwidth and marginheight
attributes.
Tips
1. Type <nobr>.
2. Create the text or elements that should appear all on one line.
3. Type </nobr>.
Figure 22.13 I have placed nobr tags around the header text to ensure that the
entire sentence is displayed on one line in the browser.
<p>Opening Hymn:</p>
Tips
• Elements within nobr tags will not be separated, unless there is a wbr tag (see
page 359), even if the size of the window causes them to be displayed off the
screen, and thus invisible to the user (Figure 22.14).
• Unlike the nowrap attribute used in tables to keep a cell's contents on a single line
(see page 239), the nobr tag must have an opening and closing tag and only
affects the text contained within the two.
• The nobr element is not standard (X)HTML (and thus will not validate).
Nevertheless, most browsers (current and otherwise) support it.
• You can also insert a non-breaking space (type ) between words that should
not be separated.
• You also use styles to keep lines together. Consult Setting White Space Properties
on page 170 for details.
Figure 22.15 The nobr tag keeps all the enclosed elements on the same line. The
wbr tag allows a line break—if necessary—depending on window size.
<p>Opening Hymn:</p>
Figure 22.16. When the visitor makes the window too narrow for the entire header
to fit, the line is divided where you inserted the wbr tag.
Figure 22.17. If the visitor expands the window so that the entire line can fit, the
line break is not used.
• It doesn't make sense to use the wbr tag without the nobr tags.
• Line breaks created with wbr only appear if the window is small enough to warrant
them. Otherwise, the elements will not be separated.
• The wbr tag is not part of the standard (X)HTML specifications. Just the same,
both Netscape and Explorer support it.
Before CSS, when you used the p or br tags, the amount of space between paragraphs was
only controlled by the size of the surrounding text. Larger text had larger spaces. Smaller text had
smaller spaces. Netscape's spacer tag let you specify exactly how much space should appear
between one line and another.
Figure 22.18 You might want to take out any p tags when using vertical spacers.
Otherwise, the paragraphs will have both the space allotted by the spacer tag as
well as that from the p tag. Clearly, this is a compatibility nightmare.
<html><head>
<body>
</body>
</html>
Figure 22.19. Since we haven't used a p tag, the two paragraphs run together in
Internet Explorer, which doesn't understand the spacer tag.
Figure 22.20. On a 96 dpi screen, there will be exactly 1/2 inch of white space
between the two paragraphs—as long as they're viewed in Netscape 4.x.
Tips
• The spacer tag with vertical type works only in Netscape 4.x. Styles are much
more flexible and much better supported (see pages 188 and 189).
Creating Indents
You can't type a tab, or specify a tab stop in (X)HTML documents. However, there are a
number of ways to create indents for your paragraphs for Netscape browsers.
To create indents:
Figure 22.21 Use horizontal spacers for indenting paragraphs, or any place you
need to add an invisible, horizontal block of space.
<title>Using spacers</title></head>
<body>
</body>
</html>
Figure 22.22. Internet Explorer ignores horizontal spacers completely, aligning all
text to the left. To indent text for Explorer, use styles (see page 168) or if you really
have to, use pixel shims (see page 364).
Tips
• You can use horizontal spacers anywhere you want, not just at the beginning of a
text paragraph.
• The spacer element has no real advantages over styles. I describe it here purely
for historical reasons, and in case you need to update someone's old code. I
recommend using styles to add indents (see page 168). Even pixel shims (see page
364) are better than the spacer element.
• The spacer tag, with type set to horizontal, is only supported by Netscape 4.x.
• You can also use the spacer element to create vertical spacing (see page 360).
</body>
Figure 22.25. List indents work on most browsers but they have two
disadvantages: the W3C wishes you wouldn't use them and they don't offer much
flexibility in the way of hanging or first-line indents.
• According to the (X)HTML specifications, the ul and ol tags may only contain
li elements, and not text. In other words, this rather common, but old-fashioned
technique is not valid HTML.
• This method won't work for hanging indents or first-line indents.
• For real indents using style sheets, consult Adding Indents on page 169.
Netscape's spacer tag can also be used to create blocks of space that you can wrap text
around.
1. Place the cursor where the space should appear, before any text that will wrap around it.
2. Type <spacer.
3. Type type="block".
4. Type width="w" height="h", where w and h are the width and height, respectively, of
the block, in pixels.
5. To wrap text around the block, type align="left" or align="right", depending on which
side of the block you want the text.
To align the block next to the text, without wrapping the text around it, type
align="direction", where direction is top, middle, or bottom.
Figure 22.26 When creating a block-shaped space, you have to specify the width
and the height, along with an alignment, to determine where the space will appear.
</body></html>
Figure 22.27. Don't forget: the spacer tag has absolutely no effect in Internet
Explorer (shown here). It only works with Netscape browsers.
Figure 22.28. Block shaped spaces are ideal for setting large, invisible margins—in
Netscape. (I've colored the space to illustrate it in this book, but it's really
invisible.)
• Internet Explorer does not support spacer. Netscape 6 only supports spacer
with the type attribute set to block. I recommend avoiding spacer like the
plague, in favor of the better supported, more powerful, and more flexible styles.
• For more information on wrapping text, consult Making Images Float on page 110.
For more information on the alignment options, consult Aligning Images on page
114.
• To create a colored block of space, use a pixel shim (see page 364).
1. Create a 1 pixel by 1 pixel GIF image in the desired color (see page 90).
2. In your HTML document, type <img src="pixelshim.gif", where pixelshim.gif is the
name of the image created in step 1.
3. Type width="w" height="h", where w and h are the desired width and height, in pixels,
of the desired space.
4. To wrap text around the shim, type align="left" or align="right" (see page 110).
Or you can align the shim next to the text (and not around it) by typing
align="direction", where direction is top, middle, or bottom (see page 114).
Figure 22.29 A pixel shim is nothing more than a one pixel by one pixel image, of
any color you like, expanded to the desired size, and aligned as necessary.
</body>
Figure 22.30. The principal advantage of pixel shims is that they work in almost
any browser. In addition, they are small and load quickly and they can be made
any color you need. Notice, however, that Explorer (top) leaves slightly more space
to the right of the image than Netscape.
Tips
• Pixel shims are well supported since they're just images, forced to work in a new
way. They are, however, unwieldy and inflexible. Use styles instead.
• Pixel shims are tiny (and thus, load quickly) and can be made any color you want—
or they can be transparent.
• You can download pixel shims from my site (see page 24).
Netscape tried to resolve the thirst for columns with this badly implemented multicol
tag. Among its limitations: it works only in Netscape 4.x, all columns must be the same width, and
perhaps worst of all, if you make the columns too narrow, they overlap and look horrible.
To create columns:
Figure 22.31 The only required attribute in the multicol tag is cols: you must
determine how many columns you want. (I've reduced the size of the text in this
illustration to better fit on the page.)
Figure 22.32. Columns are perfect for newspaper style articles. These take up 85%
of the screen, as defined in the HTML document. In addition, I've made the text one
size smaller so as to better fit in the columns.
Tips
• If you omit the width attribute, the columns will expand to fit whatever size
window the user has created.
• You can nest one set of columns with another. Simply repeat steps 1–7 when you
reach step 6 of the outer set.
Although they had already promised to work towards a universal standard for HTML,
Netscape developed a set of proprietary tags for positioning HTML elements in early 1997. Now
that Netscape 6 leads the pack in supporting CSS positioning techniques (see page 177), you can
forget about layers.
Figure 22.34 Each layer is defined separately with its own coordinates. I've just
entered plain text as the contents of each layer, but you can add any other HTML
tags you like, except frames.
</body>
Figure 22.35. There are four layers in this example. Layers become really useful
when combined with JavaScript.
1. Type <layer.
2. If desired, type id="name", where name identifies the layer to JavaScript.
3. Type top="m", where m is the number of pixels the layer's contents should be offset
from the top edge of the browser window.
4. Type left="n", where n is the number of pixels the layer's contents should be offset from
the left edge of the browser window.
5. If desired, type width="w", where w is the width of the layer in pixels.
6. If desired, type height="h", where h is the height of the layer in pixels.
7. If desired, type src="source.html", where source.html is the initial HTML content that
should appear in the layer (Figure 22.37).
Figure 22.37 If you know Explorer users are going to try to view your page,
you should use the src attribute in the layer tags to insert content and
then the nolayer tags to alert Explorer users to the fact that they won't
see the effect.
<body>
8. If desired, type clip="t, l, r, b" where t, l, r, and b are the offsets in pixels from the top,
left, right, and bottom.
9. If desired, type z-index="z", where z is a number indicating the layer's level if it overlaps
other layers. The higher the value of z, the higher the layer.
10. If desired, type bgcolor="color", where color is a hex color or one of the predefined
colors listed on the inside back cover.
11. If desired, type background="image.gif", where image.gif is the image that you'd like to
use for the background of the layer.
12. Type >.
13. Create the contents of the layer.
14. Type </layer>.
Figure 22.38. Communicator displays the contents from the files in the src
attribute.
Tips
• Layers were designed to be combined with JavaScript to create dynamic pages. For
more information, check out
http://developer.netscape.com/docs/manuals/communicator/dynhtml/layers3.htm.
My basic examples don't quite do it justice.
• You can create content for browsers (like Explorer) that don't recognize the layer
tags. Simply enclose it in opening and closing nolayer tags (Figure 22.39).
• To create relatively positioned elements (that is, elements that are offset with
respect to their natural position in the flow), use opening and closing ilayer tags
instead of layer tags.
• The official way to position elements precisely is with styles (see Chapter 11,
Layout with Styles), not this non-standard and poorly supported layer tag. Now
that Netscape 6 supports CSS, you can forget about the layer element forever. I
include the information here solely so that you can decipher old code.
Instead, the standard language for writing Web pages for mobile devices is WML, or Wireless
Markup Language. Based on XML—indeed, it's an application of XML—WML insists you
follow the same syntax rules that you've learned for XHTML: lowercase tag and attribute names,
quoted attributes, end tags, in short, valid and well-formed documents. In addition, WML asks that
you be extremely careful about size. Images should be kept to a minimum and the files themselves
should be tiny (under 2K).
Actually, WML looks remarkably like a scaled down version of XHTML, with many of the same
elements (p, br, em, etc.), although some of those elements have distinct attributes. You'll learn
all the rules for writing WML files in this chapter.
While the promise of XHTML and CSS is that you can create a single file that can be served
properly both to a desktop browser and to a microbrowser on a mobile device, the reality is that
most phones simply don't support XHTML (or even WML plus CSS) yet. Nevertheless, the
similarity between WML and XHTML makes WML an ideal first step towards XHTML for
mobile devices.
Figure 23.1. I used Openwave (right) and Nokia simulators to create the
illustrations for this chapter. They are an essential tool for developing mobile Web
sites. Download information is on page 392.
1. On the first line of a text file, type DirectoryIndex followed by a space and then
index.wml, where index.wml is the name of the file that should be displayed if a visitor
types the URL of the directory.
2. Press the Return key.
3. Type addtype mime extension, where mime is the MIME type for the desired kind of
file, and extension is the three or four letter extension those kinds of files will have. Press
Return.
4. Repeat step 3 for each type of file that you want to be able to serve.
Figure 23.2 Here is a typical .htaccess file. You can ask your ISP to set this up, or
you can simply add the file to the directories that contain your WML files.
DirectoryIndex index.wml
Tips
• You may need to give the file a different local name if your system does not permit
initial periods in the name.
• You can download a sample (but valid) .htaccess file from my site (see page 24).
1. At the very top of a blank page in any text editor, type <? xml version="1.0" ?>.
2. Next type <!DOCTYPE wml PUBLIC "//WAPFORUM//DTD WML 1.3//EN"
"http://www.wapforum.org/DTD/wml13.dtd"> so that browsers know that the page is
written in WML (version 1.3) and is designed for WAP browsers.
3. Next type <wml> to begin the actual content of your page.
4. Create the page, using the techniques described throughout this chapter.
5. Type </wml> to finish your page.
6. Make sure to save your document as text only with the .wml extension.
Figure 23.3 Don't forget the closing </wml> element. Nothing will work without it.
<?xml version="1.0"?>
"http://www.wapforum.org/DTD/wml13.dtd ">
<wml>
</wml>
• Windows users, you may want to enclose the file name in double quotation marks
so that Windows doesn't add any extra extensions to your file name as you save
(Figure 23.4).
Figure 23.4. When saving the file, choose All Files (*.*) if available and
enclose the file name in double quotes to keep Windows from adding
extraneous extensions to your files (and making them inoperable).
• Since WML is an XML application, you must follow all those persnickety syntax
rules, including using all lowercase letters for tags, attributes, and preset values,
quoting all values, using end tags, etc. For an overview, consult HTML vs XHTML
on page 36. For a complete reference, you might try my XML for the World Wide
Web: Visual QuickStart Guide, also published by Peachpit Press.
Creating a Card
A WML file or deck can be divided into one or more cards, which are analogous to individual
Web pages.
To create a card:
1. Within the WML document, after the <wml> element, type <card.
2. Next type id="label", where label is a unique word that will identify the card as the
target of links from other cards.
3. Type title="header", where header is the text that should appear at the top of the Web
page.
4. If desired, type newcontext="true" to unset all variables (see page 383) and to clear the
history stack.
5. Type >.
6. Create the card's content, as described on the following pages.
7. Type </card> to complete the card.
Figure 23.5 You must use a unique value for the id attribute in the card element.
"http://www.wapforum.org/DTD/wml13.dtd ">
<wml>
</card>
</wml>
Figure 23.6. The title attribute is displayed at the top of the microbrowser.
(Openwave on left, Nokia at right.)
• A deck (WML document) may have as many cards as you like. When the visitor
loads the deck, all the cards will be available to the mobile browser without having
to go back to the server.
• While all the cards in a deck are downloaded together, only one card at a time is
displayed on a mobile browser.
• A card's id serves as the target of a link. You may not use the same id twice in the
same deck (WML file).
• Your titles should be no more than about 18 characters long. Longer titles may
simply be truncated to fit.
<wml>
<p align="center">
</p>
</card> </wml>
Tips
• Remember that your average microbrowser on a cell phone has room for only three
lines of content (along with the title area and the button text line). If your card has
extra text, your visitors will have to scroll to see it. (The simulators shown here are
taller than average.)
• Most microbrowsers don't support all of the formatting elements.
• The mode attribute is most useful for displaying tables (see page 375).
• For more details about p, br, em, strong, b, i, u, big,
small, table, tr, td , and comments, consult the corresponding section
for (X)HTML elements of the same name.
Including an Image
To include an image:
1. Type <img src="image.wbmp", where image.wbmp is the name and location of the
WBMP format file that you wish to insert in the card.
2. Type alt="label", where label is a word that describes the image and will be displayed if
the image is not.
3. If desired, add the height, width, hspace, vspace , or align attributes.
4. Type />.
Figure 23.9 You must create alternate text (with the alt attribute) for all img
elements.
<wml>
<p align="center">
</p>
</card>
</wml>
Figure 23.10. Images should be no larger than 100 pixels across. Be restrained!
Creating a Table
You can use a table to align several columns of text on a page.
To create a table:
Figure 23.11 Here is a new card in the same deck as the previous examples. Notice
that the table must be enclosed in p tags.
<p>
<tr><td><b>Soup</b></td><td>Cream of Mushroom</td></tr>
</table>
</p>
</card>
Figure 23.12. The first column is aligned to the right while the second column is
aligned to the left (align="RL" ).
Creating a Link
There are two principal ways for your visitors to get from one card to another. You can either
create links within the page, or you can assign functions to a mobile device's buttons.
1. Type <anchor
2. If desired, type title="label", where the browser will use the label to identify the anchor
in some way, often as the label for the button the visitor will have to click to activate the
link. (The default is Link.)
3. If desired, type accesskey="n", where n is the number on the mobile device keypad that
the visitor should type to activate the link.
4. Type >.
5. Type the text and/or insert the image that should identify the anchor in the text.
6. Type <go href="#cardid">, where cardid is the value of the id attribute of the card that
should be displayed when the visitor clicks the link (see step 2 on page 372).
Or type <refresh> to have the link refresh the card, and any variables it contains.
7. Create any additional actions that should happen. For example, with all three tasks, you
could set a variable (see page 383), and in go tasks you can also post data to an external
script (see page 388).
8. Type </go>, </prev>, or </refresh> depending on what you used in step 6.
9. Type </anchor>.
Figure 23.13 Here are three simple links. In the first one, I've used the familiar a tag
(see second tip). In the second and third, I use the more WMLish anchor tag.
There's no difference between the two methods unless you want to do more than
just show a different card.
<p align="center">
Bistro/Pub</b></big>
</p>
</p>
</card>
Figure 23.14. Notice that when the link is highlighted, the button is labeled with the
title attribute (of either the a or anchor element)—it is the word "Go" in this
example.
Figure 23.15. The microbrowser now shows the card referenced by the link (the
Specials page in this case).
• You can also create links to cards in other decks by using the deck's URL in step 6.
Be default, the new deck's first card will be displayed. Or use URL#cardid to jump
to a specific card in a different deck.
• If you don't need to add any actions to the go task, you can use the a tag to create
simple links: <a href= "destination.wml">Click me</a>.
• The anchor element may also contain images, line breaks (br elements), and
text, but not p elements or formatting.
• The refresh action is most commonly used to set a variable. For more details
about variables, consult Setting and Using Variables on page 383.
• Only the go task can be used to send data to a server (with postfield). For
more details, consult Processing Data from Visitors on page 388.
• If you don't specify an additional action in step 7, you can combine the opening and
closing elements of the go, prev, or refresh tasks: e.g., <prev /> or <go
href="#cardid" />.
• Note that the anchor element creates a link that appears in the main body
(skimpy as it is) of the microbrowser and which must be selected by the visitor and
then activated with one of the buttons. The do element, described on page 378,
Programming Buttons
Although the WML specifications say that browsers are not bound to display the do element in a
given way, it seems that mostly, it's used to format the buttons (sometimes called soft keys) on a
mobile device.
To use buttons:
1. Type <do type="kind", where kind is one of accept, prev, (or others depending on
the device) and gives the mobile device a hint about the button's purpose.
2. If desired, type label="button word", where button word is a descriptive word that will
identify the button to the visitor. The label should be six letters or less.
3. If desired, type name="identifier" where identifier is a word that distinguishes this
button from others in your code.
4. Type > to complete the opening do tag.
5. Type <go href="#cardid">, where cardid is the value of the id attribute of the card that
should be displayed when the visitor clicks the button (see step 2 on page 372).
6. Create any additional actions that should happen. For example, with all three tasks you
could set a variable (see page 383), and with just the go task, you can post data to an
external script (see page 388).
7. Type the end tag that matches the opening one you used in step 5.
8. Type </do> to complete the button.
Figure 23.16 I've created a Help button that will bring visitors to a card with extra
information about how to use this site.
<p align="center">
Bistro/Pub</b></big>
</p>
</card>
Figure 23.17. On most microbrowsers, the accept type buttons are created on the
left side.
Tips
• The type attribute that you specify for the do element is supposed to help the
mobile device figure out what kind of button you're creating. On some phones, for
1. Within the card element, after the opening card tag, type <onevent type=
2. Next type "onenterforward" if you want the action to occur only if the visitor has
entered the card from a link or menu.
Or type "onenterbackward" if you want the action to occur only if the visitor has
entered this page by clicking a Back button or link (created with the prev element).
Figure 23.18 The onevent goes right after the opening card element.
<onevent type="onenterforward">
<p align="center">
Figure 23.19. When your visitors go the main page, they are immediately shuttled
to the Help screen.
• For example, you might want to set a variable only if the visitor jumps to the page,
but not if she returns. In that case, use a go action in step 4 that includes a
setvar element (see page 383).
• If you only want to (conditionally) jump to another page, you can use this shortcut:
<card onenterforward="destination.url"> . (You can use
onenterbackward this way as well.)
• You can also have an action occur after a certain amount of time. For details,
consult Scheduling an Action on page 381.
Figure 23.20 Now, in the Help card, we create an ontimer event so that whenever
a user comes to this card, they will have 3 seconds (30 tenths of a second), to read
the information and then they will be automatically returned from whence they
came.
<onevent type="ontimer">
<prev />
</onevent>
</p>
</card>
Scheduling an Action
You can make certain actions happen after a specified amount of time. This can be useful, for
example, to show a splash page, or to automatically close a window after a few seconds.
To schedule an action:
Tips
Making a Call
You can take advantage of the fact that many mobile browsers also happen to be telephones and
allow your visitors to make calls. To do so, you use a thing called WTAI (Wireless Telephony
Applications Interface) to connect from the browser to the telephone (roughly speaking). First,
you create a card that makes the call, using WTAI. Then, you link to that card from the card on
your deck from which you want to make the call.
1. Type <card id="callcard" title="Call", where callcard and Call are the id and
title attribute values (see page 372).
2. Within the card, add onenterforward= "wtai://wp/mc;number", where number is the
phone number that should be dialed.
3. Type > to finish the opening card tag.
4. Then type </card>. (The card is never shown to your visitors, so it needs no content.)
</card>
</card>
To make a call:
Create an anchor, do element, or onevent that goes to the card you created above. For
example, <do type="accept" name="call" label= "Call"><go href="#callcard" /></do>
would create a button labeled Call that would call the number specified in step 2 above.
Figure 23.23. When the visitor clicks the call us link at the end of the help screen
(top left and top right), they then see a screen similar to the one on the right asking
them to confirm that they'd like to make the call. Once the visitor clicks OK, the
browser sends the information to the phone and asks it to try to complete the call.
• The WTAI instruction can go anywhere a normal URL would go, for example as
the value of a href attribute in a go element.
• The card with the WTAI instruction can be in the same deck or in a different deck
as the one that references it.
Within a go, prev, or refresh element, add <setvar name="var" value="value" />, where
var is the name that will identify the variable and value is its content.
1. Place the cursor where you want the current value of the variable to appear.
You can output variables by themselves, in a larger block of text, or as the value of an
attribute.
2. Type $(var), where var is the name that identifies the variable.
Figure 23.24 You might want to set a default variable when the visitor enters a
card. Then, you can output variables within other text, as shown here, or even as
attribute values.
<onevent type="onenterforward">
</refresh>
</onevent>
</card>
Figure 23.25. The content of the variable ("2", that we set earlier) is output instead
of the variable name.
N (for a number)
M (for any letter, number, or symbol). Note: the mobile device may display in uppercase.
m (any letter, number, or symbol). Note: the mobile device may display in lowercase.
*f, where f is one of the preceding codes (for any quantity of the desired type of
character). Note: this can only be used once, and must be the last part of the full code.
nf, where n is a number from 0–9 and f is one of the preceding codes (for up to the
desired quantity of the desired type of character). Note: this can only be used once, and
must be the last code used.
4. If desired, type emptyok="true" if you don't want to require that the visitor enter an
answer.
5. If desired, type accesskey="n", where n is the key the visitor should type to activate the
input box.
6. If desired, type value="default", where default is the value of the input box's variable
(named in step 2) if none is entered by the visitor.
7. If desired, type type="password" to have the visitor's input hidden on screen as they
type it.
8. Type /> to complete the input box.
Figure 23.26 Note that text and input boxes must be enclosed in p tags (while
onevent elements need not be). I've set the format to 2N to allow numbers up to
99 (in other words, up to 2 digits).
<onevent type="onenterforward">
</refresh> </onevent>
</p>
</card>
Figure 23.27. Since we've already set the number variable with setvar, it has a
default value (2).
Tips
• You can require that data be entered in a particular pattern using the format
attribute. For example, you could insist on a 2 digit (and not 1 digit) number by
using format="NN" .
• The default value for emptyok is false. However, whether or not input is
required for the input box also depends on the value of the format attribute.
Creating Menus
WML pages can also include menus for offering choices to your visitors. There are a few special
features for menus.
To create menus:
Figure 23.28 Here we create a menu titled Smoking with two options, Yes or No.
<option value="no">No</option>
<option value="yes">Yes</option>
Figure 23.29. Some browsers show menus as radio buttons (above), while others
use a separate screen to give the options (right).
Figure 23.30 Two separate things are going on here. First, I've set the iname
attribute to store the index number of the chosen entree. I also set the default
entree by specifying an ivalue of 4 (which corresponds to the fourth option,
Seafood Fideua). Secondly, I've divided the menu into two subsections or option
groups to make it easier for visitors to find what they're looking for.
</optgroup>
<optgroup title="Vegetarian">
</optgroup>
</select>
Figure 23.31. The Seafood Fideua entree is chosen by default. Nokia browsers use
the optgroup element to divide menu options. Openwave browsers ignore it.
1. Create a text box (see page 384) or menu (see page 386), or set a variable yourself (see
page 383). Pay special attention to the name (or iname) attribute of the input,
select, or setvar elements, respectively. The name (or iname) attribute identifies
the variable that will contain the data.
2. In an anchor, do element or onevent, type <go href="formscript.cgi"
method="post">, where formscript.cgi is the name of the script that will process the data
from your visitors and perhaps create a response WML page from that data.
3. Next, type <postfield name="var" value="$(var)" />, where var is the value of the
name (or iname) attribute used in the input, select, or setvar elements in
step 1.
4. Repeat step 3 for each variable whose data you want to send to the server.
5. Type </go>.
6. Then close the anchor, do, or onevent element you opened in step 2.
Figure 23.32 You must use the postfield element for each variable whose value
you wish to send to the server. They must be located within a go element that
references the processing script. (The go element, in turn, must be in either a do,
anchor, or onevent element).
</optgroup> </select>
<do type="accept">
</go>
</do></p>
</card>
Figure 23.33. When the visitor activates the OK button (created with the accept-
type do element), the values of the three variables are sent to the
reserve_table.cgi script.
Figure 23.34 Here's a bit of the Perl script for processing the dinner reservations.
Note that I print out both the content headers for WML documents and the proper
DOCTYPE, as well as all of the pertinent opening and closing elements.
#!/usr/local/bin/perl
"http://www.wapforum.org/DTD/wml_1.1.xml ">
<wml><card>';
my $number = param('number');
my $smoke = param('smoke');
my $dinner_index = param('dinner_index');
Figure 23.35. The Perl script confirms the reservation for the visitor by returning a
(valid and well-formed) WML page with the appropriate information.
Tips
Figure 23.36 This template element adds a Back button to every card in the deck.
(Thing is, most browsers do that anyway.)
<?xml version="1.0"?>
"http://www.wapforum.org/DTD/wml13.dtd ">
<wml>
<template>
</template>
Tips
<?xml version="1.0"?>
"http://www.wapforum.org/DTD/wml13.dtd ">
<wml>
</head>
<template>
</template>
Figure 23.39. If someone tries to link to this page from outside the domain or path,
they get an error. (Nokia's simulator just shows an error box, but doesn't show
anything in the phone. Nevertheless, I imagine real Nokia phones do give an error
of some sort.)
• Remember that a deck's access attributes refer to the location of the page that is
trying to access the deck, not to the deck's location itself.
• If you limit access with a domain like www.mydomain.com , decks from both
domains like www.mydomain.com and mydomain.com (but not domain.com or
yourdomain.com) will be able to access the deck
• The path should begin at the root WML directory and should start with a slash. A
path like /html5ed would match decks with URLs like
http://www.cookwood.com/html5ed/ as well as http://www.
cookwood.com/html5ed/examples, but not http://www.cookwood.com/perl/html5ed/.
1. Download a software development kit (SDK) from the developer's area of the
microbrowser manufacturer you're interested in:
Nokia: http://www.forum.nokia.com/main.html
Openwave: http://developer.openwave.com/
Ericsson: http://www.ericsson.com/mobilityworld/
2. Use a syntax checker in your text editor or a validator to make sure you have written valid
and well-formed WML.
3. Open your WML page with the simulator from the SDK.
Figure 23.40. Openwave's SDK 5.0 for WAP includes all sorts of goodies, including
a simulator (right), a WML editor (left), and output and error logs (bottom).
Figure 23.41. Nokia's Mobile Internet Kit includes a simulator, editing window,
History pane, and the rather useful Variables pane, for keeping track of the value of
your variables.
• Some SDKs let you write your code in an incorporated text editor. They usually will
check and validate your code as well. The downside? They're so slow!
• Unfortunately, I have yet to see a WML SDK that runs on a Mac. I use Connectix'
Virtual PC to bridge the gap.
• Different phones have different microbrowsers. Openwave, for example, lists the
phones that use its browsers on its Web site:
http://upmkt.openwave.com/dev_phones/phones.cfm
• Or, buy a phone!
Between HTML, XHTML, CSS and the multitude of browsers and platforms on which you can
view them, it's easy to have a bit of trouble. This chapter will alert you to some common errors,
and will also help you weed out your own homegrown variety.
Once your code is correct, you should then thoroughly test your site to see if each page works the
way you want it to.
Figure 24.1. That text to the right of the image isn't supposed to be so big. What's
the problem?
• Validators have a hard time getting the big picture. While they're good at noticing
missing closing tags or missing quotes, they're not always so smart about what that
means in the rest of the file. For example, a missing closing tag can trigger lots of
error messages throughout your document. Fix the closing tag, and all of those
subsequent "errors" go away. The trick, then, is to fix a few errors at a time, starting
at the top of the file, and then immediately revalidate the file to see if other
problems are also resolved (Figure 24.2).
• Make sure you've spelled everything right. I can't tell you how many times I write scr
instead of src (which stands for source, by the way).
• Be careful about nesting. If you open <h2> and then use <b> make sure the closing
</b> comes before the final </h2>.
• The final / in empty XHTML tags is not part of the HTML specification. If you want the
file to validate as HTML, you'll have to get rid of it. (Better yet, switch to XHTML.)
• Make sure the DOCTYPE matches the HTML you're actually using. For example, if you
want to use deprecated tags, don't use HTML strict, use HTML transitional (see pages 38
and 60).
• Avoid non-standard tags. Their support across browsers is notoriously spotty.
• Be aware that most valid DOCTYPE declarations will make IE and Netscape go into
standards mode. If you're relying on old quirky behavior, you may be disappointed (see
page 39).
• If accented characters or special symbols are not displaying properly, see Chapter 20,
Symbols and Non-English Characters.
Figure 24.3 Can you see where the problem is? I've misspelled src. I can't tell you
how many times I've torn apart a table or some other complicated construction
only to find a miserable little typo like this.
Figure 24.4 The corrected version shows the src attribute spelled correctly, plus
I've removed the final / that is used only in XHTML, not HTML.
• Be sure all attribute values are enclosed in straight, not curly, quotes. If the value itself
contains quotes, use references (see page 340). Also note that a value can contain single
quotes if the value is enclosed in double quotes, or double quotes if the value is enclosed
in single quotes (Figures 24.5 and 24.6).
• Make sure all elements have opening and closing tags, or one combination tag (with a
final /). Always put a space before the / to ensure compatibility with older browsers.
• Don't combine opening and closing tags for elements that usually have content. For
example, while <p /> is technically correct in XHTML, browsers won't always know
what to do with it. In the same vein, don't use separate opening and closing tags for empty
elements as in <img src="woody.gif" alt="cat"> </img> . Again,
while this is perfectly valid XHTML, browsers will be confused (Figures 24.7 and 24.8).
Figure 24.7 Here are two examples of valid XHTML that will give most
browsers a headache.
<p />
<img src="jungle.jpg" alt="Llumi's jungle" >
</img>
Figure 24.8 Instead, don't combine the opening and closing tags of
elements that aren't usually empty (like p) and don't use individual opening
and closing tags for elements that are usually empty (like img).
<p></p>
<img src="jungle.jpg" alt="Llumi's jungle" />
• Be careful about case. All elements, attributes, and predefined values should be in
lowercase.
• Don't leave out the # when specifying hexadecimal colors.
• If symbols or accented characters are not displaying properly, see Chapter 20, Symbols
and Non-English Characters.
• Make sure you separate your properties from their values with a colon (:) not an equals
sign, like you do in (X)HTML (Figures 24.9 and 24.10).
p {font-size=24px}
Figure 24.10 Much better. Always use a colon between the property and the
value. Note that it doesn't matter if you add extra spaces before and after
the colon.
p {font-size: 24px}
• Be sure to complete each property-value pair with a semicolon (;). Make sure there are no
extra semicolons (Figures 24.11 and 24.12).
Figure 24.11 Bad! You must put one and only one semicolon between each
property-value pair. Here there's one missing and one extra.
Figure 24.12 One way to make sure that each property-value pair is
separated by the next with a semicolon is to give each one its own line. It's
easier to see the semicolons when they're not in a sea of properties, values,
and colons. (While a semicolon after the final property-value pair is
optional, it's a good habit to get into.)
p {
font-size: 24px;
font-weight:bold;
font-style:italic;
}
Figure 24.13 Bad! Get rid of those quotes around italic, CSS doesn't need
them.
Figure 24.14 The only CSS values that are enclosed in quotes are multi-
word font names.
• Make sure you're using an accepted value. Something like font-style: none isn't
going to work since the "none" value is called normal. You can find a complete list of
CSS properties and values in Appendix B, CSS Properties and Values.
• Don't forget the closing </style> tag with internal style sheets (see page 151).
• Make sure you've linked the (X)HTML document to the proper CSS file, and that the
URL points to the desired file. Remember that URLs are relative to the CSS file, not to
the (X)HTML, except for Netscape 4.x (see page 149).
1. Validate your (X)HTML and CSS (see page 394). Make any necessary changes.
2. Open a browser, and choose File > Open File.
3. Find the Web page on your hard disk that you want to test and click Open. The page
appears in the browser.
4. Go through the whole page and make sure it looks exactly the way you want it. For
example:
o Is the formatting like you wanted?
o Does each of your URLs point to the proper document? (You can check the
URLs by clicking them if the destination files are located in the same relative
position on the local computer.)
o Is your CSS file referenced properly?
o Do all of your images appear? Are they placed and aligned properly?
o Have you included your name and e-mail address so that your users can contact
you with comments and suggestions? (Or, to avoid spambots, have you included
a form that people can use to submit comments?)
5. Without closing the page in the browser, open the appropriate (X)HTML or CSS
document and make any necessary changes.
6. Save the changes.
7. Switch back to the browser and press Refresh or Reload to see the changes.
8. Repeat steps 1–7 until you are satisfied with your Web page. Don't get discouraged if it
takes several tries.
9. Revalidate the code to make sure you haven't introduced any new errors.
10. Upload the files to the server (see page 405).
11. Return to the browser and choose File > Open.
12. Type your page's URL and click Open. The page will appear in the browser.
13. With your page on the server, go through your page again to make sure everything is all
right.
Figure 24.15. This page validates but it doesn't look anything like it's supposed to.
What's the problem?
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<body>
</body>
</html>
Figure 24.17. Now that the link to the CSS is corrected, the page is displayed
properly.
• Again, if you can, test your (X)HTML documents in several browsers on various
platforms. You never know what browser (or computer) your visitors will use. The
major browsers are discussed on pages 15–16.
• The rest of this chapter deals with common problems that can occur in validated
code as well as their solutions.
• Sometimes it's not your fault—especially with styles. Make sure a browser supports
the feature you're having trouble with before assuming the problem is with your
code.
• Have you saved the file in Text Only (sometimes called "Text Document") format?
Sometimes, if you've saved the file previously as a, say, Word document, saving it as
Text Only isn't enough. You have to create a brand new document, copy and paste the
code to that new document, and then save it as Text Only.
• Have you saved the file with an.htm or.html extension? You must (see page 50).
• Have you begun the page with the proper DOCTYPE? (see page 60).
• Do you shun Word's (or some other word processor's) "Save as Web Page"or"Save as
HTML" command? That command, in all its incarnations, is only for converting regular
text into Word's idea of a Web page (Figures 24.18 and 24.19). If you're writing your
own code, this command will "code your code" (see page 52). Instead, choose Save As
and then save the file as Text Document with the.htm or.html extension.
Figure 24.18. This page, shown here in Internet Explorer, was created with
Word's Save as Web Page option. Since it already contained code, Word
simply makes a Web page that contains that code. I would bet it's not what
you expected.
• Is Windows adding.txt extensions to the files you save as "page.html", creating something
like "page.html.txt"? Find out by viewing file extensions in the folder. To avoid it,
enclose the file name in double quotation marks in the Save As dialog box.
• First, check that the file name of the image on the server matches the name you've
referenced in the img tag exactly, including upper- and lowercase letters, and the
extension (Figure 24.20). For more information, consult File Names on page 32.
• Don't use spaces in file names. While they make work locally (on your personal
computer), servers have a tough time with them.
• Next, make sure the path to the image on the server is reflected in the path that you've got
in the img tag. One easy test is to put an image in the same directory as the HTML page.
That means you'll just need the proper file name referenced in the img tag (but no path
information). If it shows up, you can be pretty sure that the problem with your image is
the path. For more information about paths, consult URLs on page 33.
• Have you saved the image as GIF or JPG? I've seen Windows users create images in
BMP format (which Internet Explorer for Windows has no trouble with) and then not
understand when Netscape (on Windows or Mac) displays a broken image icon instead of
the graphic. For more information, see Chapter 5, Creating Web Images.
• Have you saved the image in RGB format (as opposed to CMYK which is strictly for
printed images)?
Figure 24.21. On your computer, the page looks fine because your computer isn't
picky about upper- and lowercase letters.
When your page looks different from one browser to the next:
• Test your page on as many browsers and platforms as you can. Read your server logs to
see which browsers your visitors use and which browsers they don't so that you can make
informed choices about which browsers to focus on.
• Be aware of which CSS properties are supported by current browsers and which are the
most problematic. There are a number of good resources. Check my Web site for details.
• Design your page so that even if something you use is not supported, your page still
functions. This is called "degrading gracefully".
• Cater your page to your desired audience. Web designers can be expected to have all the
latest plug-ins, members of the American Iguana Club might not.
p {white-space:pre}
p>em {font-weight:bold}
Figure 24.25. Netscape 4.7 doesn't get border-bottom nor the first-letter
selector, though it gets float and white-space right.
Figure 24.26. Netscape 6 (for both Mac and Windows) has excellent CSS support.
You may question my esthetics (and my poetry) but this is the way the page is
supposed to look.
• Check out The Web Standards Project page (www.webstandards.org) for more
information on what you can do to promote the adoption of standards by the major
Web browser manufacturers (as well as by any newcomers to the game).
When the page looks fine in other browsers, but doesn't appear in
Netscape 4:
• If you're using tables, you must be sure to create a closing </table> tag to match each
and every opening one.
• If your page is set up with several framesets (see page 246), make sure you insert a
closing </frameset> tag for each and every opening one. I think this one is easy to
miss because you've got all those <frame> tags that don't require a closing tag.
Remember that the <frameset> tag does require a closing tag, and Netscape 4 won't
forgive you if you leave it out.
• If the problem is that the page looks great in Explorer but cruddy in Netscape 4 (as
opposed to nothing in Netscape 4), check Differences from Browser to Browser on page
402.
• Note that the closing </table> and </frameset> tags are always required and
should always be used.
• Only Netscape 4 (and earlier) is this picky about the closing tags.
<tr><th colspan="2">
</th></tr>
<tr>
</tr></body></html>
Figure 24.29. Netscape 4, on the other hand, is very strict. The entire table (or
frameset) disappears from view.
Still Stuck?
1. Check again for typos. Revalidate your code (see page 394).
2. Check the easy pieces first. So many times I've spent hours fiddling with an exciting new
tag that just wouldn't work only to find that the problem was a typo in some tag that I'd
used a thousand times before. Familiarity breeds contempt—check the stuff you think you
know really well before you harass the newcomers.
3. Simplify the problem. Go back to the most recent version of your page that worked
properly (which might be a blank page in some cases). Then test the page after adding
each new element.
4. Read through this chapter again.
5. Check one final time for typos.
6. Post the piece of code that doesn't work on my Question and Answer board
(www.cookwood.com/html/qanda/). Be sure to include the relevant code (or a URL), a
description of what is happening and a description of what you think should be
happening.
7. If you're at the end of your rope, write me directly at [email protected]. But
please note that I get a lot of e-mail and while I have the best intentions, I'm sometimes
too swamped to answer. I'm much more inclined to try if you assure me you've tried
everything else first.
Figure 24.30. If you get stuck, try posting a question to my HTML Question and
Answer board (http://www.cookwood.com/html/qanda/)
You may also want to contact your Web host (or Internet Service Provider) to ask them about the
best way to upload your files.
Be sure to thoroughly test your pages before publishing them. For more details, consult Chapter
24, Testing and Debugging Web Pages.
When considering a host, there are a number of things—besides price—to keep in mind.
• How much disk space will they let you have for your Web site? Don't pay for more than
you need. Remember that HTML files take up very little space while images, sounds, and
videos take up successively larger quantities.
• Do they offer technical support? If so, is it by telephone or by e-mail? How long will it
take them to get back to you?
• Will they register a domain name (see page 407) for you? How much will they charge?
• How fast is their connection to the Internet? This will determine how fast your pages are
served to your visitors. Do they have multiple connections in case one of them should
become inoperable?
• Do they include dial-up access to the Internet? (They don't usually.) Will they if you need
it?
• Will they let you run custom CGI scripts, Server Side Includes, FrontPage extensions,
RealAudio, Telnet/SSh, PHP, MySQL, and other advanced features?
• Do they offer a Web hit statistics service to let you know how many people have been
visiting your site?
However, if you don't want your Web host's server name to appear in your Web page's URL, you
can register your own domain name (for a fee, always for a fee) and then ask your Web hosting
company to create a virtual domain on their server with your domain name. In my case, while my
pages are still on Crocker's server, they look like they're on my own server: www.cookwood.com.
Even if your visitors don't know about servers and where the files actually reside, having your
own domain name makes your URLs simpler and easier to type, and thus easier to visit.
Figure 25.1. Verisign (which bought Network Solutions in 2000) is one of the
accredited registrars of domain names. You can use their site to see if a desired
domain name is available.
Figure 25.2. If the name is available, you can either register it through Verisign or
call your Web host and get them to do it for you. (Now you know: the very useful
www.catalancats.com domain can be yours!)
1. In the Connect to Remote Host window (which appears upon launching WS_FTP Pro),
click Create Site (Figure 25.3).
Figure 25.3. In the Connect to Remote Host window, click Create Site to set
up your account. (If this window doesn't appear, click Connect in the main
window.)
Figure 25.4. Insert the appropriate information in each screen and then click
Next to continue. Click Finish when you're done. Note that it doesn't matter
what you name the site. You enter the proper FTP name in the Host
Name/Address field (which appears after you click Next).
Figure 25.5. Add the .htm, .html, and .css extensions to the list so that
(X)HTML files will be transferred in ASCII mode. (Images and other
multimedia files should be transferred as Binary.)
Figure 25.6. In WS_FTP's main window, click Connect. Then choose your
site (that you set up on page page 408) in the Connect to Remote Host
window.
3. Choose your site in the list and click Connect. The server is accessed.
4. On the right side of the window, navigate to the directory on the server to which you want
to upload files (Figure 25.7).
Figure 25.7. In the left frame, select the files from your hard disk that you
want to upload. In the right frame, select the destination directory on the
server. Then click the right-pointing arrow to transfer the files.
Figure 25.8. The newly transferred files appear in the right frame. Notice the
status messages in the lower-left portion of the window.
Tips
• (X)HTML, CSS, CGI, and JavaScript files should be transferred in ASCII mode.
All other files, including images, sounds, and videos should be transferred in Binary
mode. The Auto button means that any file with an extension not listed in the
Extensions tab (Figure 25.5) will be transferred in Binary mode.
• You can create a new directory by clicking the MkDir button.
• You can find WS_FTP's home page at www.ipswitch.com/products/ws_ftp/.
• There are many other file transfer programs for Windows besides WS_FTP. Do a
search at CNET's shareware site (www.shareware.com) if you'd prefer to use some
other program.
Fetch is the leading FTP client for Macintosh. There's an excellent new version available for OS
X.
To transfer HTML files to the server with Fetch (for the Mac):
Figure 25.10. Click the Upload tab and make sure that the Add .txt suffix
option is unchecked.
Figure 25.11. In the New Connection window, type the server name (Host),
your User ID and password, and the directory where you want to transfer
the files.
Figure 25.12. Make sure the proper directory on the server (where you want
to transfer the files) is showing in the Fetch window before transferring the
files (in this case, debugging).
Figure 25.13. Click the Put Files button (or choose Command-T).
10. In the dialog box that appears, choose the files that you wish to transfer to the server.
Select multiple files holding down the Shift key. Select multiple non-contiguous files
Figure 25.14. Select the desired file or folder. (In Mac OSX, you can select
more than one by holding down the Shift or Command key.) Then click
Choose.
11. In the Put File dialog box that appears, confirm the appropriate file names and formats for
the files. The Automatic format correctly uses the Text format for (X)HTML and other
text documents and Raw Data for other files (Figure 25.15).
Figure 25.15. Confirm the file name and format for the desired files.
12. Click OK. The files are transferred to the server and maintain the hierarchy they had on
the local system (Figure 25.16).
Figure 25.16. The chosen files are uploaded to the current directory.
• (X)HTML, CSS, CGI, and JavaScript files should always be transferred as Text (in
ASCII mode). Any other file, including images, sound, and video, should be
transferred as Raw Data.
• Fetch used to belong to Dartmouth University but was bought back by its principal
engineer, Jim Matthews (thanks to winnings from a stint on the television show,
Who Wants to Be a Millionaire?). You can find Fetch's great new Web site,
complete with upgrades, documentation and support at http://fetchsoftworks.com.
• You can resize the main window so that it shows more files at one time. Just click
and drag the bottom-right corner.
• Relative URLs (see page 35) are maintained when you transfer a folder to the
server. Absolute URLs (see page 34), must be updated to reflect the files' new
locations.
• By default, Fetch converts characters from the default MacRoman to ISO-8859-1. If
you've saved your document as anything other than MacRoman (see pages 50 and
336), you'll want to turn this feature off (Customize > Preferences > Misc and then
uncheck Translate ISO Characters). If you do use this feature, your files' meta tags
should specify the ISO 8859-1 character set, not MacRoman (see page 339).
1. Go to keyword myftpspace.
2. In the window that appears, click the See My FTP Space button (Figure 25.17).
Figure 25.17. Click See My FTP Space to get to the FTP Upload area.
Figure 25.19. If you click the Create Directory button, AOL will allow you to
name the new directory.
Figure 25.20. Once you're in the desired directory, click the Upload button
at the bottom of the screen.
5. Under Remote Filename in the window that appears, type the exact name and extension
that the file should have on the AOL server. (The path appears just above "Remote
Filename". To change the path, navigate to a different directory in step 3.)
6. Click ASCII for text documents (including XHTML, HTML, CSS, and scripting files),
and Binary for everything else.
7. Finally, click Continue (Figure 25.21).
Figure 25.21. Type the file name and extension (but not the directory) that
the file should have on the AOL server, choose ASCII or Binary, depending
on the nature of the file, and then click Continue.
8. In the Upload File dialog box that appears, click Select File (Figure 25.22), and then
choose the desired file from your hard disk and click OK.
9. The Upload File dialog box returns with the selected file listed in the File box. Click Send
to upload the file (Figure 25.23).
Figure 25.23. The selected file is listed in the File box at the bottom of the
screen. Click Send to upload the file to AOL.
Tips
Figure 25.24. The chosen file is uploaded to the current directory with the name
specified in the Remote Filename box. This particular file will now be accessible at:
http://members.aol.com/lizcastro/cats/catpage.html (until I cancel my AOL
account).
There are a number of good resources on the Web for improving one's ranking in search engines.
For this chapter, I am indebted to two excellent WebMonkey articles written by Paul Boutin
(hotwired.lycos.com/webmonkey/01/23/index1a.html and
www.hotwired.com/webmonkey/99/31/index1a.html) and to the site put together at
searchenginewatch.com by Danny Sullivan.
There are several search engine optimization companies who would like to charge you for
completing the steps I outline in this chapter —while making big promises about search engine
results. Unfortunately, some of them go too far and spend much too much energy (not to mention
your money) trying to trick visitors into coming to your site (or trying to trick search engines into
listing your site). Their slimy techniques, apart from annoying potential visitors, can even get you
removed from some search engines. If you have real (non-pornographic, non-gambling) content
on your site, you can do just as good or better without them.
About Keywords
When prospective visitors go to a search engine to find information, they type a few identifying
keywords that describe what they're looking for. The more those words are honestly reflected on
your page, the better your chances are that your page will appear in a search engine's results. So,
it's a good idea to think about what your page is about, decide on some keywords that describe
your page (and that might be used to find it), and then use your keywords consistently.
Do
But...
• Don't create headers out of GIF images if they contain keywords since search engines
cannot understand the text in an image. At the very least, add keywords to such an
image's alt tag (see page 105).
• Don't use keywords where they don't make sense. It is their natural and consistent use
which is rewarded.
• Don't repeat keywords endlessly and meaninglessly, perhaps in a small font or with the
same color as the background. This is called spamming and can get you banned from a
search engine's results.
Figure 26.1 In this document, I've used the keywords Barcelona and market in the
title, headers, alternate text for images, and in the first paragraph. Try searching
for Barcelona market on Google.
<title>Barcelona's Market</title>
</head>
<body>
<h1>Barcelona's Market</h1>
Figure 26.2. Use keywords as consistently and naturally as you can. If you do it
right, there's no reason to cheat.
Figure 26.3 If you want to be absolutely sure that a search engine knows what your
page is about, you can specify the keywords with a meta tag.
</head>
<body>
<h1>Barcelona's Market</h1>
Tips
Figure 26.4 You can offer search engines a concise description of your site.
<title>Barcelona's Market</title>
</head>
<body>
Figure 26.5. Instead of using the first few lines of the page, or showing where the
keywords appeared, MSN uses the description given in the meta tag.
• When a visitor sees a list of links that match their keywords, the description of your
page may help it outshine the competition. Be careful to describe your page
succinctly and descriptively. Avoid generic marketing hype in favor of specific
features that set your site apart from the rest.
• AltaVista limits the length of the description to 1024 characters.
• If your page is set up with frames, be sure to include a description in every frame
page, as well as the frameset itself.
• Google does not pay any attention to the description you include with the meta
tag. Instead, it shows visitors the specified keywords in the context of the matching
pages.
1. In the head section of your Web page, type <meta name="author" content= "name"
/>, where name is the person who wrote the (X)HTML page.
2. In the head section of your Web page, type <meta name="generator"
content="program" />, where program is the name of the software that created (or
edited) the (X)HTML page.
3. In the head section of your Web page, type <meta name="copyright"
content="© year holder" />, where year is the calendar year of the copyright, and
holder is the name of the person or entity who holds the copyright to the page.
<title>Barcelona's Market</title>
<body>
<h1>Barcelona's Market</h1>
• The generator is created automatically by most Web page editors. You can delete it
if you prefer not to give them credit.
• If you browse a page with Internet Explorer 5 for Windows and then save the
source to your hard disk, Explorer will actually add meta information to the
file, claiming to be its generator. (For more information on saving the source
code from a page on the Web, consult The Inspiration of Others on page 57.)
Figure 26.8 When a search engine's robot encounters this page, it will ignore both
the page and the page's links.
<head>
<title>Untitled</title>
</head>
</html>
Tips
In the head section of your page, type <meta name="robots" content="noarchive" />.
Figure 26.10 When a search engine's robot encounters this page, it will continue to
index the page, but it won't archive it (and thus won't be able to offer a cached
version should your page (or server) be unavailable).
</head>
<body>
</body>
</html>
Tip
• Presently, Google is the most important search engine that archives Web pages. If
you'd like to keep only Google from archiving your pages, you can specify
googlebot instead of robots as the value of the name attribute above.
Figure 26.11. In the Organize Favorites dialog box, click Create Folder and
give the new folder a name. Then click Close.
Figure 26.12. After choosing Add to Favorites, select the crawler page
folder in which the link should be added.
8. When you've added all the desired pages, choose File > Import and Export.
9. Use the Wizard to create an HTML file of your crawler page favorites folder (Figure
26.13).
2. Click the New Folder button in the Bookmarks window to create a new folder to hold the
bookmarks for your most important pages (Figure 26.15).
Figure 26.15. Once the Bookmarks window is open and active, click the
New Folder button.
3. Select the new folder in the Bookmarks window and choose View > Set as New
Bookmarks Folder so that all new bookmarks will be automatically added to this folder.
4. Close the Bookmarks window.
5. Navigate to the important pages on your site that you want to be sure the search engine
finds.
Figure 26.16. Once you've created bookmarks for all the important pages on
your site, choose File > Export Bookmarks to save the bookmarks file as an
HTML file.
9. Open the bookmarks file and delete everything except the links to the important pages on
your site.
10. Continue with step 10 on page 422.
Figure 26.17. A crawler page should contain links to all of the pages on a site that
you want indexed by a search engine.
Tips
Figure 26.18. Go to the search engine's Add URL page. This is Google. You
can add comments about your page, though they are not used in the search
results.
Yahoo's is at http://docs.yahoo.com/info/suggest/
4. Type your (crawler) page's URL in the appropriate text box and click the Submit button.
5. Go back to the search engine in two weeks and search for your site. If it doesn't appear,
submit it again.
• The most popular general search engines are Google and Yahoo. Also see
http://www.useit.com/about/searchreferrals.html.
• You might also want to register your site with a search engine that specializes in a
particular topic. So, if your page is about Star Trek, you might want to register it
with http://www.treksearch.com. Yahoo has a very complete list of specific topic
search engines.
• Ask sites with similar content if they would link to your site.
• Join Web rings of sites with similar content.
• Offer to exchange links with sites of similar content.
• Make sure to submit your site to major as well as specific search engines.
Tips
• Don't create bogus domains and then link to your page from there. Search engines
can spot this scam from a mile away.
• Links from authoritative sites of the same topic are more valuable than links from
less authoritative or more generic sites.
• You can find out who links to you by typing link:yourdomain.com in Google.
• Note that the wording of the link and the keywords on the originating page can be
almost as important in determining how and whether a page gets listed as the
keywords on the page itself. (For more details, do a search for googlebombing.)
Frames
While frames can be useful for showing more than one page at a time (see page 241), this
flexibility can also keep them from getting indexed by search engines. Some search engines will
ignore a frameset's frames in favor of its alternate content (as marked by the noframe tag). And
if they do index an individual frame, search engines often give the individual frame as a result,
which may or may not make sense without the enclosing frameset (Figures 26.19, 26.20, and
26.21).
Figure 26.19. So inspired by the endless Catalan examples in this book, you go
searching for Catalan grammar and vocabulary at Google and find this page.
Figure 26.21. You might never see the rest of the site. The person who designed
this frame-based site (yes, it was me) should have given you a way to get to the
frameset from the individual frame (or used JavaScript, see page 327).
Some search engines don't know what to do with image maps and ignore them altogether. Any
linked pages may thus not get indexed. It's always a good idea to repeat the links from an image
map as text, both for search engines and for visitors who cannot use images.
While you can create fancy, customized effects by dynamically creating pages based on
information you've collected from your visitors, these pages are hard for search engines to deal
with. On the one hand, they may be suspicious that you're trying to serve different versions to
search engines than you are to regular visitors (a big no-no that can also get your page removed
from a search engine). On the other hand, the page is a moving target; there's no place to link to
once a prospective visitor says they're interested in going back. At the very least, use URLs that
search engines can digest, preferably without ? or & (as may appear in CGI instructions).
• Add your URL to your signature so that it will be included in all outgoing e-mail.
• Answer questions or post information on a related newsgroup and make sure your URL is
prominently included in your signature. (On the other hand, it's also considered good
form to keep your signature relatively brief and humble.)
• Post a note in the moderated newsgroup comp.infosystems.www.announce or the in the
unmoderated comp.internet. nethappenings. (The hyphen is part of the address.)
• Join a Web ring. A Web ring is a group of related Web sites that have links that go from
one site to the next. Web rings encourage visitors from one site to explore related ones.
You can search for pertinent Web rings at Yahoo.
Figure 26.22. Adding your page to my gallery is just one of a number of techniques
you can use to get people to come visit your site.
On the following pages, you'll find a list of the (X)HTML elements and attributes described in this
book. In the "Vers." or version column, I've used a D to mark elements or attributes that have been
deprecated (and thus not allowed in strict), and an F to mark elements and attributes that are only
allowed in the frameset flavor. Thus, only elements with no code in the version column may be
used in strict (X)HTML. You should use a DOCTYPE that corresponds to the elements used in
your Web page (see pages 38 and 60).
Proprietary tags are marked with an N if only recognized by Netscape, an IE if only recognized by
Internet Explorer, or with N+IE if supported by both. You should omit the DOCTYPE when using
proprietary tags, since they are not valid in any DTD.
[*]
the embed element, while non-standard, used to be universally accepted. Internet Explorer 5.5+ for
Windows no longer supports it.
[*]
Although not formally described as deprecated, the iframe element (and its associated attributes) are
not part of (X)HTML strict. Call it what you will, but use them only in transitional flavor (X)HTML.
Find extra tips, the source code for examples, and more at www.cookwood.com
I have included the table on the next page to give you a quick reference to each of the properties
and its allowed values. I have also indicated each property's default or initial value, the elements
to which it may be applied, whether or not the property is inherited, and what percentages refer to
if they may be used. Finally, I have referenced the page number in the book where the property or
value is discussed.
Many of the properties accept a length, percentage, or color for values. For more details on
entering values, consult A Property's Value on page 44.
any combination of a single value each for initial value depends on individual values; not
one color or inherit initial value: the value of the color property; not
inherited
For defining just the border's style on only one
side of an element (p. 186)
initial value: none; not inherited
border-top-style, border-right-style,
border-bottom-style, border-left-style
font-family for choosing the font family for text (p. 158)
one or more quotation markenclosed font initial value: depends on browser; inherited
names followed by an optional generic font
name, or use inherit
font-size for setting the size of text (p. 162)
an absolute size, a relative size, a length, a initial value: medium; the computed value is
percentage, or inherit inherited; percentages refer to parent element's
font size
font-style for making text italic (p. 160)
either a length, percentage, auto, or initial value: auto; may be applied to all
inherit elements except non-replaced inline elements,
table columns, and column groups; not inherited
left for setting the distance that an element should be
offset from its parent element's left edge (pp. 179,
either a length, percentage, auto, or 180, 181) initial value: auto; may only be
inherit applied to positioned elements; not inherited;
percentages refer to width of containing block
letter-spacing for setting the amount of space between letters (p.
168)
either normal, a length, or inherit
initial value: normal; inherited
line-height for setting the amount of space between lines of
text (p. 164)
either normal, a number, a length, a
percentage, or inherit initial value:normal; inherited; percentages
refer to the font size of the element itself
list-style for setting a list's marker (regular or custom) and
its position (p. 210)
any combination of the values for list-style-
type, list-style-position and/or list-style- initial value depends on initial values of
image, or use inherit individual elements; may only be applied to list
elements; inherited
list-style-image for designating a custom marker for a list (p. 208)
either a URL, none, or inherit initial value: none; may only be applied to list
elements; overrides list-style-type ;
inherited
list-style-position for determining the position of a list's marker (p.
209)
either inside, outside, or inherit
initial value: outside ; may only be applied to
list elements; inherited
list-style-type for setting a list's marker (p. 206)
either disc, circle, square, initial value: disc; may only be applied to list
decimal, lower-roman , elements; not used if list-style-type is
upperroman, lower-alpha , valid; inherited
upper-alpha , none, or inherit
margin for setting the amount of space between one or
more sides of an element's border and its parent
one to four of the following: length, element (pp. 189, 201)
percentage, or auto, or inherit
initial value depends on browser and on value of
either a length, percentage, or inherit initial value: 0; not inherited; percentages refer to
width of containing block
page for specifying on which kind of page an element
should be printed (p. 202)
either a page area's name or auto
initial value: auto; may only be applied to
block-level elements; inherited; names are defined
with @page rule
page-break-after, page-break-before for specifying when page breaks should or should
not occur (p. 200)
either always, avoid, auto, right,
left, or inherit initial value: auto; may only be applied to
block-level elements; not inherited
page-break-inside for keeping page breaks from dividing an element
across pages (p. 200)
either avoid, auto, or inherit
initial value: auto; may only be applied to
block-level elements; inherited
position for determining how an element should be
positioned with respect to the document's flow
either static, relative, absolute, (pp. 179, 180, 181)
fixed, or inherit
initial value: static; may not be applied to
generated content; not inherited
right for setting the distance that an element should be
offset from its parent element's right edge (pp.
either a length, percentage, auto, or 179, 180, 181)
inherit
initial value: auto; may only be applied to
positioned elements; not inherited; percentages
refer to width of containing block
size for determining the size of the printing area in a
defined page (p. 201)
either individual lengths for width and height,
a single value for both width and height, initial value: auto; may only be used within an
landscape , portrait, auto, or @page rule
inherit.
table-display for choosing the algorithm that should be used to
determine the widths of cells (p. 240)
one of fixed, auto, or inherit
initial value: auto; not inherited
text-align for aligning text (p. 171)
either baseline, sub, super, top, initial value:baseline ; may only be applied to
text-top, middle, bottom, inline-level and table cell elements; not inherited;
textbottom, a percentage, a length, or percentages refer to the element's line-height
inherit property
either a length, percentage, auto, or initial value: auto; may not be applied to non-
inherit replaced inline elements, table rows, or row
groups; not inherited; percentages refer to width
of containing block
word-spacing for setting the distance between words (p. 168)
Intrinsic Events
EVENT WORKS WITH WHEN
onblur a, area, button, input, label, the visitor leaves an element
select, textarea that was previously in focus
(see onfocus below)
onchange input, select, textarea the visitor modifies the value
or contents of the element
onclick All elements except applet, base, the visitor clicks on the
basefont, br, font, frame, frameset, specified area
head, html, iframe, meta, param,
script, style, title
ondblclick Same as for onclick the visitor double clicks the
specified area
onfocus a, area, button, input, label, the visitor selects, clicks, or
select, textarea tabs to the specified element
onkeydown input (of type name or password), the visitor types something in
textarea the specified element
onkeypress input (of type name or password), the visitor types something in
textarea the specified element
onkeyup input (of type name or password), the visitor lets go of the key
textarea after typing in the specified
element
Since there are more than 65,000 characters in Unicode, printing out each one's numeric or
hexadecimal reference would require a book of its own, and be rather unwieldy to boot. Instead,
you can consult Unicode's site, (www.unicode.org) where the characters are neatly divided by
language and theme.
I can, however, provide you with a list of the 252 named references (officially called character
entity references, but also known as entity references or named entity references) that can be used
in (X)HTML. You'll find the complete tables in this appendix, as well as on my Web site:
www.cookwood.com/entities/. I have included the equivalent numeric codes for your reference.
They are divided into categories that I hope will help make them easier to find. (Perhaps the
easiest way to find the desired symbol is to go to the Web page cited above and use the Find
command.)
Note that the tables were generated with a browser, for authenticity's sake, and thus appear slightly
more pixelated than regular text in this book.
Find extra tips, the source code for examples, and more at www.cookwood.com
Punctuation characters
Find extra tips, the source code for examples, and more at www.cookwood.com
In the hexadecimal system, which is base 16, there are sixteen symbols: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
a, b, c, d, e, and f. To represent numbers greater than f (which in base 10 we understand as 15), we
again use a combination of symbols. This time the first digit specifies how many ones, but the
second digit (again, to the left) specifies how many sixteens. Thus, 10 in the hexadecimal system
means one sixteen and no ones. In the base 10 system, it'd be 16.
In (X)HTML and CSS, hexadecimal numbers are used to define colors (see page 46) and to insert
symbols (see page 340). While you can convert hexadecimal numbers by hand, I've also included
a table to help you quickly look up a number's hexadecimal equivalent.
Figure E.1. Hexadecimal numbers are base 16, that is the first digit (starting on the
right) represents the ones, the second digit represents the 16's, the third digit
represents the 256's, and so on.
Hexadecimal Equivalents
So, to use this chart, imagine you want to find the hex value for a color with 35% red, 0% green,
and 50% blue. The percentages are relative to 255, so 35% x 255 = 89. Now, find the hexadecimal
equivalent of 89, near the bottom of the third column above. So for red, we have 59. Green is
easy; 0 = 00. For blue, we again have to multiply the percentage by 255 to get the numerical value.
50% x 255 is 127 (more or less). Then find the hex value for 127, at the very bottom of the fourth
column. So, the blue is 7F. The final step is to write it all together: #59007F, which will get us a
fine dark purple, precisely 35% red, 0% green, and 50% blue.
(X)HTML Editors
You can use any text editor to write (X)HTML, including SimpleText or TeachText on the
Macintosh, WordPad for Windows, or vi in Unix systems. The (X)HTML code produced with
these simpler programs is no different from the (X)HTML produced by more complex (X)HTML
editors.
A simple text editor is like the most basic SLR 35 mm camera. You have to set your f-stop and
aperture manually, and then focus before shooting. The dedicated (X)HTML editors are point-and-
shoot cameras: just aim and fire, for a price. They are more expensive, and generally less flexible.
• they insert opening and closing tags with • they don't all support the full
a single click (X)HTML or CSS specs 100%
• they check and verify syntax in your • they are more difficult to learn, and
(X)HTML and CSS less intuitive than they promise
• they allow you to add attributes by • they cost money (all simple text
clicking buttons instead of typing words editors are included free with their
in a certain order in a certain place in the respective system software)
document • they use up more space on disk and
• they offer varying degrees of more memory
WYSIWYG display of your Web page • some add proprietary information
• they correct mistakes in existing (like their name, for example), and
(X)HTML pages tags to the (X)HTML document
• they make it easy to use special • some eliminate tags that they don't
characters understand—even if the tags are part
• they color code elements, attributes, and of the standard (X)HTML
values, making them easy to edit specifications
(X)HTML Editors
WYSIWYG
Macromedia $400. Probably the http://www.macromedia.com/software/dreamweaver.com/
Dreamweaver most popular editor demo available
(M, W) among Web
professionals.
Adobe $400. Formerly http://www.adobe.com/prodindex/golive/main.html.com
GoLive (M, GoLive Cyber- demo available
W) Studio.
Dreamweaver's
WYSIWYG
main competition.
Text Based
BBEdit (M) $120. Excellent http://www.barebones.com demo available
HTML editor from
Bare Bones
Software. The most
popular non-
WYSIWYG
HTML editor.
Find extra tips, the source code for examples, and more at www.cookwood.com
Graphics Tools
Name Description URL
Adobe Photoshop $600. Excellent, http://www.adobe.com/prodindex/photoshop/main.html
(M, W) all-purpose image demo available
editing program.
Version 7 includes
Image-Ready,
Adobe's Web
graphics program
Adobe Photoshop $100. A http://www.adobe.com/products/photoshopel/main.html
Elements (M, W) remarkably robust,
consumer-end
version of the
excellent Adobe
Photoshop
Macromedia $300. A specialized http://www.macromedia.com/software/fireworks/ demo
Fireworks graphics program available
for creating Web
images
Macromedia Flash $500. Designed for http://www.macromedia.com/software/flash/ demo
creating Web available
animations.
Paint Shop Pro $100. Jasc http://www.jasc.com/products/psp/ demo available
(W) Software. Powerful
image editing
program for
Windows.
Commercial and
shareware versions
available. Supports
JPEG, PNG, GIF.
GraphicConverter $35. Thorsten http://www.graphicconverter.net/ demo available
(M) Lemke's image
editor for
Macintosh. Reads
and writes an
incredible array of
graphics formats,