XHTML & Css Tutorials
XHTML & Css Tutorials
SPECIAL THANKS TO: ..................................................................................................................... 7 INTRODUCTION .............................................................................................................................. 7 The Internet, the Web, and HTML......................................................................................... 8 Open but Not Equal ................................................................................................................ 8 The Browser Wars .................................................................................................................. 9 The Push for Standards ......................................................................................................... 9 The Real World ..................................................................................................................... 10 What Should You Use?........................................................................................................ 11 How This Book Works .......................................................................................................... 11 The HTML VQS Web Site .................................................................................................... 12 CHAPTER 1. W EB PAGE BUILDING BLOCKS ................................................................................. 13 Markup: Elements, Attributes, and Values.......................................................................... 13 A Web Page's Text Content................................................................................................. 17 Links, Images, and Other Non-Text Content...................................................................... 19 File Names ............................................................................................................................ 20 URLs...................................................................................................................................... 21 HTML vs XHTML .................................................................................................................. 26 Versions, flavors, and DOCTYPE ....................................................................................... 28 The Default Display of (X)HTML.......................................................................................... 31 Adding Style to Your Web Pages ........................................................................................ 33 The Cascade: When Rules Collide ..................................................................................... 34 A Property's Value ................................................................................................................ 37 CHAPTER 2. W ORKING W ITH W EB PAGE FILES ........................................................................... 41 Designing Your Site.............................................................................................................. 41 Creating a New Web Page .................................................................................................. 43 Saving Your Web Page........................................................................................................ 44 About Microsoft Word and Web Pages............................................................................... 47 Specifying a Default or "Home" Page ................................................................................. 49 Editing Web Pages ............................................................................................................... 50 Organizing Files .................................................................................................................... 52 Viewing Your Page in a Browser......................................................................................... 53 The Inspiration of Others...................................................................................................... 55 CHAPTER 3. BASIC (X)HTML STRUCTURE .................................................................................. 59 Starting Your Web Page ...................................................................................................... 59 Creating the Foundation....................................................................................................... 60 Declaring the Encoding ........................................................................................................ 61 Creating a Title...................................................................................................................... 63 Creating Section Headers.................................................................................................... 65 Starting a New Paragraph.................................................................................................... 66 Naming Elements ................................................................................................................. 67 Breaking up a Page into Divisions....................................................................................... 68 Creating Inline Spans ........................................................................................................... 70 Creating a Line Break........................................................................................................... 71 Adding Comments ................................................................................................................ 73 Labeling Elements in a Web Page ...................................................................................... 74 CHAPTER 4. BASIC (X)HTML FORMATTING ................................................................................. 76 Making Text Bold or Italic..................................................................................................... 76 Changing the Size of Text.................................................................................................... 78 Using a Monospaced Font................................................................................................... 80 Using Preformatted Text ...................................................................................................... 81 Quoting Text ......................................................................................................................... 83 Creating Superscripts and Subscripts................................................................................. 86 Marking Changed Text......................................................................................................... 88 Explaining Abbreviations...................................................................................................... 89 CHAPTER 5. CREATING W EB IMAGES .......................................................................................... 92 About Images for the Web ................................................................................................... 92 Getting Images ..................................................................................................................... 98 The Save for Web Command .............................................................................................. 99
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
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.
Page 8 of 654
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.
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/
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
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.
Page 12 of 654
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.
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
An element can be block-level or inline. If it is block-level, it will always be displayed on a new line, like a new paragraph in a book; if it is inline, it will be displayed in the current line, like the next word in a paragraph. 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.
[View full width]
<div>< img src="blueflax.jpg" alt="Blue Flax (Linum lewisii)" width="300" height="175" /> <p> I am continually amazed at the beautiful, delicate Blue Flax that somehow took hold in my garden. They are awash in color every morning, yet not a single flower remains by the afternoon. They are the very definition of <em>ephemeral</em>.</p> <p>© 2002 by Blue Flax Society. </p> </div>
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.
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.
<div><img src="blueflax.jpg" alt="Blue Flax (Linum lewisii)" width="300" height="175" /> <p>I am continually amazed at the beautiful, delicate Blue Flax that somehow took hold in my garden . They are awash in color every morning, yet not a single flower remains by the afternoon . They are the very definition of <em>ephemeral</em>.</p> <p>© 2002 by Blue Flax Society .</p> </div>
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 Unicodeencoded 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
<div><img src=" blueflax.jpg " alt="Blue Flax (Linum lewisii)" width="300" height="175" /> <p>I am continually amazed at the beautiful, delicate Blue Flax that somehow took hold in my garden. They are awash in color every morning, yet not a single flower remains by the afternoon. They are the very definition of <em>ephemeral</em>.</p> <p>© 2002 by Blue Flax Society.</p> </div>
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.
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 index.html image.gif data.html Absolute URL (can be used anywhere) www.site.com/web/index.html www.site.com/web/images/image.gif www.site.com/info/data.html Relative URL (only works in youarehere.html) index.html images/image.gif ../info/data.html (none: use absolute) (none: use absolute)
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
<p>I am continually amazed at the beautiful, delicate Blue Flax that somehow took hold in my garden. They are awash in color every morning, yet not a single flower remains by the afternoon. They are the very definition of <em>ephemeral </em>. <p>© 2002 by Blue Flax Society.
Figure 1.28 In XHTML, all elements must have closing tags.
[View full width]
<p>I am continually amazed at the beautiful, delicate Blue Flax that somehow took hold in my garden. They are awash in color every morning, yet not a single flower remains by the afternoon. They are the very definition of <em>ephemeral </em>.</p> <p>© 2002 by Blue Flax Society. </p>
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).
<img src= blueflax.jpg alt="Blue Flax (Linum lewisii)" width=300 height=175 align=left>
Figure 1.32 In XHTML, all attribute values must always be enclosed in quotes.
[View full width]
<img src= "blueflax.jpg" alt="Blue Flax (Linum lewisii)" width="300" height="175" align= "left" />
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.
<img src="blueflax.jpg" alt="Blue Flax (Linum lewisii)" width="300" height="175" align ="left" />
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
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1 -transitional.dtd ">
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.
body {background:url(bg_flax.jpg) bottom right norepeat} p {font-family: "Trebuchet MS", "Helvetica", sansserif; font-weight: bold; color:3366cc; } img {float:left;margin-right:10px}
Page 29 of 654
Figure 1.39. If you omit the DOCTYPE, Explorer continues to act in its nonstandard, 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
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.
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.
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.
body {background:url(bg_flax.jpg) bottom right no-repeat} p {font-family: "Trebuchet MS", "Helvetica", sansserif; font-weight: bold; color:#3366cc; } img {float:left;margin-right:10px}
Figure 1.46 The em element is contained within the p element, and thus is a child of
p.
[View full width]
<p>I am continually amazed at the beautiful, delicate Blue Flax that somehow took hold in my garden. They are awash in color every morning, yet not a single flower remains by the afternoon. They are the very definition of <em>ephemeral</em> .</p> <p>© 2002 by Blue Flax Society.</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>Here's a generic p element. It will be red. </p> <p class="group"> Here's a group-class p element. There are two rules that apply, but since the p.group rule is more specific, this paragraph will be blue.</p> <p class="group" id="one"> Here's a p element with an id of one. There are four rules that could apply to this paragraph. The first two are overruled by the more specific last two. The position breaks the tie between the last two: the one that appears later wins, and thus this paragraph will be magenta. </p>
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.
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 other value (Figure 1.53). work much like ems, in that they are relative to some
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. Figure 1.55. URLs in CSS properties do not need to be enclosed in quotation marks.
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
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
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.
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).
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
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. These instructions cover Word 2000 for Windows. Other versions may have slightly different wording or dialog boxes.
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) . Figure 2.17. In Windows, you can also right-click the document's icon and then choose Edit in the pop-up menu that appears. (Note that the default browser here appears to be Netscape, given the Web page's icon.)
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.
Figure 2.19. In Windows, from the desktop or the Windows Explorer, choose File > New > Folder.
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.
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). Figure 2.22. On Windows machines, you'll get an intermediary box asking if you want to type the path in by hand. If you don't (!), click the Choose File button (in IE, it's Browse). You'll get the dialog box shown in Figure 2.23.
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 o o o You can (usually) also double-click a Web page's icon to view it in a browser. 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). 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. 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.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 popup 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
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). 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
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "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. 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. Create a template with the appropriate DOCTYPE declaration and html tag as a starting point for all your pages. 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). 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). 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) . Declaring the appropriate DOCTYPE tells validators which specifications to compare your code against (see page 394). 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.
o o
o o
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!
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "> <html xmlns="http://www.w3.org/1999/xhtml">
</html>
Page 60 of 654
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "> <html xmlns="http://www.w3.org/1999/xhtml">
</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. Another reason to use head and body tags is for controlling when a particular script will run (see page 314) .
Page 61 of 654
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.
Page 62 of 654
</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 element is required. A title cannot contain any formatting, images, or links to other pages. A page's title directly affects its ranking in many search engines. The closer a title is to the exact words that a potential visitor types without any extra words the higher up it will appear in the listings. It is also used to identify your page in the results (Figure 3.8). Figure 3.8. Perhaps most importantly, the title is used to describe your page in search results from Google and others. In addition, it's purportedly one of the more important factors for determining a page's relevance and rank in search results.
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>
<head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>Antoni Gaud - Introduction</title> </head> <body>
<h1>Antoni Gaud </h1> <h2>La Casa Mil #</h2> <h2>La Sagrada Fam lia</h2>
</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 o o Think of your headers as hierarchical dividers. Use them consistently. The only official rule about headers is that the higher the level (the smaller the number), the more prominently they should be displayed. Nevertheless, the major browsers currently display them all the same: in Times New Roman, boldface, at 24, 18, 14, 12, 10 and 8 pixels (9 pixels on the Mac), respectively. You can use styles to format headers with a particular font, size, or color (and more). For details, consult Chapter 10, Formatting with Styles. Add a named anchor (or id) to your headers so that you can create links directly to that header (see page 120). If desired, you can align the text in the header by typing align="direction" in the opening tag, where direction is left, right, or center. But note that the align attribute has been deprecated in favor of style sheets (see page 171) .
o o o
</head> <body> <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> <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> <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> </body>
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 o In HTML, the closing </p> tag is optional. However, it is required both in XHTML and when applying styles to a paragraph. Therefore, I recommend always ending a paragraph with </p>. You can use styles to format paragraphs with a particular font, size, or color (and more). For details, consult Chapter 10, Formatting with Styles. To control the amount of space between lines, consult Setting the Line Height on page 164. To control the amount of space after a paragraph, consult Adding Padding around an Element on page 188 or Setting the Margins around an Element on page 189. One quick and dirty (and valid) trick for adding extra space between paragraphs is to type (a non-breaking space) between each additional p element. Better yet, use CSS (see pages 188%189). You can align the text in the paragraph by typing align="direction" in the opening p tag, where direction is left, right, center, or justify. But note that the align attribute has been deprecated in favor of style sheets (see page 171).
o o
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 class="name", where name is the identifying name of the class.
Tips o o o o o o Each id in an (X)HTML document must be unique. In other words, no two elements can be named with the same id. More than one element may belong to, and thus be marked with, the same class. For information about applying styles to an element with a particular id or class, consult Selecting Elements by Class or ID on page 137. The class and id attributes may be added to most (X)HTML elements but are particularly useful with the div and span elements (see pages 68%69) . The id attribute automatically turns the element into an anchor, to which you can direct a link. For more details, consult Creating Anchors on page 120. Finally, the id attribute can also be used to identify elements that will be affected by a scripting language, such as JavaScript.
</head><body> <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 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 o o o A division is a block-level element. That means that its contents automatically start on a new line. 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. You're not required to label each division with a class or id, though they're much more powerful if you do. 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
<body> <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>
<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 o o For more details on the difference between block-level and inline content, consult Block vs Inline on page 28. A span has no inherent formatting. It becomes useful when you apply styles to it (generally through its class or id). 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.
Page 71 of 654
<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. You can use multiple br tags to create extra space between lines or paragraphs. 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. 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). 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.
o o
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.
<body> <!--Here is the table of contents, which in a real document might be a good deal longer. --> <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>
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 o o o Comments are particularly useful for describing why you used a particular tag and what effect you were hoping to achieve. Another good use for comments is to remind yourself (or future editors) to include, remove, or update certain sections. You should view your commented page with a browser before publishing to avoid sharing your (possibly) private comments with your public. 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. 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.
[View full width]
<body> <!--Here is the table of contents, which in a real document might be a good deal longer. --> <div id="toc" title="Table of Contents" >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>
<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="".
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.
[View full width]
<h1>Barcelona Night Life</h1> <p>Barcelona is such a great place to live. People there really put a premium on <strong> socializing </strong>. Imagine it being more important to go out with your friends than to get that big promotion. Even when you're, gasp, <em>pushing 30</em>. They say there are more bars in Barcelona than in the rest of the European community <em>combined</em>.</p>
Page 77 of 654
Figure 4.4. Most browsers display em with italics and strong with bold.
o 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. 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. 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.
<h1>Barcelona Night Life</h1> <p>Barcelona is such a great place to live. People there really put a premium on <strong>socializing </strong>. Imagine it being more important to go out with your friends than to get that big promotion. Even when you're, gasp, <em>pushing 30</em>. They say there are more bars in Barcelona than in the rest of the European community <em>combined</em>.</p>
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> <p><small>The opinions expressed on this page are mine and mine alone. </small></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
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. 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. 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.
<body> <h2>Perl Tutorial, Lesson 1</h2> <p>If you're on a UNIX server, every Perl script should start with a shebang line that describes the path to the Perl interpreter on your server. The shebang line might look like this:</p> <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) . You can also format several lines of monospaced text with the pre tag (see page 77) . You can apply any font (that your visitor has installed) to your text with styles (see page 158).
o o
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.
<body> <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: <pre>my $number = param('number'); my $smoke = param('smoke'); my $dinner_index = param('dinner_index');
Page 82 of 654
Tips o 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) . 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. 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. You can also use styles to maintain line breaks and spaces (see page 170). Note that pre is block-level while the tags on page 76 are all inline.
o o
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.
<p>Sometimes I get to the point where I'm not sure anything matters at all. Then I read something like this and I am inspired: </p> <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> <p>This is from Barbara Kingsolver's brilliant collection of essays, <cite>High Tide in Tucson</cite> (1995, HarperCollins)</p>.
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.
[View full width]
<html xmlns="http://www.w3.org/1999/xhtml" lang="en"> [snip] <p>And then she said <q>Have you read Kingsolver's <q> High Tide in Tucson </q> ? It's inspiring. </q></p> <p>She tried again, this time in French: <q lang="fr"> Avezvous lu le livre <q lang="fr"> High Tide in Tucson </q> de Kingsolver? C'est inspirational.</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!)
[View full width]
<html xmlns="http://www.w3.org/1999/xhtml" lang="fr"> [snip] <p>And then she said <q lang="en">Have you read Kingsolver's <q lang="en"> High Tide in Tucson</q>? It's inspiring. </q></p> <p>Grasping at straws, she gave it one last shot, this time in French:<q>Avez-vous lu le livre <q>High Tide in Tucson </q> de Kingsolver? C'est inspirational.</q></p>
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. 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. 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. 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. For more details on the xml:lang and lang attributes, consult Specifying Your Page's Language on page 342. You can find a complete list of language codes at http://www.w3.org/WAI/ER/IG/ert/iso639.htm.
o o o
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> <p>In addition to being an amazing cellist, Pau Casals is remembered in this country for his empassioned speech against nuclear proliferation at the United Nations<sup>2</sup> which he began by saying "I am a Catalan. Catalonia is an oppressed nation."</p> <p><sup>1</sup>It means Paul in English.<br /> <sup>2</sup>In 1963, I believe.</p> </body>
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 o o o o Most browsers automatically reduce the font size of a sub- or superscripted character by a few points. Superscripts are the ideal way to format certain foreign language abbreviations like Mlle for Mademoiselle in French or 3 a for Tercera in Spanish. Subscripts are perfect for writing out chemical molecules like H2O. Superscripts are also handy for creating footnotes. You can combine superscripts and links to make active footnotes (the visitor jumps to the footnote when they click the number or asterisk). For more information, see Chapter 7, Links. Super- and subscripted characters gently spoil the even spacing between lines. You can remedy this by changing the size of the sub or sup text (see pages 75 and 162) and adjusting its line height (see page 164).
Figure 4.21 You have to be a little bit careful to include the associated punctuation with the ins and del elements.
[View full width]
<body> <p><big>I promise to do all of my homework, <ins> all of my chores,</ins> clean the cat
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>
Figure 4.22. The changes become quite apparent.
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). 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. 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.
o o
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. Or type <acronym if the abbreviation can be pronounced as a word. 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.
[View full width]
<p><abbr title="Lyndon Baynes Johnson">LBJ</abbr> took the <abbr title="Interborough Rapid Transit">IRT</abbr> down to 4th Street <abbr title="United States of America">USA</abbr> . <br />When he got there, what did he see? <br />The youth of America on <abbr title="d-Lysergic Acid Diethylamide">LSD</abbr> .</p> <p>--Hair, the Musical, 1967</p> <p>Or perhaps you'd rather talk about something slightly less political, like <acronym title="Light Amplification By Stimulated Emission of Radiation">laser</acronym> , or <acronym title="Radio Detection And Ranging">radar</acronym> , or <acronym title="Self-Contained Underwater Breathing Apparatus">scuba</acronym> ? </p>
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). Figure 4.24. Netscape 6 Mac/Win highlight abbreviations and acronyms with a dotted underline and when your visitors hover, they get a question mark pointer, and then the contents of the element's title attribute.
Page 90 of 654
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. Figure 4.25. Explorer 5 for Mac displays acronyms in small caps, and if the visitor hovers over them in just the right place, produces the contents of the element's title attribute. It completely ignores the abbr elements.
Explorer for Windows (up to version 6) supports neither abbr nor acronym (though it still shows titles as tool tips).
Page 91 of 654
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 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". 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. 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. Many photo processing outfits will develop a roll of film directly onto a CD. 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. 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.
Page 99 of 654
Images with continuous tones, like photographs, should be saved in either JPEG or PNG24 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.
6. Adjust the additional settings that appear until you get the smallest file possible with an acceptable quality. (These settings are discussed throughout the rest of this chapter.) 7. Click OK in Photoshop Elements or Save in Photoshop. Choose a directory and name the new file. It will automatically carry the extension of the selected format (and thus normally will not replace the original image).
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 computergenerated 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).
Figure 5.9. The Save For Web window in Photoshop Elements, Adobe's consumer-end digital-imaging program, is slightly simpler than Photoshop's !for example, only allowing for one optimized version to be shown at a time!but still contains the most important features. Perhaps the most important difference is the absence of the Color Table. However, with the dwindling base of 8-bit monitors, exerting precise control over which colors appear in an image begins to look a lot like overkill (see page 96).
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).
Tips o 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. 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. 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). 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.
To create transparency:
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... 1. Copy part of an existing image (Figure 5.13). Figure 5.13. Select the desired portion of an existing image (left) and then choose Edit > Copy.
2. Paste it to a new layer. New layers by default have a transparent background (Figure 5.14). 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).
3. Hide or eliminate any non-transparent layers, if necessary. Or... You may have to combine the two techniques, for example, pasting a new layer into a new document with a transparent background.
3. If you know the color of the background upon which the image will be placed (that will shine through the transparent areas), choose that color in the Matte menu ( Figure 5.16). The pixels that are partially transparent will be blended with the Matte color to make a smooth transition from the image to the background. 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.
If you don't know the background color, choose None in the Matte pop-up menu. This creates a hard border, converting pixels that are 50% or more transparent to fully transparent and pixels that are less than 50% transparent to fully opaque. 4. Click OK and give the file a name. 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 o In Photoshop, but not Photoshop Elements, you can select individual colors from the Color Table and convert them to transparency. 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.
Figure 5.18. One way to select the background is to first select the foreground and then choose Select > Inverse.
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.
4. Use the Save For Web window to save the image as usual (without choosing the Transparency option, since there are no real transparent areas). 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. 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. Of course, if your visitors override the background color, the effect is lost.
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 topright 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).
Figure 5.21. In order to see what your image will look like on an 8-bit monitor, choose Browser Dither from the pop-up menu that descends from the little arrow at the top-right corner of the image area.
Figure 5.22. The background color is not Web-safe and so it dithers on an 8bit monitor.
1.
4. Click the color cube icon at the bottom of the Color Table tab (the second icon from the left) to shift the dithering color to a Web-safe color (Figure 5.25). 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 Websafe substitute.
5. Go through steps 1!5 for each color that is noticeably dithering. Figure 5.26. Instead of changing all the colors, we change only the color that was dithering badly.
Tips
Since there are only 216 Web-safe colors, a suitable substitute for your color may not be available. You have to decide whether it's worth it to switch to a Web-safe color in order to avoid dithering (which is not always the end of the world and which only occurs on 8-bit monitors). The Browser Dither option actually shows you the colors you would see if you were viewing the image in a Web browser. Therefore, in Photoshop, if you try to select a dithering color with the Browser Dither option on, you'll end up selecting the Websafe color, if it's available in the Color Table. Instead, turn off the Browser Dither option so that you can select the real culprit. In Photoshop (but not Photoshop Elements) you can unshift colors by selecting them and choosing Shift/Unshift Selected Colors to/from Web Palette in the document panel menu. You can also let Photoshop decide which colors to shift by setting a tolerance level in the Web Snap box at the bottom right of the Save For Web window's options area. Personally, I like manually choosing just the colors that are causing a problem. Since JPEG images generally have many more than 256 colors, there's no way to keep them from dithering. Only worry about Web-safe colors with GIF or PNG-8 images.
2. Click in the Colors pop-up menu and reduce the number of colors (Figure 5.28). 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 o In my tests, it seems that in general, if reducing colors helps GIF or PNG compression, switching to JPEG format does even better. The rub is that JPEG doesn't support transparency. So, if you must have transparency, reducing colors can be a fruitful exercise, since this will effectively reduce the size of a transparent GIF.
Tips o o o Displaying images progressively is probably most useful with large images. Interlacing has the biggest impact on slow computers with slow connections. On faster computers, it's often hard to notice any effect at all. If you readjust any of the other settings in the Save For Web window or scroll the preview around with the Hand tool, the Interlaced option goes back to being unchecked. Be sure to recheck it before you click OK.
Or... (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.
Figure 5.32. With a Blur factor of 0.5, the image size is reduced to 50.74K and the download time goes to 19 seconds. Also notice, however, that the image is noticeably, if subtly, blurred.
Tips o 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. 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. 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.)
Figure 5.33. Every layer that will be a frame in the animated GIF should be visible. Here we see the last frame (the top layer) of our soon-to-be animated GIF and the Layers palette.
2. Choose File > Save for Web. 3. In the Save For Web window, choose GIF Format and check the Animation box. The controls become active in the bottom part of the window (Figure 5.34). 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.
5. Check the Loop box if you'd like the animation to begin again each time it reaches the end. 6. Click the arrows at the bottom of the Animation area to preview the different frames of the animation in the optimization window.
Tips o o o You insert an animated GIF on your page just like any other image (see page 104). 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. Animated GIFs are created essentially the same way in Photoshop, but it relies on ImageReady (which is included with Photoshop) for saving them.
<h1>Barcelona's Market</h1> <img src="outsidemarket.jpg" /> <p>This first picture shows the entranceway to the Mercat de la Boquer a, the central market that is just off the Rambles. It's an incredible place, full of every kind of fruit, meat, fish, or whatever you might happen to need. It took me a long time to get up the nerve to actually take a picture there. You might say I'm kind of a chicken, but since I lived there, it was just sort of strange. Do you take pictures of your supermarket?</p>
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.
Tips o o o o Add a p or br tag before an image to start it on its own line. For information on creating images especially for Web pages, consult Chapter 5, Creating Web Images. Use this technique to place GIF, JPEG, PNG, or any other kind of images that the browser recognizes. Don't expect your visitors to wait more than 10 seconds to load and view your entire page (about 50K total with a 56 Kbps modem connection). One alternative is to
create miniatures (see page 92) of large images and let visitors choose to view the larger images (see page 109). There is a deprecated border attribute (border="n" , where n is the width in pixels) that adds or eliminates a border around images, especially the automatic border that appears around images used in links (see page 128) . Better yet, you can use styles to control this and all other aspects of images (see page 186) .
<h1>Barcelona's Market</h1> <img src="outsidemarket.jpg" alt="Entranceway to Mercat de la Boquer a"/> <p>This first picture shows the entranceway to the Mercat de la Boquer a, the central market that is just off the Rambles. It's an incredible place, full of every kind of fruit, meat, fish, or whatever you might
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.
Tips
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="". Figure 6.5. On Explorer for Windows, when the visitor points at an image with alternate text, the alternate text appears in a tool tip. You can create tool tips for all current browsers by using the title tag (see page 72).
o o
If the image is just for formatting, like a horizontal line or a bullet image, the W3C suggests you use alt="". 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. 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.
2. Choose Properties or Get Image Info (depending on your browser). A box appears that shows the dimensions of your image, in pixels (Figure 6.7). 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.
To figure out the size of your image with Photoshop or Photoshop Elements:
1. Open the image in Photoshop or Photoshop Elements. 2. Choose Window > Info to display the Info palette, if it's not already visible. 3. Choose Select All (Command-A on a Mac, Control-A on Windows). The image's dimensions will be displayed in the bottom-right corner of the Info palette (Figure 6.9). You may have to choose Palette Options in the Info palette's menu to display the dimensions 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.
Figure 6.9. The Info palette in both Photoshop and Photoshop Elements displays the size of a selection. Choose the units by selecting Palette Options in the pop-up menu.
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.
[View full width]
[snip] just sort of strange. Do you take pictures of your supermarket?</p> <img src="vegetables.jpg" width=" 417" height=" 283" alt=" Peppers and Cucumbers" /> <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.
Tips o o 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. 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). 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.) 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
You can change the size of an image just by specifying a new height and width in pixels. This is an easy way to have large images on your page without long loading times. Beware, though, if you enlarge your pictures too much, they'll be grainy and ugly.
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.
[View full width]
<h1>Fish Ladies</h1> <img src=" fishlady.jpg" width=" 198" height=" 219" alt=" One of the fish ladies" />
<p>The fish ladies hold a special place in the market's heart, where the floors are wet and kind of slimy, the pervasive smell of fish floats in the air, and the cold chill from the ice makes you forget the sunny day you left outside. Unless they're helping
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 o You can also use a percentage value in step 2, with respect to the browser window (not the original image size). 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) . You can set just the width or just the height and have the browser adjust the other value proportionally.
You can also use styles to control the width and height of elements. For more information, consult Setting the Height or Width for an Element on page 190.
<h1>More Market Pictures</h1> <p><a href=" flowers.jpg" ><img src=" flowers_little.jpg" alt=" Flowers on the Rambles" width=" 83" height=" 125" /></a> <a href=" fruitstand.jpg" ><img src=" fruitstand_little. jpg" alt=" Fruit stand" width=" 103" height=" 67" /></a> <a href=" ham.jpg" ><img src=" ham_little.jpg" alt=" Charcuterie" width=" 123" height=" 85" /></a> <a href=" cannedgoods. jpg" ><img src=" cannedgoods_little.jpg" alt=" Canned goods, hams, wine, oil, olives!" width=" 84" height=" 123" /></a> </p>
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.
Figure 6.17. If the visitor clicks the icon, the browser opens a new window with the full size image.
Tip
Using miniatures or thumbnails is an ideal way to get a lot of graphic information on a page without making your visitors wait too long to see it. Then they can view the images that they are most interested in at their leisure.
<body> <img src=" house.jpg" align=" right" alt=" house" width=" 237" height=" 225" /> <h1>The Pioneer Valley: Northampton</h1> This triplex on South Street is a good [snip] </body>
Figure 6.19. The image is aligned to the right and the text wraps around it.
Figure 6.20 To make the image appear on the left with the text wrapped around the right side, use align="left" .
<body> <img src=" house.jpg" align=" left" alt=" house" width=" 237" height=" 225" /> <h1>The Pioneer Valley: Northampton</h1> This triplex on South Street is a good [snip] </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.
<body> <img src=" courthouse.jpg" alt=" courthouse" align="right" width=" 256" height=" 229" /> <h1>The Pioneer Valley: Northampton</h1> <p>This building, that some might say looks like a church, is actually the Hampshire County Courthouse. If you ever get called to be [snip] </p> < <img src=" house.jpg" alt=" house" align=" left" width=" 237" height=" 225" /> <p>This triplex on South Street is a good example of multifamily dwellings in the area. Built as a one family home in the 30s, it has been [snip].</p> </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.
Tips o o o The key is to place each image directly before the text it should "disrupt." 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. 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.
<img src=" house.jpg" align=" right" height=" 200" alt=" house" /> <h1>The Pioneer Valley: Northampton</h1> <img src=" flower.gif" align=" left" alt=" flower" width=" 43" height=" 43" /> <br clear=" left" /> This triplex on South Street is a good example of
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.26 The order is the same as in the last example; only the clear attribute has changed.
<img src="house.jpg" align="right" width="237" height="225" alt="house" /> <h1>The Pioneer Valley: Northampton</h1> <img src="flower.gif" align="left" alt="flower" width="43" height="43" /> <br clear="all" /> This triplex on South Street is a good example of
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
browsers, and thus, I think it's important to know about the clear attribute. For information on using styles to control the text flow, consult Controlling Where Elements Float on page 195. Note that the clear attribute affects the elements that follow a floated image, while the CSS clear property described on page 195 more directly affects the floated element itself. It's just a slightly different perspective.
Figure 6.29 You can add horizontal space or vertical space, or both, to your images.
<p><img src="house.jpg" align="right" height="200" alt="house" vspace="15" /></p> <h1>The Pioneer Valley: Northampton</h1> <p><br clear="right" /> <img src="flower.gif" align="left" width="43" height="43" hspace="6" alt="flower" /> This triplex on South Street is a good example of [snip]
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 o You don't have to add both hspace and vspace at the same time. 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. 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.
If you just want to add space to one side of the image, you could use Photoshop to add blank space to that side, and skip hspace and vspace altogether. Then, make the blank space transparent (see page 93).
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.
[View full width]
<img src="castle.jpg" alt="castellers" /> default <img src="star.gif" align="texttop" alt="star" /> texttop <p><img src="castle.jpg" alt="castellers" /> default <img src="star.gif" align="top" /> top</p> <p><img src="castle.jpg" alt="castellers" /> default <img src="star.gif" align="middle" /> middle </p> <p><img src="castle.jpg" alt="castellers" /> default <img src="star.gif" align="absmiddle" /> absmiddle</p> <p><img src="castle.jpg" alt="castellers" align="texttop"/> texttop <img src="star.gif" align="bottom" /> bottom</p> <p><img src="castle.jpg" alt="castellers" align="texttop"/> texttop <img src="star.gif" align="absbottom" /> absbottom</p>
3. Add other attributes as desired and then type the final />. 4. Type the text with which you wish to align the image. (This text may also precede the image.)
Tips o The absmiddle , absbottom , and texttop values are proprietary extensions developed by Netscape, but current browsers of both versions support them. Earlier versions of Explorer treated texttop as top, absmiddle as middle and absbottom as bottom. IE also understands center, for middle. The align attribute is deprecated. That means the W3C recommends you start using style sheets to control how elements are aligned on your page (see page 196).
1. Type <hr where you want the rule to appear. The text that follows will appear in a new paragraph below the new rule. 2. If desired, type size="n", where n is the rule's height in pixels. 3. If desired, type width="w", where w is the width of the rule in pixels, or as a percentage of the document's width. 4. If desired, type align="direction", where direction refers to the way a rule should be aligned on the page; either left, right, or center. The align attribute is only effective if you have made the rule narrower than the browser window. 5. If desired, type noshade to create a solid bar, with no shading. Add ="noshade" in XHTML. 6. Type the final /> to complete the horizontal rule definition. Figure 6.33 The hr tag includes an automatic line break both before and after the rule.
<body> <img src="banner.gif" alt="SE banner" /> <h1>New products</h1> <p>AstroFinder 3 <br />Pleiades Expander <br />Southern Cross</p> <hr size="10" width="80%" align="center" noshade="noshade" /> </body>
Figure 6.34. Horizontal rules are helpful for dividing sections on your page.
Tips
All of the attributes for hr (but not hr itself) are deprecated. The W3C recommends using styles to format your horizontal rules (see page 175) . There is no CSS equivalent to noshade . One solution is to omit rules and just apply borders (see page 186) . IE supports a color attribute, which automatically sets the noshade attribute.
Chapter 7. Links
Links are the distinguishing feature of the World Wide Web. They let you skip from one page to another, call up a movie or a recording of The Nields (or your favorite band), and download files with FTP. 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.
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.
[View full width]
<body> <h1>Cookie and Woody</h1> <img src="woodygran.jpg" alt="Woody" width="202" height="131" /> <img src= "cookiefora. jpg" width="143" height="131" /> <p>Generally considered the sweetest and yet most independent cats in the <a href="pioneerval.html"> Pioneer Valley,</a> Cookie and Woody are consistently underestimated by their humble humans.</p>
So, a link to a page at another site might look like: <a href="http://www.site.com/directory/page.html"> Label text</a> (Figures 7.5, 7.6, and 7.7). Specify the path but omit the file name to link to the default file for a directory, usually one of index.html or default.htm: http://www.site.com/directory/. Omit the path as well to link to a site's default (home) page: http://www.site.com/. It's a good idea to use all lowercase letters for your URLs to avoid problems on the many servers that are case sensitive. href stands for hypertext reference. Figure 7.3. 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 actually click on a link...
Figure 7.4. ...the page associated with that destination URL is displayed in their browser.
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.
Try not to use "Click here" for a label. Instead use the key words that already exist in your text to identify the link. You may apply styles (see page 157) or (X)HTML basic text formatting (see page 73) to the label or even use an image as a label (see page 128). To create a link to a particular place on a page, use an anchor (see pages 120% 121) . To make the link appear in a given window or frame, use a target (see page 122) . You can create keyboard shortcuts for links. For more details, see page 126. You can determine the tab order for visitors who use their keyboards to navigate your page. For more details, consult Setting the Tab Order for Links on page 127. An a element may contain any kind of inline tag except another a element. It may not contain a block-level element like p.
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.
[View full width]
<body> <h1>Pixel</h1> <p>If you'd like to meet a JavaCat, check out <a href="http://www.pixel.mu/">Pixel</a> at Tom Negrino and Dori Smith's great site about their <a href="http://www.javascriptworld.com/"> <em>JavaScript for the World Wide Web: Visual QuickStart Guide</em></a>.</p> </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...
Figure 7.7. ...the page associated with that destination URL is displayed in their browser.
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.
[View full width]
<body> <div class="toc"> <h2>Table of Contents</h2> <a href="#intro">Introduction</a> <br/> <a href="#descrip">Description of the Main Characters</a><br/> <a href="#rising">Rising Action</a><br /> <a href="#climax">Climax</a><br /> <a href="#denoue">Denouement</a> </div> <h2><a name="intro">Introduction</a>< /h2> <p>This is the intro. If I could think of enough things to write about, it could span a few pages, giving all the introductory information that an introduction should introduce. </p> <h2><a name="descrip">Description of the Main Characters</a></h2> <p>Frankie and Johnny are the main characters. She's jealous, and seems to have a reason to be. He's a sleaze, and will pay the price. </p> <h2><a name="rising">Rising Action</a> </h2> <p>This is where everything starts happening. Johnny goes out, without Frankie, without even tellin' her where he's going. She's not crazy about it, but she lets him go. A while later, she gets thirsty and decides to go down to the corner bar for some beer. Chatting with the bartender, she learns that Johnny has been there with no other than Nellie Bly. Furious, she catches the cross town bus to find him.</p> <h2><a name="climax">Climax</a></h2> <p>When Frankie gets to Nellie's house, she looks up and sees them kissing on the balcony. With tears in her eyes, she picks up her shotgun and kills her Johnny. He falls to the ground.</p> <h2 id="denoue" >Denouement</h2> <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
You can also create an anchor by adding an id attribute to the desired element (see page 67) . Quotes are always required around the anchor name in XHTML. While they're sometimes optional in HTML (see page 36) , I highly recommend them. In a long document, create an anchor for each section and link it to the corresponding item in the table of contents.
The W3C, Netscape, and others are not at all consistent with the terminology. Some folks call links anchors a is for anchor, after all others call targets anchors. In this book, the word anchor refers to a specific location in a document that you link to. (A target is the window or frame where a link will appear. See page page 122.)
Figure 7.10. Once the visitor clicks the link, the particular part of the page that the anchor references is displayed at the top of the browser window.
Tips
If the anchor is in a separate document, use <a href="page.html#anchorname"> to reference the section. (There should be no space between the URL and the #.) If the anchor is on a page on a different server, you'll have to type <a href= "http://www.site.com/path/page.html #anchorname"> (with no spaces). While you obviously can't add anchors to other people's pages, you can take advantage of the ones that they have already created. View the source code of their documents to see which anchor names correspond to which sections. (For help viewing source code, consult The Inspiration of Others on page 57.) If the anchor is at the bottom of the page, it may not display at the top of the window, but rather towards the middle.
To target links:
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.)
[View full width]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/2000/REC-xhtml1-20000126/DTD/ xhtml1transitional.dtd "> [snip]<h1>Nathaniel Hawthorne</h1> <p>Nathaniel Hawthorne was one of the most important writers of 19th century America. His most famous character is <a href="hester.html" target= "characters" >Hester Prynne</a>, a woman living in Puritan New England. [snip]</p> <p>Besides <a href="scarlet.html" target="books" ><em>The Scarlet Letter</em></a>, Hawthorne wrote <a href="gables.html" target="books" ><em>The House of Seven Gables</em>
Figure 7.12. When the visitor clicks a link with a target...
Figure 7.13. ...the corresponding page is shown in the targeted window. In this example, it's the characters window.
Tips
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 email 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-befinalized XLink. I say, use target. (It is part of both (X)HTML transitional and frameset.)
1. In the head section of your Web page, type <base. 2. Type target="title", where title is the name of the window or frame in which all the links on the page should open, by default. 3. Type /> to complete the base tag. 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.
[View full width]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional //EN" "http://www.w3.org/TR/2000/REC-xhtml1-20000126/DTD/ xhtml1transitional.dtd "> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <title>American Writers of the 19th Century</title> <base target="characters" /> </head> <body> <h1>Nathaniel Hawthorne</h1> <p>Nathaniel Hawthorne was one of the most important writers of 19th century America. His most famous character is <a href="hester.html">Hester Prynne</a>, a woman living in Puritan New England. Another famous object of Hawthorne's writing was <a href="http://www. ripon.edu/dept/pogo/presidency/Pierce/">Franklin Pierce </a>, the 14th president of the United States.</p> <p>Besides <a href="scarlet.html" target="books"> <em>The Scarlet Letter</em></a>, Hawthorne wrote <a href="gables.html" target="books"> <em>The House of Seven Gables</em></a>, <a
Tips
Target names are case sensitive! In addition, you should always enclose them in quotation marks. You can override the default target specified in the base tag by adding a target attribute to an individual link (see page 122). While the base tag is part of (X)HTML strict, the target attribute is not. I use it anyway (see the last tip on page 122). You can also use the base tag to set the base URL for constructing relative URLs. This can be particularly useful when a Perl CGI script, located off in the cgi-bin directory, is generating the (X)HTML page, and you want to reference a bunch of images or links in the main part of your server. Use <base href="base.url" /> where base.url is the URL that all relative links should be constructed from. Put another way, the URL reflects the virtual location of the generated (X)HTML page.
<h1>Getaway Destinations</h1> <p>There are lots of different kinds of links that you can create on a Web page.</p> <p>You might want to create a link to a directory on <a href="ftp://www.joy.ne.jp/welcome/ igs/Go/">the IGS Go site</a> to help visitors download articles or problems about Go (a Japanese strategy game). Or
point them to a specific file like the <a href="ftp://www.joy.ne.jp/welcome/igs/Go/ FAQ">Go FAQ</a> so they don't have to navigate the FTP site.</p> <p>To allow access to a <a href="ftp://name:password@ftp.site.com/directory ">private FTP site</a>, you have to preface the server name with the user name and password.</p> <p>A link to an e-mail address is a great way to elicit comments about your Web page. Unfortunately, spammers are great at snatching up e-mail addresses from Web pages and filling your mailbox with unsolicited junk. Don't think so? <a href="mailto:html5ed@cookwood.com">Tell me</a> about it.</p> <p>Links to newsgroups help visitors find other people interested in the same topic. For example, check out the <a href="news:rec.pets.cats"> newsgroup for cat lovers</a> . Can you believe there's no special section for Llumi and Xixo? </p> <p>Some libraries let you <a href="telnet://melvyl.ucop.edu:23/">log into their system</a> from home with telnet to see if a particular book is available or checked out. Most browsers don't view telnet connections inline, but instead open a helper application like Nifty Telnet.</p> <p>Hey, what if you just want to let your visitors download a file that's on your server in the same directory as your Web pages? No problem. The link will look like any other Web link. Here, download the Windows version of the <a href="http://www.cookwood.com/html5ed/examples/html5ed _examples.zip"> examples</a> from this book. </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
Tips
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.
You can preface an FTP URL with name:password@ to access a private FTP site. Beware that browsers keep track of where you've been, however, including your password. (For example, in Netscape, type about:global.) If you want to create an FTP link to a particular directory on the FTP site (as opposed to an individual file), simply use ftp://ftp.site.com/directory. You don't need to use the trailing forward slash. When you don't specify a specific file to download, the browser automatically displays the contents of the last directory in the path.
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.
[View full width]
<h1>Our Cats</h1> <p>Each of our cats has their own home page. Click on the corresponding link or use the keyboard shortcut to see each one. <br /><a href="gatetseng.html#woody" accesskey="w" >Woody</a>(Alt-W, Ctrl-W) <br /><a href="gatetseng.html#cookie" accesskey="c" >Cookie</a> (Alt-C, Ctrl-C) <br /><a href="gatetseng.html#xixona" accesskey="x" >Xixona</a> (Alt-X, Ctrl-X) <br /><a href="gatetseng.html#llumeta" accesskey="l" >Llumeta</a> (Alt-L, Ctrl-L)</p> </body>
Figure 7.18. There's no way to tell a link has a keyboard shortcut unless you've labeled it as such.
Figure 7.19. When the keyboard shortcut is used, the link is immediately accessed (and the corresponding page is shown).
Tips
On Netscape (Mac/Win) and Explorer for Mac, typing a keyboard shortcut activates the link, but on Explorer for Windows, it merely gives focus to the link and the visitor must still press Return to actually follow it. On Windows systems, to invoke the keyboard shortcut, visitors use the Alt key plus the letter you've assigned. On Macintosh, visitors use the Control key, plus the letter.
Keyboard shortcuts don't work at all in Opera and are unreliable with frames, unless the visitor selects the frame which kind of defeats the purpose. Keyboard shortcuts that you choose can (annoyingly) override the browser's shortcuts. For example, in most Windows programs, Alt-F is for accessing the File menu. If you use Alt-F for a keyboard shortcut, your visitors won't be able to use the keyboard to access their browser's File menu.
<div id="toc"><a href="toc.html" tabindex="2"> Contents</a> <a href="search.html" tabindex="2" >Search</a> <a href="company.html" tabindex="2">About Us</a></div> <h1>Our Cats</h1> <p>Each of our cats is special. Click on the corresponding link or use the keyboard shortcut to read about each one.</p> <p><a href="gatetseng.html#woody" accesskey="w" tabindex="1" >Woody</a> (Alt-W, Ctrl-W) <br /><a href="gatetseng.html#cookie" accesskey="c" tabindex="1" >Cookie</a> (Alt-C, Ctrl-C) <br /><a href="gatetseng.html#xixona" accesskey="x" tabindex="1" >Xixona</a> (Alt-X, Ctrl-X) <br /><a href="gatetseng.html#llumeta" accesskey="l" tabindex="1" >Llumeta</a> (Alt-L, Ctrl-L)</p> </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.
Tips
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.
1. Type <a href="destination.html">, where destination.html is the URL of the page that the user will jump to when they click the button. 2. Type <img src="image.jpg" where image.jpg gives the location of the image file on the server. 3. If desired, type border="n", where n is the width in pixels of the border. Use a value of 0 to omit the border. 4. Add other image attributes as desired and then type the final />. 5. If desired, type the label text, that is, the text that will be underlined or highlighted in blue, that when clicked upon will take the user to the URL referenced in step 1. 6. Type </a> to complete the link. Figure 7.22 There is no text in the first two button links. The final </a> comes right after the image tag.
[View full width]
<body> <h1>Cookie and Woody</h1> <p>Generally considered independent cats in the href="pioneerval.html"> are consistently underestimated by their <p> <a href="prevpage.html"> <img src="pointleft.gif" alt="Previous page" /> </a> <a href="nextpage.html"> <img src="pointright.gif" alt="Next page" /></a></p> <p><a href="mailto:lcastro@crocker.com"><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).
the sweetest and yet most <a Pioneer Valley,</a> Cookie and Woody humble humans.</p>
Figure 7.24. This is the original pointright.gif image. It does not have a border. In most browsers (not Opera), borders are automatically added to all images used to label links. You can adjust the border with the deprecated border attribute in the img tag, or with styles (see page 186).
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).
2. Open the image in Photoshop or other image editing program. 3. Choose Window > Palettes > Show Info (Figure 7.25). Figure 7.25. In either Photoshop (left) or Photoshop Elements, choose Window > Info to show the Info palette.
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.
7. Repeat steps 5!6 for the rectangle's lower-right corner, for each point of a polygon, or for a circle's center and radius.
If desired, add a keyboard shortcut by typing accesskey="x" (see page 126) . Type /> to complete the clickable area. Repeat steps 3!10 for each area. Type </map> to complete the map. Type <img src="image.gif", where image.gif is the name of the image to be used as an image map. 14. Add image attributes, including alt. 15. Type usemap="#label", where label is the map name defined in step 2. 16. Type the final /> for the image.
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.
[View full width]
<body><p> <map name="banner" id="banner"> <area alt="new information" shape="rect" coords="395, 18, 445, 35" href="newinfo.html" /> <area alt="press releases" shape="rect" coords="395, 38, 445, 55" href="pressrelease. html" /> <area alt="events" shape="rect" coords="395, 58, 445, 75" href="events.html" /> </map> <img src="clickimage.gif" alt="SE banner" usemap="#banner" width="450" height="100" /> </p> <div id="content"> <h1>Starsearch Enterprises</h1> <a href="newinfo.html">New programs</a> <br /> <a href="pressrelease.html">Press releases</a><br /> <a href="events.html">Upcoming events</a> <br /> <a href="infoSE.html">About Starsearch Enterprises</a><br /> </div> </body>
Figure 7.28. When your users point at one of the defined areas, the destination URL appears in the status bar at the bottom of the window.
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.
The target attribute is only allowed in (X)HTML transitional and frameset. The id attribute in map is required in XHTML strict, but most browsers need the name for it to work. So use both.
<body> <p><a href="http://www.cookwood.com/cgibin/imagemap/banner.map "> <img src="clickimage.gif" alt="SE banner" ismap="ismap" /> </a></p> <h1>Starsearch Enterprises</h1> <p><a href="newinfo.html">New programs</a> <br /> <a href="pressrelease.html">Press releases</a> <br /> <a href="events.html">Upcoming events</a> <br /> <a href="infoSE.html">About Starsearch Enterprises</a></p> </body>
Figure 7.31. When your user points at a part of a clickable image, the cursor changes into a hand and the corresponding URL shows in the status area at the bottom of the window.
Tip
For information on creating sets of coordinates for server-side image maps, consult your Internet service provider. They'll be able to tell you what kind of server they have and in what format the coordinates should be.
Figure 8.2. Multiple property/value pairs in the declaration must be separated by a semicolon. Some folks simply end every property/value pair with a semicolon! including the last pair in a list!so that they never forget to add it. That's fine, as shown here, but not required. Note the extra spacing and indenting to keep everything readable.
3. Type property: value;, where property is the name of the CSS property that describes the sort of formatting you'd like to apply and value is one of a list of allowable options for that property. CSS properties and their values are described in detail in Chapters 10 and 11. 4. Repeat step 3 as needed. 5. Type } to complete the declaration and the style rule.
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:
the type or name of the element (Figure 8.3), 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.
the context in which the element is found (Figure 8.4), Figure 8.4. This selector uses context. The style will only be applied to the
the class or id of an element (Figure 8.5), 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.
<h1>Antoni Gaud </h1> <div id="gaudi"> <p>Many tourists are drawn to Barcelona to see Antoni Gaud 's incredible architecture. </p> <p>Barcelona <a href="http://www.gaudi2002. bcn.es/english/flash/home/GO.htm">celebrates </a> 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 <em>real people</em> 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 <em>most visited</em> building in Barcelona. </p> </div> </div>
Figure 8.9 This selector will choose all of the h2 elements in the document.
h2{color:red;}
Figure 8.10. All the h2 elements are colored red.
Tips
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.
1. Type . (a period). 2. With no intervening space, immediately type label, where label identifies the class to which you'd like to apply the styles. 3. Create the rest of the style rule as usual (see page 134) . Figure 8.11 The division with an id of gaudi encloses almost the entire page (everything but the initial h1).
[View full width]
<h1>Antoni Gaud </h1> <div id="gaudi"> <p>Many tourists are drawn to Barcelona to see Antoni Gaud 's incredible architecture. </p> <p>Barcelona <a href="http://www.gaudi2002. bcn.es/english/flash/home/GO.htm">celebrates </a> 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 <em>real people</em> 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 <em>most visited</em> building in Barcelona. </p> </div> </div>
Figure 8.12 This selector will choose the div element with an id equal to "gaudi".
div#gaudi {color:red;}
Tips
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.
<h1>Antoni Gaud </h1> <div id="gaudi"> <p>Many tourists... </p> <p>Barcelona...</p> <div class="works"><h2>La Casa Mil #</h2> <p>Gaud 's work...</p> </div> <div class="works"><h2>La Sagrada Fam lia</h2> <p>The complicatedly named... </p> </div> </div>
div#gaudi p {color:red;}
3. If necessary, repeat steps 1!2 for each successive generation of ancestors. 4. Type descendant, where descendant 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.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.
Tips
A selector based on an element's ancestor is called a descendant selector. Descendant selectors are well supported by current browsers. Don't be thrown off by the div#gaudi portion of the example (even though it's ugly). Remember that it simply means "the div whose id is equal to gaudi" (see page 137). So div#gaudi p means "any p element that is contained in the div whose id is equal to gaudi".
A parent is the element that directly contains the desired element (the child) with no intermediary containing elements.
Tips
A selector based on an element's parent is called a child selector. Among current browsers, only IE 5.5 and IE 6 for Windows fail to support the child selector.
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:
1. Type parent, where parent is the name of the desired element's parent. 2. Type: first-child (just like that) (Figure 8.19). Figure 8.19 This selector chooses only those p elements that are the first child of the gaudi div.
Figure 8.21 This selector chooses only those p elements which directly follow a sibling p element.
Tips
Also see Parents and Children on page 29. The :first-child part of the selector is called a pseudo-class, because it identifies a group of elements without you, the designer, having to mark them in the (X)HTML code. Unfortunately, it is not yet supported by Internet Explorer for Windows (as of version 6). Adjacent sibling selectors are currently supported only by Netscape 6.
1. Type a (since a is the name of the link tag). 2. Type : (the colon). 3. Type link to change the appearance of links that haven't yet been or currently aren't being clicked or pointed at. 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. Or type hover to change the appearance of links when pointed to. Or type active to change the appearance of links when clicked. 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.
[View full width]
<h1>Antoni Gaud </h1> <div id="gaudi"> <p>Many tourists are drawn to Barcelona to see Antoni Gaud 's incredible architecture. </p> <p>Barcelona <a href="http://www.gaudi2002. bcn.es/english/flash/home/GO.htm">celebrates </a> 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 <em>real people</em> 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 <em>most visited</em> building in Barcelona. </p> </div></div>
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;}
Figure 8.25. The a element (the link) is red when it's new and unvisited, yellow after the visitor clicks it, olive when it has the focus, green when pointed at, and blue when clicked on.
Tips
These pseudo-classes (classes for intangible characteristics you can't mark manually) are supposed to work with all kinds of elements, but current browsers only support them for the link (a) tag. Since a link can be in more than one state at a time (say, simultaneously active and hovered above), it's important to define the rules in the following order: link, visited, focus, hover, active (LVFHA).
Figure 8.26 There is nothing highlighted here because you can't identify the first line until the page is displayed in the browser.
[View full width]
<h1>Antoni Gaud </h1> <div id="gaudi"> <p>Many tourists are drawn to Barcelona to see Antoni Gaud 's incredible architecture. </p> <p>Barcelona <a href="http://www.gaudi2002. bcn.es/english/flash/home/GO.htm">celebrates </a> 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 <em>real people</em> 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 <em>most visited</em> building in Barcelona. </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).
Figure 8.29 Here the selector will choose just first letter of each p element. For the corresponding (X)HTML code, see Figure 8.26 on page 142.
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.
Tips
The first-letter and first-line selectors are called pseudoelements, since they refer to actual content that can't be manually marked as an independent element. OK, you could conceivably mark each first letter of the paragraph with a special span tag (though it would be cumbersome), but the content of the first line depends on a myriad of factors, including such uncontrollable issues as the size of the visitor's window and the visitor's monitor resolution. If the paragraph begins with a quotation mark, the first-letter selector may include an opening quotation mark together with the first letter. Netscape 6, Internet Explorer 6, and Opera 6 all support both the firstline and first-letter pseudo-elements. You may combine the first-letter or first-line pseudoelements with more complicated selectors than that which I've used in this example. For example, if you wanted just the first-letter of the p elements in the works divs, your selector would be div.works p:first-letter.
<h1>Antoni Gaud </h1> <div id="gaudi"> <p>Many tourists are drawn to Barcelona to see Antoni Gaud 's incredible architecture. </p> <p>Barcelona <a href="http://www.gaudi2002. bcn.es/english/flash/home/GO.htm">celebrates </a> 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 <em>real people</em> 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 <em>most visited</em> building in Barcelona. </p> </div> </div>
4. Type ] (Figure 8.32). Figure 8.32 The square brackets enclose the desired attribute and any desired value.
5. Create the rest of the style rule as usual (see page 134) . 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).
5. Create the rest of the style rule as usual (see page 134) . Figure 8.34 There is one h1 and two h2 elements.
[View full width]
<h1>Antoni Gaud </h1> <div id="gaudi"> <p>Many tourists are drawn to Barcelona to see Antoni Gaud 's incredible architecture. </p> <p>Barcelona <a href="http://www.gaudi2002. bcn.es/english/flash/home/GO.htm">celebrates </a> 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 <em>real people</em> 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 <em>most visited</em> building in Barcelona. </p> </div> </div>
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.
Tips
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).
3. Then, specify the class or id of the desired element(s). For more details, consult Selecting Elements by Class or ID on page 137. 4. Next, specify the pseudo-class or pseudoelement. For more details, consult Selecting Link Elements Based on Their State on page 141 and Selecting Part of an Element on page 142. 5. Finally, specify which attributes and values must be present for the element to be selected. For more details, consult Selecting Elements Based on Attributes on page 144. 6. And then, create the rest of the style rule as usual (see page 134). 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.
3. Save the document in Text Only format in the desired directory (Figure 9.2). Give the document the extension .css to designate the document as a Cascading Style Sheet. 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.
<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" /> </head> <body> <img src="palau_corner.jpg" alt="Palau de La Música, from the corner" width="63" height="163" align="left"/> <img src="palau250.jpg" alt="El Palau de la Música" width="250" height="163"
Figure 9.5. The styles (a red, solid border) are applied to each img element.
Figure 9.6. Other documents can link to the very same external style sheet.
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).
3. To designate a style sheet that should be offered as an alternate choice, use rel="alternate stylesheet" title="label" in the link element, where label identifies the alternate 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.
<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.
Tips
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.
<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.
Tips
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.
Figure 9.15 The @import rule must be placed before any individual style rules in the style element. (It may come after other @import rules.)
<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
Netscape 4 doesn't support the @import rule. However, because its support of CSS in general is pretty abysmal, many Web page coders use this limitation to their advantage. For example, you could link to style sheets with rules that Netscape 4 deals with properly and then import style sheets with advanced techniques it can't handle. Netscape 4 will then have at least some of the style information while browsers who support @import will have it all. For more on hiding CSS from buggy browsers, see Johannes Koch's helpful http://pixels.pixelpark.com/~koch/hide_css_from_browsers/ The @import rule can also be written as @import url(external.css); or @import url("external.css");. Regardless, always put it before any other style rules in the style element and don't forget the semicolon. Style rules in an imported style sheet take precedence over any rules that come before the @import rule (for example, rules in earlier @import rules or in external sheets placed before the style element). You may use the @import rule in an external style sheet (as always, before any other style rules).
<head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>La Casa Milà</title> </head> <body> <img src="palau_corner.jpg" alt="Palau de La Música, from the corner" width="63" height="163" align="left"/> <img src="palau250.jpg" alt="El Palau de la Música" width="250" height="163" style="color: red; border: solid" align="left" /> <img src="tickets.jpg" alt="The Ticket Window" width="87" height="163"/> <br clear="all" /> <p>I love the Palau de la M &sica. It is ornate and
Figure 9.18. Only the middle image has a border. To repeat the effect shown in the rest of this chapter, you'd have to add style="color:red;border:solid" to every single img tag individually.
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.
External style sheets can also contain @import rules. In that case, the imported rules are overridden by the other rules contained in the external style sheet (since, by definition, they must follow the @import rule). Their relationship with the document's other style sheets is determined by the position of the link to the external style sheet, as usual. 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.
/* Images will have a solid red border */ img {color:red; border: solid}
Figure 9.24 If you prefer, you can insert comments after a style rule.
img {color:red; border: solid} /* Images will have a solid red border */
Tips
Comments may include returns, and thus span several lines. You can put comments around style rules effectively hiding them from the browser. This is a good way to test style sheets without permanently removing problematic portions. You may not put comments inside other comments. In other words, comments may not include */. You may start comments on their own line, or at the end of a style rule.
<body> <div id="toc"> <a href="#gaudi"> Antoni Gaud </a> <a href="#mila"> La Casa Mil #</a> <a href="#sagrada"> La Sagrada Fam lia</a> </div> <div id="gaudi"> <h1><a name="gaudi"> Antoni Gaud </a></h1> <p>Many tourists ... </p> <p>Gaud 's ... the <a href="#mila">Casa Mil#</a> and its undulating balconies, to the Church of the <a href="#sagrada"> Sacred Family </a> and its organic, bulbous towers. </p> <p>Barcelona <a href="... G0.htm"> celebrates </a>the 150th anniversary ... There has <span class="emph"> never</span> been a better time to visit this incredible city. </p> <div class="work"> <h2><a name="mila"> La Casa Mil#</a></h2> <p>If you walk down ... Dom (nec i Muntaner's <a href="lleomorera.html"> Casa Lle* i Morera </a>to Puig i Cadalfach's <a href="amatller.html"> Casa Amatller</a>. But there is ... </p>
<p>One of the things ... real people live there. (OK, <span class="emph"> rich</span> people live there.) Originally built ... </p>
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!
h1, h2 {font-family: "Arial Black", "Helvetica Bold", sansserif} p {font-family: "Verdana", "Helvetica", sans-serif }
Figure 10.3. On this system, both first choices, Arial Black and Verdana, were available.
Tips
Surround multi-word font names with quotes (single or double). You can specify fonts for different alphabets in the same font-family rule (say, Japanese and English) to format a chunk of text that contains different languages and writing systems. Common fonts on Windows systems are Times New Roman and Arial. Most Macs have Times and Helvetica available. You can use the following generic font names serif, sans-serif, cursive, fantasy, and monospace as a last ditch attempt to influence which font is used for display. You can set the font family, font size, and line height all at once, using the general font property (see page 165). The font-family property is inherited.
@font-face {font-family: "Sunnyside"; src: url(SUNNYSI0.eot)} h1, h2 {font-family: "Sunnyside" , "Helvetica Bold"} p {font-family: "Verdana", "Helvetica", sans-serif}
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.
Tips
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.
h1, h2 {font-family: "Arial Black", "Helvetica Bold", sansserif} p {font-family: "Verdana", "Helvetica", sans-serif} .emph {font-style: italic }
Figure 10.7. Any elements in the emph class (like the word never in the third full paragraph above) will be displayed in italics.
Tips
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.
h1, h2 {font-family: "Arial Black", "Helvetica Bold", sansserif;font-weight: normal } p {font-family: "Verdana", "Helvetica", sans-serif} .emph {font-style: italic; font-weight:bold } a:link, a:hover { font-weight:bold }
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.
Tips
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.
There are two basic ways to set the font size for the text in your Web page. You can mandate that a specific size be used or you can have the size depend on the element's parent.
h1, h2 {font-family: "Arial Black", "Helvetica Bold", sansserif;font-weight: normal} h1 {font-size: 20px } h2 {font-size: 14px } p {font-family: "Verdana", "Helvetica", sans-serif; fontsize:12px } .emph {font-style: italic; font-weight:bold} a:link, a:visited, a:hover {font-weight:bold} #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.
Tips
See page 44 for details about units. There shouldn't be any spaces between the number and the unit. The average pixel is about 1/80th of an inch high (1/32 cm), though it depends on the screen resolution. Imagine a 17" monitor, whose screen is roughly 12.5" wide, with a resolution of 1024 x 768. At that resolution, text at 16 pixels would be about 1/5 of an inch high (about 1/2cm). Pixels are probably the most popular sizing unit. They give the designer control over the text size and, except in Internet Explorer for Windows, the visitor can resize the text when needed with their browser's Text Size (or Zoom) option. Only use points, cm, mm, or picas in style sheets that format printed output (see page 197).
Different browsers interpret the keywords in different ways. Explorer 5.x uses small as its base size while IE 6, Opera, and Netscape use medium. It's not worth the hassle to me. The font-size property is inherited.
h1, h2 {font-family: "Arial Black", "Helvetica Bold", sansserif;font-weight: normal} h1 {font-size: 1.25em } h2 {font-size: .875em } p {font-family: "Verdana", "Helvetica", sans-serif; fontsize:75%} .emph {font-style: italic; font-weight:bold} a:link, a:hover {font-weight:bold} #toc {font-size:75% }
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.
Tips
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.
If you use a percentage or em value, it is the resulting size (not the factor) that is inherited.
h1, h2 {font-family: "Arial Black", "Helvetica Bold", sansserif;font-weight: normal} h1 {font-size: 20px} h2 {font-size: 14px} p {font-family: "Verdana", "Helvetica", sans-serif; fontsize:12px; line-height:150% } .emph {font-style: italic; font-weight:bold} a:link, a:hover {font-weight:bold} #toc {font-size:12px}
Figure 10.15. Spacing out the lines makes them easier to read.
Tips
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).
If you use a percentage or em value, only the resulting size (or "computed value") is inherited. So, given a parent at 16 pixels with a line height of 150%, the parent's line height will still be 24 pixels. However, all child elements will also inherit a line height of 24 pixels, regardless of their font size.
h1, h2 {font: 20px "Arial Black", "Helvetica Bold", sansserif} h2 {font-size:14 px} p {font: 12px/150% "Verdana", "Helvetica", sansserif} .emph {font-style: italic; font-weight:bold} a:link, a:hover {font-weight:bold} #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).
Tips
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.
h1, h2 {font: 20px "Arial Black", "Helvetica Bold", sansserif; 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}
Figure 10.19. The headers are navy blue, the text is light purple, and the links are pink, but turn blue when hovered on.
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%. 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.
The background refers not to the background of the entire page, but to the background of the specified element. In other words, you can change the background of just a few paragraphs or words, by setting the background of those words to a different color.
body {background:#9cf } h1, h2 {font: 20px "Arial Black", "Helvetica Bold", sansserif; 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.
Tips
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 fontsize of 20px will mean an additional 5 pixels between each letter).
[View full width]
body {background:#9cf} h1, h2 {font: 20px "Arial Black", "Helvetica Bold", sansserif; color:navy; letter-spacing:0.4em } 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.23. I rather like the effect of spaced out headers.
Tips
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.
Adding Indents
You can determine how much space should precede the first line of a paragraph.
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).
[View full width]
body {background:#9cf} h1, h2 {font: 20px "Arial Black", "Helvetica Bold", sansserif; color:navy; letter-spacing:.4em} h2 {font-size: 14px} p {font: 12px/150% "Verdana", "Helvetica", sansserif; color:#909; text-indent:1.5em } .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.25. Each paragraph is indented 18 pixels.
Tips
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.
Use a value of 0 to remove an inherited indent. For example, you might want to create a special class for the first paragraph in each section and set its text indent to 0.
body {background:#9cf} h1, h2 {font: 20px "Arial Black", "Helvetica Bold", sansserif; color:navy; letter-spacing:.4em} h2 {font-size: 14px} p {font: 12px/150% "Verdana", "Helvetica", sansserif; color:#909;text-indent:1.5em} .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; whitespace: nowrap}
Figure 10.27. The table of contents line won't wrap, even when the browser window is too narrow to display the entire line.
Tips
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 .
Aligning Text
You can set up certain (X)HTML elements to always be aligned to the right, left, center, or justified, as desired.
To align text:
1. Type text-align:. 2. Type left to align the text to the left. Or type right to align the text to the right. Or type center to center the text in the middle of the screen. Or type justify to align the text on both the right and left. Figure 10.28 Don't forget the hyphen in text-align .
[View full width]
body {background:#9cf} h1, h2 {font: 20px "Arial Black", "Helvetica Bold", sansserif; color:navy; letter-spacing:.4em; text-align: center } h2 {font-size: 14px} p {font: 12px/150% "Verdana", "Helvetica", sansserif; color:#909;text-indent:1.5em; text-align: justify } .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; whitespace:nowrap; text-align: center}
Figure 10.29. The table of contents and headers are centered while the paragraph text is justified.
Tips
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.
You can define the text case for your style by using the text-transform property. In this way, you can display the text either with initial capital letters, in all capital letters, in all small letters, or as it was typed.
body {background:#9cf} h1, h2 {font: 20px "Arial Black", "Helvetica Bold", sansserif; color:navy; letter-spacing:.4em; textalign:center} h1 {text-transform:uppercase} h2 {font-size: 14px} p {font: 12px/150% "Verdana", "Helvetica", sansserif; color:#909;text-indent:1.5em; textalign:justify} .emph {font-style: italic; font-weight:bold}
Figure 10.31. Now the header really stands out.
Tips
I'm unimpressed with the capitalize value. While I sometimes need to capitalize all the important words in a sentence, or even just the first word in a sentence, I am hard pressed to think of an example where I'd need to capitalize everything. Now, a true headline-style capitalization property would be welcome. Of course it would have to be language dependent. The lowercase value can be useful for creating stylish headers (or if you're e.e. cummings). The text-transform property is inherited.
Many fonts have a corresponding small caps variant that includes uppercase versions of the letters proportionately reduced to small caps size. You can call up the small caps variant with the font-variant property.
body {background:#9cf} h1, h2 {font: 20px "Arial Black", "Helvetica Bold", sansserif; color:navy; letter-spacing:.4em; textalign:center} h1 {text-transform:uppercase} h2 {font-size: 14px; font-variant:small-caps } p {font: 12px/150% "Verdana", "Helvetica", sansserif; color:#909;text-indent:1.5em; textalign:justify} .emph {font-style: italic; font-weight:bold}
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. Figure 10.33. Notice how different these three versions of small caps are, even on the same computer with the same fonts installed. On top you see Explorer 6 for Windows, which I believe reduces the uppercase letters for a fake small caps effect. The two bottom browsers, Netscape and Opera, show true, or at least more attractive, small caps.
Decorating Text
Style sheets let you adorn your text with underlines, overlining, lines through the text (perhaps to indicate changes), and even blinking text.
To decorate text:
1. Type text-decoration: . 2. To underline text, type underline. Or, for a line above the text, type overline. Or, to strike out the text, type line-through. Or to make the text appear and disappear intermittently, type blink.
[snip] a:link {font-weight:bold; color:#cc00ff; textdecoration:none } a:visited {font-weight:normal; color:#cc00ff; textdecoration:none } a:hover {font-weight:bold; color: #0000ff; textdecoration:underline } #toc {font-size:12px; color:#cc00ff; background:#ccc; whitespace:nowrap; textalign: center}
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.
Tips
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).
<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.
Note that some layout properties, particularly em and percentage values, depend on an element's parent. Remember that a parent is the element that contains the current element (see page 28) . 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.
Tips
Netscape 6 is so scrupulous with standards that it adds a bit of space under inline images in table cells for descenders, one must presume. As long as you only have one image per cell, you can get rid of the space by making the images block level. If you use display: none, no trace remains of the hidden element in the browser window. There is no empty space. The display property is not inherited. You can use visibility:hidden to hide elements without taking them out of the flow. In other words, the space they would have occupied remains behind.
flow. You can take elements out of the normal flow and position them absolutely by specifying their precise position with respect to their parent element.
#bg {position: absolute; top: 250px; left: 2%; } #content {position: absolute; top: 0px; left: 30%; } #navigation { position: absolute; top: 10px; left: 2%; } #navigation a {display: block}
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.
Tips
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.
#bg {position: fixed; top: 250px; left: 2%; } #content {position:absolute; top: 0px; left: 30%; } #navigation { position: fixed; top: 10px; left: 2%; } #navigation a {display: block}
Figure 11.11. At first glance, this page looks identical to the one shown in Figure 11.9 on page 179.
Figure 11.12. When the visitor scrolls down, however, notice that the navigation area (Catalonia, Home, Barcelona, etc.) and the background image remain stationary.
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.
Unfortunately, Explorer for Windows (up to and including version 6) does not support fixed positioning. Positioning is not inherited.
#bg {position: absolute; top: 250px; left: 2%;} #content {position:absolute; top: 0px; left: 30%;} #navigation {position: absolute; top: 10px; left: 2%} #navigation a {display: block} h2, h3 {position:relative; left:-25px }
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.
Tips
The "relative"in relative positioning refers to the element's original position, not the surrounding elements. You can't move an element with respect to other elements. Instead, you move it with respect to where it used to be. Yes, this is important! The other elements are not affected by the offsets they flow with respect to the original containing box of the element, and may even be overlapped. Offsets don't work unless you're also using the position property. Positioning is not inherited.
Figure 11.15 We make the background of the body, the content division and hovered navigational links white. We set the background of the bg division to black (in anticipation of the changes on pages 190"192). We set the hover color for the current page's link to transparent since we don't want it to look like a link.
body {background-color:#fff; } #bg {position: absolute; top: 250px; left: 2%; background-color:black } #content {position:absolute; top: 0px; left: 30%; background-color:#fff } #navigation {position: absolute; top: 10px; left: 2%} #navigation a {display: block} #navigation a:hover { background-color:#fff; } #navigation a:hover.current { backgroundcolor:transparent } 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).
2. Then type url(image.gif), where image.gif is the name of the image that should be used for the background, or none to use no image at all (Figures 11.17 and 11.18). Figure 11.17 We'll make a momentary digression to show background images, which are difficult to use effectively.
body {background:white url(img/castle_bg.jpg) repeat-x bottom left } #bg {position: absolute; top: 250px; left: 2%; backgroundcolor:black} #content {position:absolute; top: 0px; left: 30%; background-color:#fff} #navigation {position: absolute; top: 10px; left: 2%} #navigation a {display: block} #navigation a:hover {background-color:#fff;} #navigation a:hover.current {background-color:transparent} 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).
1. Type background: 2. Specify any of the accepted background property values (as described on the preceding page), in any order.
Tips
The default for background-color is transparent . The default for background-image is none. The default for backgroundrepeat is repeat. The default for background-attachment is scroll. The default for background-position is top left. When using the background shortcut property (above), you needn't specify all of the properties. But beware that any non-specified properties are set to their defaults (and thus may override earlier style rules). The background properties are not inherited. You only need to explicitly set default values like transparent or scroll when you want to override another style rule. If you use the background-position property with a repeat, the position specifies where the first image in the repeat starts, e.g., from the top right. Set the background property for the body element to create a background for the entire page. (It's the only way Netscape 4 will apply a background property.) If you specify both a color and a URL for the background, the color will be used until the URL is loaded, and will be seen through any transparent portions of the background image. (If you don't specify a color, Netscape 4 will use black.)
body {background-color:#fff; color:#000} #bg {position: absolute; top: 250px; left: 2%; backgroundcolor:black} #content {position: absolute; top: 0px; left: 30%; background-color:#fff} #navigation {position: absolute; top: 10px; left: 2%; color:white } #navigation a {display: block} #navigation a:link.current, #navigation a:visited.current, {color:#ff9 ;} #navigation a:hover {background-color:#fff; color:#339} #navigation a:hover.current {background-color: transparent; color:#ff9} h1 {background-color: #339; color: #fff }
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%.
The color property is most often used to affect text. For more information, consult Setting the Text Color on page 166. Changing the foreground color of an image doesn't have any effect. (You'll have to do that in an image editing program.) You can, however, change the background color (that is, what will appear through transparent areas). For more information, consult Changing the Background on page 182.
Or type auto to get whatever cursor usually appears in that situation. 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?
body {background-color:#fff; color:#000} #bg {position: absolute; top: 250px; left: 2%; backgroundcolor:black} #content {position: absolute; top: 0px; left: 30%; background-color:#fff} #navigation {position: absolute; top: 10px; left: 2%; color:white} #navigation a {display: block} #navigation a:link.current, #navigation a:visited.current, {color:#ff9;} #navigation a:hover {background-color:#fff; color:#339} #navigation a:hover.current {background-color: transparent; color:#ff9; cursor: default } h1 {background-color: #339; color: #fff}
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).
Tips
IE 5.x for Windows recognizes the hand value, but not the standard ). 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-style: type , where type is none, dotted, dashed, solid, double, groove, ridge, inset, or outset.
body {background-color:#fff; color:#000} #bg {position: absolute; top: 250px; left: 2%; backgroundcolor:black} #content {position:absolute; top: 0px; left: 30%; background-color:#fff; border-left: 1px solid black } #navigation {position: absolute; top: 10px; left: 2%; color:white} #navigation a {display: block} #navigation a:link.current, #navigation a:visited.current, {color:#ff9;} #navigation a:hover {background-color:#fff; color:#339} #navigation a:hover.current {background-color: transparent; color:#ff9; cursor: default } h1 {background-color: #339; color: #fff}
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).
div {height: 70px; width: 200px; margin-bottom: 10px; background: #ffc; border-color: #c06; border-width: 2px 5px 10px 15px} .dotted { border-style: dotted } .dashed { border-style: dashed none } .double { border-style: none double } .groove { border-top-style: groove} .ridge {border-right-style: ridge }
Tips
Borders are not inherited. The individual border properties (border-width , border-style, and border-color ) can have from one to four values. If you use one value, it is applied to all four sides. If you use two, the first is used for the top and bottom, and the second for the right and left. If you use three, the first is used for the top, the second for the right and left, and the third is used for the bottom. And if you use four, they are applied to the top, right, bottom, and left, in clockwise order. You must define at least the style for a border to display. If there's no style, there will be no border. The default is none. If you use a shortcut, like border or border-left (etc.), the properties you don't give values for are set to their defaults. So border: 1px black means border: 1 px black none , which means you won't get a border (even if you specified a style earlier with border-style). The default color is the value of the element's color property (see page 166) . The width can also be expressed in generic terms: thin, medium, and thick. The default is medium, which for IE is 4 pixels and for Netscape is 3. Older browsers (before IE 5.5 and Netscape 6) don't support every single border style. The border property can be used for tables and their cells. For more details, consult Adding a Border on page 218. Frankly, I think someone went a bit over the top in thinking up different ways of setting the border properties.
body {background-color:#fff; color:#000; padding:0; } #bg {position: absolute; top: 250px; left: 2%; backgroundcolor:black} #content {position:absolute; top: 0px; left: 30%; background-color:#fff;border-left: 1px solid black; padding: 20px; }
#navigation {position: absolute; top: 10px; left: 2%; color:white} #navigation a {display: block;color:#fff; padding-left: 10px; padding-right: 10px; } #navigation a:link.current, [snip] h1 {background-color: #339; color: #fff; padding: 0 10px }
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.
Use percentages or ems to create liquid layouts that expand or contract depending on the visitor's monitor.
body {background-color:#fff;color:#000;padding:0 0 0 0;margin:0 0 0 0 } #bg {position: absolute; top: 250px; left: 2%; backgroundcolor:black} #content {position:absolute; top: 0px; left: 30%; background-color:#fff;border-left: 1px solid black; padding: 20px} #navigation [snip] h1 {background-color: #339; color: #fff; padding: 0 10px; margin-top:10px } h2 {margin:0} h3 {margin: 15px 0 0 0 } p {margin: 5px 0 }
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).
Tips
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.
Type width: w, where w is the width of the element's content area, and can be expressed either as a length (with units) or as a percentage of the parent element. Or use auto to let the browser calculate the width. Type height: h, where h is the height of the element, and can be expressed only as a length (with units). Or use auto to let the browser calculate the height.
Figure 11.31 Remember that in the (X)HTML code, we set the width of the image in the bg area to 100 pixels.
body {background-color:#fff;color:#000;padding:0 0 0 0;margin:0 0 0 0} #bg {position: absolute; top: 250px; left: 2%; backgroundcolor:black; top:0; left:10%; marginleft:-200px;} #bg img { width:538px; height:850px; } #content {position:absolute; top: 0px; left: 30%; background-color:#fff;border-left: 1px solid black; padding: 20px; } #navigation {position: absolute; top: 10px; left: 2%; color:white; width: 26%} #navigation a {display: block;color:#fff; padding-left: 10px; padding-right: 10px;}
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.
Tips
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.
If you manually set the width, margin-left , and margin-right values, but together with the border and padding they don't equal the size of the containing block, something's got to give. And indeed, the browser will override you and set margin-right to auto (Figures 11.34 and 11.35). If you manually set the width but set one of the margins to auto, then that margin will stretch or shrink to make up the difference. If you manually set the width but leave both margins set to auto, both margins will be set to the same maximum value (resulting in your element being centered). 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.
div {width:300px; height: 500px; background: yellow} p.auto { width:auto; margin: 10px; padding: 5px; border: 5px solid blue; background: white;} p {width: 200px; margin: 10px; padding: 5px; border: 5px solid purple; background: white;}
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.
Note that browsers never adjust the width of the borders or the padding. 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.
body {background-color:#fff; color:#000;padding:0 0 0 0;margin:0 0 0 0} #bg {position: absolute; top: 250px; left: 2%; backgroundcolor:black; top:0; left:10%; marginleft:-200px; z-index: 1;} #bg img {width:538px; height:850px;} #content {position:absolute; top: 0px; left: 30%; background-color:#fff;border-left: 1px solid black; padding: 20px; z-index: 2; } #navigation {position: absolute; top: 10px; left: 2%; color:white; width: 26%; z-index: 3;} #navigation a {display: block;color:#fff; padding-left: 10px; padding-right: 10px;}
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!
Tips
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.
positioning. Regardless of the cause, you can control the area outside of the element's box with the overflow property.
#calendar {background:#339; color:white; padding:5px; margin-left:5px; margin-top:7px; font-size:.8em; width:150px;} #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.
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.
Figure 11.42 We want the entire calendar division to float to the right of the paragraph.
[View full width]
#content {position:absolute; top: 0px; left: 30%; background-color:#fff;border-left: 1px solid black; padding: 20px; z-index: 2;} #calendar {background:#339; color:white; padding:5px; margin-left:5px; margin-top:7px; font-size:.8em; width:150px; float: right }
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.
<h3>The Competition</h3> <img src="img/anxaneta.jpg" alt="Anxaneta" width="39" height="72" class="icon" /> <div id="calendar">
Figure 11.45. Since the little image comes first in the (X)HTML, it gets floated farthest to the right.
Non-replaced elements without an explicit width will not float properly. The float property is not inherited.
solid black; padding: 20px; z-index: 2;} #calendar {background:#339; color:white; padding:5px; margin-left:5px; margin-top:15px; font-size:.8em; width:150px; float: right; clear:right } #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) .
You can align elements in many different ways to make them look neater on the page.
body {background-color:#fff;color:#000;padding:0 0 0 0;margin:0 0 0 0} #bg {position: absolute; top: 250px; left: 2%; backgroundcolor:black; top:0; left:10%; margin-left:-200px; z-index: 1;} #bg img {width:538px; height:850px} #content {position:absolute; top: 0px; left: 30%; background-color:#fff;border-left: 1px solid black; padding: 20px; z-index: 2;} img.line {vertical-align: top ;}
Figure 11.49. The top edges of the three line class images are aligned.
<head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>Red and Louis</title> <link rel="stylesheet" media="screen" type="text/css" href="screen.css" /> <link rel="stylesheet" media="print" type="text/css" href="print.css" /> </head> <body> <div id="story"> <h1>Red and Louis</h1>
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>
<meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>Red and Louis</title> <link rel="stylesheet" media="screen" type="text/css" href="screen.css" /> <style type="text/css"> @import "print.css" print; </style> </head> <body> <div id="story"> <h1>Red and Louis</h1>
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.3. In a screen version, you might have a table of contents sidebar, some ads, and sans-serif fonts (which tend to be easier to read 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.
Tips
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-inside: avoid. Figure 12.5 I don't want paragraphs to be divided between pages so I use pagebreak-inside:avoid . So that each second level header starts on its own page, I add page-break-before:always to the h2 tags.
Tips
The page-break-before and page-break-after properties theoretically accept values of left and right (to make pages start on the left or right side, respectively), but those values are currently not supported on any browser. The default value for all of the page-break properties is auto. Only pagebreak-inside is inherited. Currently, page breaks before and after elements are supported by Internet Explorer and Opera, though Explorer does not seem to understand the avoid value. Mozilla is rumored to have some support but Netscape 6 does not. Only Opera understands page-break-inside .
CSS offers a number of other features that help control how Web pages are printed. Unfortunately, only widows and orphans are supported, and only by Opera. I'll give you a quick synopsis, nonetheless.
@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}
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.
If desired, in the style rule, type widows: n;, where n is the minimum number of lines in the element that should appear at the top 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).
Tips
Only Opera supports the orphans and widows properties. It's a shame that these features are not better supported by other browsers. However, things move so quickly that perhaps by the time you read this, things will have improved. Note that the better-supported page-break-inside property can also help avoid stranded lines. See page 200.
Figure 13.1 There is no official way to format a list's title. You can use a regular header (see page 65).
[View full width]
<body> <p>Ordered lists are the most common kinds of lists, perfect for explaining step by step instructions or for giving an outline (complete with links to the corresponding sections, if desired) for a larger document. <h1>Changing a light bulb</h1> <ol> <li>Make sure you have unplugged the lamp from the wall socket.</li> <li>Unscrew the old bulb.</li>
<li>Get the new bulb out of the package.</li> <li>Check the wattage to make sure it's correct.</li> <li>Screw in the new bulb.</li> <li>Plug in the lamp and turn it on!</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.
[View full width]
<body> 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. <h1>PageWhacker, version 12.0--Features</h1> <ul> <li>New or improved features marked with a solid bullet.</li> <li>One click page layout</li> <li>Spell checker for 327 major languages</li> <li>Image retouching plug-in</li> <li>Special HTML filters</li> <li>Unlimited Undo's and Redo's</li> <li>Automatic book writing</li> </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). Figure 13.4. Unordered lists have round, solid bullets by default.
Keep the text in your list items short. If you have more than a few lines of text in each item, you may have better luck using headers (h1, h2, etc.) and paragraphs (p). Inserting a line break (br) in a list item breaks the text to the next line, but maintains the same indenting. No text is permitted between the opening ol or ul tag and the first li tag. Nevertheless, browsers will display such text with the same indentation as the first item in the list, but without a bullet. The ul tag is often used for indentation, though this is considered a hack from the pre-standards era. You may create one list inside another, even mixing and matching ordered and unordered lists. Be sure to nest each list properly, using all the required opening and closing tags. Lists are automatically indented from the left margin (40 pixels is typical for the default 16 pixel size text). If you use CSS to style your lists, changing or reducing the left margin may make your bullets disappear beyond the left edge of the window.
<body> <h1>The Great American Novel</h1> <ol> <li>Introduction</li> <li>Development</li> <li>Climax</li> <li>Denouement</li> <li>Epilogue</li>
</ol> </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.
<body> <h1>Changing a light bulb</h1> <ol start="2"> <li>Unscrew the old bulb. <p>some omitted steps here</p></li> <li value="5">Screw in the new bulb.</li> <li>Plug in the lamp and turn it on!</li> </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.
Tips
By default, all lists start at 1. The value attribute overrides the start value. When you change a given list item's number with the value attribute, the subsequent list items are also renumbered accordingly. Unfortunately, the W3C has deprecated both the start and value attributes without offering a CSS alternative. If you need them, just be sure to use the proper (transitional) DOCTYPE (see pages 38 and 60). The start value is always numeric regardless of the numbering scheme. For more on choosing number styles for markers, see page 206.
<ul> <li>New or improved features marked with a solid bullet.</li> <li class="new">One click page layout</li> <li>Spell checker for 327 major languages</li> <li>Image retouching plug-in</li> <li>Special HTML filters</li> <li>Unlimited Undo's and Redo's</li> <li class="new">Automatic book writing</li> </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.
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 liststyle-type is used. The custom markers are inherited.
<ul> <li>New or improved features marked with a solid bullet.</li> <li class="new">One click page layout. This is particularly useful when you're under a heavy deadline. You just select whether you want the end product to be a book or a Web site, and poof, it's done.</li> <li>Spell checker for 327 major languages</li> <li>Image retouching plug-in</li> <li>Special HTML filters</li> <li>Unlimited Undo's and Redo's</li>
Figure 13.14 I've added the inside list-style position to the style sheet rule shown in Figure 13.11 on page 208.
Tips
Markers are hung outside the list paragraph, by default. The list-style-position property is inherited.
3. If desired, specify the custom marker that should be used for list items (as described on page 208). 4. If desired, specify whether markers should be hung outside the list paragraphs or flush with the text (as described on page 209). 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 liststyle-type to square. It's just shorter.
[View full width]
Tips
You may specify any or all of the three liststyle properties. You might think that by omitting one of the three properties, you won't be affecting it, but that's not always the case. Any properties not explicitly set are returned to their defaults (disc for list-style-type , none for list-styleimage, and outside for list-style-position ). The properties may be specified in any order. The list-style property is inherited.
4. Type the word or short phrase that will be defined or explained, including any logical or physical formatting desired. 5. Type </dt> to complete the definition term. 6. Type <dd>. 7. Type the definition of the term that was entered in step 4. 8. Type </dd> to complete the definition. 9. Repeat steps 3!8 for each pair of terms and definitions. 10. Type </dl> to complete the list of definitions. Figure 13.19 Each entry word is labeled with the dt tag, while the definition itself is labeled with a dd tag.
[View full width]
<h1>Classical Greek Verb Tenses</h1> <dl> <dt>Present</dt> <dd><span class="example">e.g. .luo, luomai</span>. The present usually shows the pure verb stem in verbs with strong stems. [snip]</dd> <dt>Future</dt> <dd><span class="example">e.g. luso, lusomai, luthesomai</span>. The future has the[snip]</dd> <dt>Aorist</dt> <dd><span class="example">e.g. .elusa, eluthen, elusamen</span>. The aorist (from [snip]</ dd> </dl>
Figure 13.20 You may want to add formatting to your definition term to help it stand out.
Tips
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.
1. For styling the outermost list, type toplevel li {style_rules}, where toplevel is the list type of the outermost list (e.g., ol, ul, dt) and style_rules are the styles that should be applied. 2. For the second level list, type toplevel 2ndlevel li {style_rules}, where toplevel matches the toplevel in step 1 and 2ndlevel is the list type of the second level list. 3. For the third level list, type toplevel 2ndlevel 3rdlevel li {style_rules}, where toplevel and 2ndlevel match the values used in steps 1!2 and 3rdlevel is the kind of list used for the third nested list. 4. Continue in this fashion for each nested list that you wish to style. 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).
<h1>The Great American Novel</h1> <ol> <li>Introduction <ol> <li>Boy's childhood</li> <li>Girl's childhood</li> </ol> </li> <li>Development <ol> <li>Boy meets Girl</li> <li>Boy and Girl fall in love</li> <li>Boy and Girl have fight</li> </ol> </li> <li>Climax <ol> <li>Boy gives Girl ultimatum <ol> <li>Girl can't believe her ears</li> <li>Boy is indignant at Girl's indignance</li> </ol> </li> <li>Girl tells Boy to get lost</li> </ol> </li> <li>Denouement</li> <li>Epilogue</li> </ol>
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 ol ol li
li ol ol li
Figure 13.24. The first level lists (ol li) have capital Roman numerals. The second level lists (ol ol li ) have capital letters, and the third level lists (ol ol ol li) have Arabic numerals.
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 {fontsize:100%}. Now nested list items will always be the same size as top level ones. (Thanks to Eric Meyer.)
6. Finally, create or insert the content. 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.
1. Type <table>. 2. Type <tr> to define the beginning of the first row. If desired, press Return and Tab to visually distinguish the row elements. 3. Type <td> to define the beginning of the cell. 4. Type the contents of the cell. 5. Type </td> to complete the cell. 6. Repeat steps 3!5 for each cell in the row. 7. Type </tr> to complete the row. 8. Repeat steps 2!7 for each row. 9. To finish the table, type </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.
[View full width]
<table> <tr><td><img src="elephant.jpg" width="200" height="150" alt="Elephant Baby"> </td></tr> <tr><td class="caption"> A baby elephant hanging out with its mom, aunts and great-aunts, and maybe even its grandmother </td></tr> </table>
Figure 14.4 The style sheet contains only pure text formatting; nothing that would affect the table per se.
Figure 14.6. Here's the exact same table in a narrower browser window. The table simply contracts to fit better in the 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
page, th is not very useful. On the other hand, if you're organizing tabular data, header cells can help describe your table and make it more accessible. You can create a title for the table with the caption element. Use align= "direction" , where direction is top, bottom, left, or right to align the caption. It's ugly and not well supported.
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.
<table border="10"> <tr><td><img src="elephant.jpg" width="200" height="150" alt="Elephant Baby"></td></tr> <tr><td class="caption">A baby elephant hanging out with its mom, aunts and great-aunts, and maybe even its grandmother</td></tr> </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.
Figure 14.9 You can specify the width, color, and style with the single shortcut border property.
Figure 14.11. This page uses the same CSS as the previous illustration (Figure 14.10), but no border attribute in the (X)HTML. Notice that there are no borders around the cells.
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 (nondeprecated) (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.
browser window, no matter what size the visitor makes it. It's also quite common to specify the width of the navigational column in pixels so that it is not affected by the ebb and flow of browser size. 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.
<table border=0 width="200" class="rightsidebar"> <tr><td><img src="elephant.jpg" width="200" height="150" alt="Elephant Baby"></td></tr> <tr><td class="caption">A baby elephant hanging out with its mom, aunts and great-aunts, and maybe even its grandmother</td></tr> </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.)
Figure 14.16 In this case, the table is made narrower than the image it contains.
Figure 14.18 In this case, the table is made wider than the image it contains.
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.
Netscape 4.x doesn't recognize the CSS width property. You'll have to use the (X)HTML width attribute instead.
Tips
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.
<h1>The Truth about Elephants</h1> <table border=0 width="200" class="rightsidebar" align="right" > <tr><td><img src="elephant.jpg" width="200" height="150" alt="Elephant Baby"></td></tr> <tr><td class="caption">A baby elephant hanging out with its mom, aunts and great-aunts, and maybe even its grandmother</td></tr> </table>
<p>It's hard to tell what goes through a baby elephant's mind when its mom is trying to put it to sleep. Do you think baby elephants wake up in the
Figure 14.24 You must specify a width when using the float property.
Tips
For more details about floating elements, see pages 110 and 194. For more details on controlling where elements float, see pages 112 and 195. The CSS float property is not supported by Netscape 4.x or earlier or Explorer 3 or earlier. The right and left values for the align attribute have been deprecated, though they continue to enjoy broad support. You can use one system or both, depending on how well supported or how standard you want your code to be.
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.
<table width="100%" border="1"> <tr><td><!-- Left Navigation --></td> <td><!-- Main Content --> <h1>The Truth about Elephants</h1> <table border=0 width="200" class="rightsidebar" align="right"> <tr><td><img src="elephant.jpg" width="200" height="150" alt="Elephant Baby"></td></tr>
<tr><td class="caption">A baby elephant hanging out with its mom, aunts and great-aunts, and maybe even its grandmother</td></tr> </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
independent tables. I link the two tables visually by ensuring that the width of the first column in each is the same (shown here in bold).
<!-- Top Logo Bar --> <table width="100%"> <tr><td ><img src="logo.jpg" width="120" alt="Northampton Zoo Logo"></td> <td><img src="ad2.gif" width="320" alt="main ad" ></td> <td><img src="miniad.jpg" width="160" height="100" alt="mini ad" ></td></tr></table> <!--Left Nav and Main Content --> <table width="100%"> <tr> <!-- Left Navigation --> <td class="toc"><img src="spacer.gif" alt="" width="120" height="1"> <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.
Tips
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.
<table width="100%" border="0"> <tr><td ><img src="logo.jpg" width="120" alt="Northampton Zoo Logo"></td> <td align="center"><img src="ad2.gif" width="320" alt="main ad" ></td>
<td align="right" ><img src="miniad.jpg" width="160" height="100" alt="mini ad"></td></tr></table> <table width="100%"> <tr> <!-- Left Navigation --> <td class="toc" valign="top" ><img src="spacer.gif" alt="" width="120" height="1"> <p><a href="lions.html">Lions</a> <br /><a href="armadillos.html">Armadillos</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).
[View full width]
h1 {font: bold 1.8em/1em "comic sans", "verdana", sans-serif;white-space:nowrap} .rightsidebar {width:200px;float:right} .caption {font-size:.8em;font-style:italic; fontfamily:"verdana", sans-serif; text-align: center} .toc {font-family:"verdana", sans-serif; verticalalign:top } [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).
Figure 14.33. Notice how the middle cell in the top row stays centered even though the window is bigger. Perhaps more important, the right-hand cell (with the lion) stays aligned to the right, flush with the elephant picture and the rest of the text.
Tips
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.
looks like it stretches with the browser window. And I've added a dark green background to the left navigation bar.
[View full width]
<body text="#006666" bgcolor="white"> <table width="100%" border="0" class="logobar" bgcolor="#ffff66"> <tr><td ><img src="logo.jpg" width="120" alt="Northampton Zoo Logo"></td> <td class="center"><img src="ad2.gif" width="320" alt="main ad" ></td> <td class="right"><img src="miniad.jpg" width="160" height="100" alt="mini ad" ></td></ tr></table> <table width="100%"> <tr> <!-- Left Navigation --> <td class="toc" bgcolor="#339966"> <img src="spacer.gif" alt="" width="120" height="1">
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).
Figure 14.36 In this example, I've created all the background colors with CSS instead of (X)HTML. In addition, I've added a background image for the left navigation bar.
[View full width]
body {color:#006666; background:white} h1 {font: bold 1.8em/1em "comic sans", "verdana", sansserif;white-space:nowrap} .rightsidebar {width:200px; float:right; background:#006666; color:white} .caption {font-size:.8em; font-style:italic; fontfamily:"verdana", sans-serif; textalign: center;color:white} .toc {background: #339966 url(longerfish.jpg);fontfamily:"verdana", sans-serif;vertical-align:top} [snip] .logobar {background:#ffff66 }
Figure 14.37. Is the space around the cells bugging you yet? We're getting there next!
Tips
The CSS background property is described in detail on pages 182!183. This section is devoted to explaining its peculiarities with respect to tables. The CSS background property with a color value is well supported, all the way back to IE and Netscape 3. Background images are supported back to version 4 of both browsers. The bgcolor attribute is deprecated in HTML 4. The background attribute for the table tag was never even officially a part of the HTML 4 specification. (It's been deprecated as an attribute to the body tag.). The W3C would prefer you use the CSS background property. Nevertheless, both bgcolor and background continue to be well supported. You can add the bgcolor attribute to any table tag (table, tr, thead, etc.) to change the color of the cells in one or more rows or columns at once. The bgcolor attribute in an individual cell (th or td) overrides the color specified in a row (in a tr tag), which in turn overrides the color specified for a group of rows or columns (in thead, colgroup , etc.), which, as you might expect, overrides the color specified for the entire table (in the table tag). Consult CSS Colors on page 46 and the inside back cover for help choosing colors.
You can add both a background image and a background color to a cell. The background color will both display before the image and then continue to shine through the transparent parts of the image, if there are any. If you set a background image for the whole table, beware! Netscape 4 copies the whole image into each cell individually instead of filling the entire table with a single image. You can also set the color of the contents of a cell. For information, consult Changing the Foreground Color on page 184. For information about changing the color of the borders, consult Adding a Border on page 218. Make sure that your background images do not distract from the content that is placed on top of them. I am continually amazed at how many sites use bizarrely busy backgrounds with text that is for all intents and purposes illegible.
Figure 14.39 I have set both the cellpadding and cellspacing to zero so that there is no extra space around or between the cells of my logo bar (and other elements).
<table width="100%" cellspacing="0" cellpadding="0" border="0" class="logobar" bgcolor="#ffff66"> <tr><td ><img src="logo.jpg" width="120" alt="Northampton Zoo Logo"></td>
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).
Figure 14.43 In this example, I use a combination of the padding, margin, border-spacing properties.
[View full width]
h1 {font: bold 1.8em/1em "comic sans", "verdana", sansserif;white-space:nowrap; margin:10px 0px 5px } p {margin:0px 0px 10px 0px } table, td { border-spacing:0 } .rightsidebar {width:200px; float:right; color:white; background:#006666; margin:0px 0px 5px 10px} .caption {font-size:.8em;font-style:italic;font-family:
"verdana", sans-serif;text-align:center; color:white; padding:5px;margin:0 } .toc {background: #339966 url(longerfish.jpg); fontfamily:"verdana", sans-serif; vertical-align:top; padding:25px 10px 0px }
Figure 14.44. The spacing looks much better now.
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.
[View full width]
<table width="100%" cellspacing="0" cellpadding="0" border="0"> <tr><!-- Left Navigation --> <td class="toc"><img src="spacer.gif" alt="" width="100" height="1">[snip]</td> <td> </td> <td class="top">
<h1>The Truth about Elephants</h1> [snip] mind, I could only find a picture of an elephant?)</p> </td></tr> <tr><td colspan="3" class="copyright"> Copyright © 2002 by Northampton Zoological Society, Inc. </td></tr> </table>
Figure 14.46. The new row spans all three columns.
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).
You can use the CSS margin property (see page 189) to control the spacing between h1 and p elements that may be contained in cells, or the space around a table. Remember that the CSS alternative to cellpadding is called padding , while the CSS alternative to cellspacing is called border-spacing . The padding property can be used on any element; border-spacing is just for table cells. The border-spacing property is inherited but padding is not. Netscape 6 is so scrupulous with standards that it adds a bit of space under inline images in table cells for descenders, one must presume. As long as you only have one image per cell, you can get rid of the space by making the images block level (see page 28) . Or you can trigger quirks mode (see page 39) . Netscape 4, on the other hand, is sloppy with returns and spaces. Don't put any carriage returns in table cells. Netscape 4 and up support the hspace and vspace attributes for the table element, which add extra space between the table and the text or elements next to it. Internet Explorer does not support these attributes. For more details, see page 113.
<table width="100%" cellspacing="0" cellpadding="0" border="0"> <tr><!-- Left Navigation --> <td class="toc" rowspan="2" ><img src="spacer.gif" alt="" width="100" height="1">[snip]</td> <td> </td> <td class="top"> <h1>The Truth about Elephants</h1> [snip] mind, I could only find a picture of an elephant?)</p>
</td></tr> <tr><td colspan="2" class="copyright"> Copyright © 2002 by Northampton Zoological Society, Inc.</td></tr>
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 .
<table width="100%" border="1"> <caption align=top>Bear sightings in Western Massachusetts</caption> <colgroup class="cities" /> <colgroup span="3" class="data" />
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 .
3. 4. 5. 6.
If desired, define the attributes for the column group. Type the final >. If desired, define individual columns as specified below with col. Type </colgroup>.
<table width="100%" border="1"> <caption align=top>Bear sightings in Western Massachusetts</caption> <colgroup class="cities" /> <colgroup span="3" class="data" > <col span="2"/> <col class="totals" /> </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.
<table width="100%" border="1"> <caption align=top>Bear sightings in Western Massachusetts</caption> <colgroup class="cities" /> <colgroup span="3" class="data" > <col span="2"/> <col class="totals" /> </colgroup> <thead class="titles"> <tr> <td> </td> <td>Babies</td>
Figure 14.57. Notice that Netscape does understand the horizontal section elements.
Tips
Both types of column group definitions are completely ignored by Netscape. Use colgroup when you want to determine where dividing lines (rules) should go. Use col for everything but deciding where dividing lines go. For more information on drawing dividing lines, consult page 239.
You can use many attributes to format column groups, including bgcolor , style, and others. You can divide column groups (colgroup) into columns (col) in order to add non-structural information (like size, alignment, or whatever) to individual columns within structural column groups. Simply type the col tag after the parent colgroup tag (Figure 14.52). Note that col tags' attributes override the attributes in the colgroup tag. If a column group is not divided into individual columns, you may combine the opening and closing tags: <colgroup span="3" /> . In HTML, the closing tag for colgroup is optional. The col element is always empty. In HTML you may omit the /. If the column group only contains one column, you don't need to use the span attribute. Its default is 1. Header cells those marked with the th tag are not affected by the alignment specified in a column group. For more information on aligning cells, consult Aligning a Cell's Contents on page 226.
Figure 14.58 Add the frame attribute within the table tag.
<table width="100%" border="1" frame="vsides"> <caption align=top>Bear sightings in Western Massachusetts</caption> <colgroup class="cities" /> <colgroup span="3" class="data" > <col span="2"/> <col class="totals" /> </colgroup> <thead class="titles"> <tr> <td> </td> <td>Babies</td>
Figure 14.59. With frame="vsides" , Explorer incorrectly shows not only the external vertical sides of the table, but also the vertical sides of the individual cells. You can work around that by setting rules to none (next page), but meanwhile it's a bug.
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.
void, for no external borders above, for a single border on top below, for a single border on bottom hsides, for a border on both the top and bottom sides vsides, for a border on both the right and left sides rhs, for a single border on the right side lhs, for a single border on the left side box or border, for a border on all sides (default)
none, for no internal rules rows, for horizontal rules between each row in the table cols, for vertical rules between each column in the table (Figures 14.61 and 14.62)
Figure 14.61 The rules attribute determines which internal borders should be displayed. In this example, we will show the column borders.
<table width="100%" rules="cols" > <caption align="top">Bear sightings in Western Massachusetts</caption> <colgroup class="cities" /> <colgroup span="3" class="data" >
Figure 14.62. Here we've got rules="cols" . Explorer again mistakenly shows the external border as well as the interior column rules.
Figure 14.63. When we specify frame="vsides" and rules="cols" , we get the desired effect: vertical external rules and vertical internal rules.
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.64. The attribute rules="groups" is particularly useful when you've divided the table into column and row groups (see pages 235"237). Instead of rules between each column, rules are only displayed between column groups.
all, for rules between each row and column in the table (default)
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.
<td>5</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
In HTML, but not XHTML, you can just type nowrap by itself. Browsers will make the cell (and the table that contains it) as wide as it needs to accommodate the single line of text even if it looks really ugly. I don't recommend using the nowrap tag with tables used for layout. It overrides the width attribute. You can use regular line breaks (br) between words to mark where you do want the text to break. You can also type instead of a regular space to connect pairs of words or other elements with non-breaking spaces. For more information on line breaks, consult Creating the Foundation on page 62, Keeping Lines Together on page 358, and Creating Discretionary Line Breaks on page 359.
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. Figure 14.68 The table-display property with a value of fixed helps tables render more quickly. It is useful for tables whose cells are regular in size.
that framesets use either the HTML or XHTML Frameset DOCTYPE. If you don't want to type it, you can copy it from my Web site (see page 24).
[View full width]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/ DTD/xhtml1-frameset.dtd "> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Frames in Rows</title> </head> <frameset rows="65,*,60"> <frame name="banner" src="banner.html"/> <frame name="photos" src="openingpage.html"/> <frame name="buttons" src="buttons.html"/> </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.
Figure 15.3. Viewed individually, the pages shown in Figure 15.2 appear just as any other Web page.
Figure 15.4. Here is the page from Figure 15.3 shown as one of three frames in a frameset.
Tips
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) .
To support visitors whose browsers don't understand frames, see page 260.
</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.
Figure 15.7. Browsers show the columns of frames in very much the same way as they show frames in rows.
Tips
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.8 You set the size of rows and columns in the frameset tag. Then define each row from left to right, and from top to bottom.
[View full width]
</head> <frameset frameborder="0" rows="*, 193, 104, 165, *" cols="*, 110, 110, 110, *" > <frame name="border1" src="border.html" scrolling="no" marginwidth="1" marginheight="1" /> [snip five more borders] <frame name="border6" src="border.html" scrolling="no" marginwidth="1" marginheight="1" /> <frame name="topleft" src="balcony1.html" scrolling="no" marginwidth="1" marginheight="1" /> <frame name="topmiddle" src="balcony2.html" scrolling="no" marginwidth="1" marginheight="1" />
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.
Tips
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.
To combine framesets:
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.
[View full width]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/ DTD/xhtml1-frameset.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <title>Combining Framesets</title> </head> <frameset rows="65,*,60"> <frame name="banner" src="banner.html" /> <frameset cols="120,*"> <frame name="index" src="indexcity.html" /> <frame name="photos" src="openingpage.html"/> </frameset> <frame name="buttons" src="buttons.html" /> </frameset> </html>
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.
Tips
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.
</head> <body bgcolor="#FFFFFF"> <h1>Barcelona Tours</h1> Here's an idea of what the Barcelona Tours home page looks like: <hr /> <iframe src="bcntourrc.html" name="bcntours" width="500" height="450">The <a href="bcntourrc.html">Barcelona Tours</a> page contains great photos and essential tips for making your vacation a success.</iframe> </body> </html>
Figure 15.13. Floating frames function similarly to images, flowing with the rest of the content on the page.
Tips
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.
All browsers display a frame's contents with a default margin of from 8 to 15 pixels on each side (Figure 15.14). You can adjust the margin so that there is more space, or, if you prefer, so that the frame's contents begin in the top-left corner. Figure 15.14. Note how the contents of each frame with default margins begins slightly down and to the right.
</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.
Figure 15.16. With the margins at 0, each frame's contents start in the top-left corner of each frame.
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.
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"> <frame name="banner" src="banner.html" scrolling="no" /> <frameset cols="120,*"> <frame name="index" src="indexcity.html"/> <frame name="photos" src="openingpage.html"/></frameset> <frame name="buttons" src="buttons.html" scrolling="no"/></frameset>
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.
Tips
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.
Figure 15.20 You can add the bordercolor tag to any frameset or frame tag. Here it's been added to the topmost frameset tag so that it will affect all the frames contained within.
<frameset bordercolor="#ff0000" rows="65,*,60"> <frame name="banner" src="banner.html" scrolling="no"/> <frameset cols="120,*" > <frame name="index" src="indexcity.html"/> <frame name="photos" src="openingpage.html" /> </frameset> <frame name="buttons" src="buttons.html" scrolling="no"/>
Figure 15.21. Both Netscape and Explorer support the non-standard
bordercolor attribute. They also both add a bit of black to the bottom part of the
border, regardless of the color you've chosen.
Tips
A bordercolor tag in an individual frame overrides a bordercolor tag in a row or column, which in turn overrides the tag defined in the topmost frameset. If two bordercolor tags at the same level conflict, the one that comes first in your (X)HTML file takes precedence. When you change the border of an individual frame, other frames that share its borders are also affected. The bordercolor tag is not standard (X)HTML but has been and continues to be supported by both Netscape and Explorer.
<frameset bordercolor="#ff0000" border="10" rows="65,*,60"> <frame name="banner" src="banner.html" scrolling="no" /> <frameset cols="120,*"> <frame name="index" src="indexcity.html" /> <frame name="photos" src="openingpage.html"
Figure 15.23. Thick, colored borders can help divide information into understandable chunks.
Figure 15.24. With a value between 1 and 5, Explorer for Windows shows no borders at all (though it continues to leave the empty space for them).
Tips
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).
Figure 15.25 If you want to be sure that your page has no borders, whether it is viewed in Netscape or Explorer, set both the border and frameborder tags to 0.
<frameset bordercolor="#ff0000" border="0" frameborder="0" rows="65,*,60"> <frame name="banner" src="banner.html" scrolling="no" /> <frameset cols="120,*"> <frame name="index" src="indexcity.html" /> <frame name="photos" src="openingpage.html"
Figure 15.26. To have each frame right up next to the adjacent one, use frameborder="0" border="0" .
Figure 15.27. With just frameborder="0" , Explorer continues to leave space between frames. It's most noticeable below the left City Tour frame.
Tips
The frameborder attribute is standard (X)HTML. Hurray! If you use frameborder="0", the sculpted borders disappear but Explorer continues to show space between frames. To get rid of both borders and space, use frameborder="0" and border="0". Type frameborder="1" in the desired frame or frameset tag to view some borders when the topmost frameset is set for none. To make the horizontal borders disappear, define the columns in the outer frameset and the rows in the inner frameset and then type frameborder="0" within each of the frame tags in the desired column. You can use the frameborder tag with individual frames. Explorer will display the border around an individual frame, but Netscape will show the border for the entire row.
Figure 15.28. Normally when the visitor places the pointer over a border, it changes into a double-headed arrow with which she can change the size of the frame. Also notice the hash mark in Netscape 4 which indicates the frame can be resized.
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 bordercolor="#ff0000" border="6" rows="65,*,60"> <frame name="banner" src="banner.html" scrolling="no" noresize="noresize" /> <frameset cols="120,*"> <frame name="index" src="indexcity.html" /> <frame name="photos" src="openingpage.html" /> </frameset> <frame name="buttons" src="buttons.html" scrolling="no" noresize="noresize" />
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.)
Tips
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.
Figure 15.31 Targets will only work if the frame in which you want the page to appear has a name.
<frameset cols="120,*"> <frame name="index" src="indexcity.html" /> <frame name="photos" src="openingpage.html" />
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.
<tr><td bgcolor="#F3D7E3"><a href="openingpage.html" target="photos" > Beginning</a></td></tr> <tr><td bgcolor="#F6D5C3"><a href= "rambles.html" target="photos" >Les Rambles Boulevard</a></td>
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.34. ...the Les Rambles page replaces the Welcome page 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.
[View full width]
stalls, younger people arguing at the political booths, mimes and bands, beggars and pickpockets (well, maybe you won't <em>see</em> them). If I were there, I'd be drinking an orxata at the Café de l'Ópera watching all the people go by.</p> <p>Find out more at the < a href= "http://www.bcn.es/english/ihome.htm " target="_top">Official Barcelona Site</a> <br/><a href="plcat.html">Next stop</a></p>
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).
Figure 15.37. ...the link is displayed in the full window without any frames.
Or type target="_parent" to open the link in the frame that contains the current frameset. This will only be different from _top when you are using nested framesets. For more information on nested framesets, consult Nesting Framesets on page 259. Figure 15.38 In the original document, I've set the target for each link individually.
<title>Buttons</title> </head> <body bgcolor="white"> <table cellpadding="5" cellspacing="0" width="100%"> <tr><th><font color="#FFFFFF" size="+1">City Tour</font></th></tr> <tr><td bgcolor="#F3D7E3"><a href="openingpage.html" target="photos" >Beginning</a></td></tr> <tr><td bgcolor="#F6D5C3"><a href="rambles.html" target="photos" >Les Rambles Boulevard</a></td></tr> <tr><td bgcolor="#D8E9D6"><a href="plcat.html" target="photos" >Plaça Catalunya</a></td></tr>
Figure 15.39 You can save a lot of typing by using the base tag to set the default target for every link on the page. This document is equivalent to the one shown in Figure 15.38.
<title>Buttons</title> <base target="photos"/> </head> <body bgcolor="white"> <table cellpadding="5" cellspacing="0" width="100%"> <tr><th><font color="#FFFFFF" size="+1">City Tour</font></th></tr> <tr><td bgcolor="#F3D7E3"><a href= "openingpage.html">Beginning</a></td></tr> <tr><td bgcolor="#F6D5C3"><a href="rambles. html">Les Rambles Boulevard</a></td></tr> <tr><td bgcolor="#D8E9D6"><a href="plcat. html">Plaça Catalunya</a></td></tr>
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.
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.
Nesting Framesets
As if frames and framesets weren't complicated enough, you can nest framesets inside of frames to achieve special effects.
To nest framesets:
1. Build the child, or inner, frameset (see page 242) . 2. Build the parent, or outer, frameset ( Figure 15.40). When you reach the frame in which you wish to nest the child frameset, type src="child.html" in the frame tag, where child.html is the file that you built in step 1. 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*"> <frame src="bigindex.html" /> <frame name="main" src="bcntourrc.html" /> </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.
Tips
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.)
<frameset rows="65,*,60"> <frame name="banner" src="banner.html" noresize="noresize" scrolling="no" /> <frameset cols="120,*"> <frame name="index" src="indexcity.html" /> <frame name="photos" src="openingpage.html" /> </frameset> <frame name="buttons" src="buttons.html" noresize="noresize" scrolling="no" /> <noframes><body> <p>The information on this page is displayed in frames. Your browser can't view frames ( or if you're using Internet Explorer, you've turned frame viewing off--go to Preferences under Edit and then Web Content and check Show Frames). Sorry!</p>
</body></noframes> </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.44. When you turn frames off in Internet Explorer, the alternate information is displayed. This is a good way to test how this information will appear.
Figure 15.45 You can embed one (X)HTML page in another by using the object element.
[View full width]
</head> <body bgcolor="#FFFFFF"> <h1>Barcelona Tours</h1> <p>Here's an idea of what the first page of the Barcelona Tours site looks like: </p> <hr /> <object type="text/html" data="openingpage.html" width="500" height="450" > The <a href="openingpage.html"> Barcelona Tours</a> page contains great photos and essential tips for making your vacation a success.</object> </body>
Figure 15.46. The referenced page is embedded on our Web page as if it were a frame. The links work and everything!
Figure 15.47 Here are two nested object elements. The outer one could be in a new, experimental, but not very well supported MIME type. The inner is the old (X)HTML standby.
<body bgcolor="#FFFFFF"> <h1>Barcelona Tours</h1> Here's an idea of what the first page of the Barcelona Tours site looks like: <hr /> <object type="unsup/fake" data="superbcn.sup" width="500" height="450" > <object type="text/html" data="openingpage.html" width="500" height="450" > The <a href="openingpage.html">Barcelona Tours</a> page contains great photos and essential tips for making your vacation a success. </object> </object>
</body>
Figure 15.49 You can add title and longdesc information to each frame to help explain how the frames in the site work together.
[View full width]
</head> <frameset rows="65,*,60"> <frame name="banner" src="banner.html" title="The Welcome Banner"/> <frameset cols="120,*"> <frame name="index" src="indexcity.html" title="The Table of Contents" /> <frame name="photos" src="openingpage.html" title="Main Content and Photographs" longdesc="frameinfo.html#photos" /> </frameset> <frame name="buttons" src="buttons.html" title="Larger Navigation System" /> <noframes><body> <p>There is a <a href="plaintextversion.html"> non-frames version</a> of this site.</p> <p>And here is <a href="frameinfo.html">more information</a> about the way the frames work together.</p> </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.
[View full width]
<body> <h2>Information about the frames and frameset</h2> <p id="photos">The "Main Content and Photographs" frame is situated in the center right of the frameset. It will contain descriptions of Barcelona monuments and buildings as well as photographs of the same</p>
Tips
You can find a list of MIME types on my Web site (see page 24). The object element is designed to be nested. Browsers are supposed to ignore the objects that they do not recognize and display only the first one they support. It's an ingenious system for serving alternate content to browsers in a format they can handle. Netscape 6 and Opera 6 both support the object element properly. IE 6 for Windows insists on adding unsightly scroll bars around every object (even images). In addition, if you nest objects as described on this page, it leaves an empty space and scrollbars for the objects it doesn't support instead of ignoring them completely as it's supposed to do. It's not pretty. IE for Mac does slightly better. If it doesn't support an object, it doesn't leave an empty box for it. However, if it supports multiple objects, it displays them all (instead of displaying only the first one that it supports). It breaks the whole system of providing alternate content. The object element is often used for embedding multimedia content in Web pages. For more details, Chapter 17, Multimedia. Browsers may not support the object element itself, the MIME type of the object you're trying to display, or the method that you're using to display it. For example, IE 6 for Windows depends on proprietary ActiveX technology for its multimedia objects which other browsers do not support.
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/
get feedback have a guestbook take a survey see who's visiting you sell stuff and much more!
and partly because it has this reputation as a cool language really! Perl programmers love to brag about how they can do anything with Perl, on one line, in a million different ways. 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.
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.
<p>E-mail: <input type="text" name="visitor_email" size="30" /></p> <p>Computer: <input type="radio" name="computer" value="Mac" />Macintosh</p> <input type="radio" name="computer" value="Win" />Windows</p>
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). Label Name E-Mail Computer Send info Name visitor_name visitor_email computer submit Value Cookie cookie@cookwood.com Mac Send info
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.
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.
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
the public domain. They now offer support for those scripts www.extropia.com.
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; use CGI ':standard'; my @param=param(); print "Content-type: text/html\n\n"; foreach my $name (param()) { my @value= param($name); print "<p>The field with the NAME attribute equal to <b> $name</b> had a VALUE equal to <b>@value</b></p>\n"; }
Tips
To get more high-powered scripts, consult Getting a Script on page 266. If you are intrigued by writing your own scripts, you might be interested in my other book: Perl and CGI for the World Wide Web: Visual QuickStart Guide, Second Edition, also published by Peachpit Press. With the same clear, concise, and visually oriented format as the book you have in your hands, it is a perfect starting place for non-programmers who want to make their Web pages interactive. For details, check out www.cookwood.com/perl/. End of blurb.
Preparing a Script
Whether you've written your own script or are using someone else's, you'll have to do a couple of things to get the script ready for use with your form.
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.
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:
1. Type <form method="post". 2. Type action="script.url"> where script.url is the location on the server of the CGI script that will run when the form is submitted (see pages 264%268) . 3. Create the form's contents, as described on pages 272!292, including a submit button (see page 282) or active image (see page 286). 4. Type </form> to complete the 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.
Please share any suggestions or comments with us: <textarea name="comments" rows="3" cols="65" wrap="wrap">Comments?</textarea> <hr /> <input type="submit" value="Order Bed" name="submit" /> <input type="reset" value="Start Over" name="startover" /> </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.
You can also use the get method to process information gathered with a form. However, since the get method limits the amount of data that you can collect at one time, I recommend using post.
<h2>Ordering your new bed</h2> <form method="post" enctype="text/plain" action="mailto:orderbed@cookwood.com"> Name: <input type="text" name="name" />
Figure 16.11. Forms that will be submitted via e-mail look precisely the same as those that are processed with a CGI script.
Figure 16.12. The data is contained in the body of the e-mail message. Note that the default Subject line depends on the browser your visitor uses (in this example, it was Netscape, code name Mozilla). The From field should reveal the visitor's email address. The To field will correspond to the address you entered for the action attribute.
Tips
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.
Figure 16.14. Response-O-Matic gets you started by asking you a few questions and then creating a template, as shown in Figure 16.15.
Figure 16.15. Save the template to your hard disk and edit it as necessary. (Just don't change the hidden fields.)
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.
Name: <input type="text" name="name" /> Address: <input type="text" name="address" size="30" /> <p>City: <input type="text" name="city" /> State: <input type="text" name="state" size="2" maxlength="2" /> Zipcode: <input type="text" name="zip" size="5" maxlength="5" />
Figure 16.17. Text boxes can be different sizes to accommodate different types of fields.
Figure 16.18. It's important to give descriptive names to your text boxes (with the name attribute) so that you identify the information you're receiving.
Tips
Even if your visitor skips the field (and you haven't set the default text with the value attribute), the name attribute is still sent to the server (with an undefined, empty value). The default size is 20. However, visitors can type up to the limit imposed by the maxlength attribute. Still, for larger, multi-line entries, it's better to use text areas (see page 278).
Figure 16.21. The password data appears as regular text after processing by a form-parsing script. Password boxes are not high-security! (See second to last tip.)
Tips
Even if nothing is entered in the password box, the name is still sent to the server (with an undefined value). You could set default text for value (as in step 4 on page 272), but that kind of defeats the purpose of a password. The only protection the password box offers is from folks peering over your visitor's shoulder as she types in her password. Since the password box does not encrypt the data when it is sent to the server, moderately experienced crackers can discover the password without much trouble.
<b>Size:</b> <input type="radio" name="size" value="K" />King <input type="radio" name="size" value="Q" />Queen <input type="radio" name="size" value="T" />Twin <input type="radio" name="size" value="S" />Single
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.
Figure 16.24. Note that it is the value (Q) and not the label (Queen) that gets sent to the script.
Tip
If you don't set the value attribute, the word "on" is sent to the script. It's not particularly useful since you can't tell which button in the set was pressed.
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. (The ="checked" is optional in HTML.) 6. Type /> to complete the checkbox. 7. Type the text that identifies the checkbox to the user. This is often the same as the value, but doesn't have to be. 8. Repeat steps 2!7 for each checkbox in the set. 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> <input type="checkbox" name="extras" value="foot" />Footboard <input type="checkbox" name="extras" value="drawers" />Drawers (for underneath) <input type="checkbox" name="extras" value="casters" />Casters <input type="checkbox" name="extras" value="nosqueak" />Squeak proofing</p>
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.
Figure 16.27. Since the visitor has chosen two checkboxes, both values (but not their labels, of course) are sent to the script. This particular script separates multiple values with a comma.
Tip
If you don't set the value attribute, the word "on" is sent to the script. It's not particularly useful since you can't tell which box in the set was checked.
Creating Menus
Menus are perfect for offering your visitors a choice from a given set of options.
To create menus:
1. If desired, type the text that will describe your menu. 2. Type <select. 3. Type name="name", where name will identify the data collected from the menu when it is sent to the server. 4. If desired, type size="n", where n represents the height (in lines) of the menu. 5. If desired, type multiple="multiple" to allow your visitor to select more than one menu option (with Ctrl or Command). (The ="multiple" is optional in HTML.) 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="Maplewood">Maplewood </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.
Figure 16.30. Notice that the name attribute (woodtype) and not the label (Type of wood:) is what gets sent to the script.
If you have a particularly large menu with many options, you may want to group the options into categories.
<b>Type of wood:</b> <select name="woodtype" > <optgroup label="Hard woods"> <option value="Mahogany">Mahogany</option> <option value="Maplewood">Maplewood</option> <option value="Cherry">Cherry</option> </optgroup> <optgroup label="Soft woods"> <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!
Figure 16.33. IE 6 for Windows and Netscape 6 on both platforms show a single menu divided into groups.
Tips
If you add the size attribute in step 4, the menu appears more like a list, and there is no automatically selected option (unless you use selected see step 8). If size (see step 4) is bigger than the number of options, visitors can deselect all values by clicking in the empty space. While the label attribute is a standard part of (X)HTML, only IE 5 for Mac and mobile devices support it. If there is no label attribute, the browser automatically uses the text enclosed in the option tag. IE5 for Mac shows the optgroup tag as a submenu. IE 6 for Windows and Netscape 6 on both platforms simply divide the options into categories. No other browser supports optgroup at all. The closing option tag in step 13 is optional in HTML 4 (but not in XHTML). You can also use the abbreviated selected and multiple in HTML, whereas XHTML requires selected="selected" and multiple="multiple" .
<hr />Please share any suggestions or comments with us: <textarea name="comments" rows="3" cols="65" wrap="wrap">Comments?</textarea>
Figure 16.35. The visitor can override the default text simply by typing over it.
Figure 16.36. Text areas are great for getting longer comments and suggestions from visitors. They are typically used in guestbooks and bulletin boards.
Tips
There is no use for the value attribute with text areas. Visitors can enter up to 32,700 characters in a text area. Scroll bars will appear when necessary. Netscape 4.x doesn't wrap text automatically in large text areas. You can add the non-standard wrap attribute so that it will. Other browsers ignore it.
<body> <form method="post" action="http://www.cookwood.com/cgibin/perl2e/uploading/uploading. cgi" enctype="multipart/form-data" > <h2>What files are you sending?</h2> <p><input type="file" name="uploadfile" size="40"/ > <p><input type="submit" name="submit"/> </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.
Figure 16.39. Once the file is uploaded, the visitor gets a confirmation message.
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.
Don't get carried away by the word hidden. While hidden fields are not shown by the browser, they still form part of the (X)HTML code that makes up the page (so the CGI script can get at them), and thus are not at all invisible if someone should look at the source code for your page (see page 57) .
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.
<form method=post action="whatever.cgi"> <input type="hidden" name="name" value="value" /> <input type=submit value="submit data" />
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).
3. Type the final />. 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.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?
Tips
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.44 If you want a submit button with an image, you'll have to create it with the button tag.
[View full width]
<h2>Ready to vote?</h2> <form action="http://www.cookwood.com/cgibin/vote.cgi " method="post"> <input type="radio" name="cats" value="W" accesskey="w" />Woody<br /> <input type="radio" name="cats" value="C" accesskey="c" />Cookie<br /> <input type="radio" name="cats" value="X" accesskey="x" />Xixona<br /> <input type="radio" name="cats" value="L" accesskey="l" />Llumeta<br /> <input type="radio" name="cats" value="A" accesskey="a" />All of them (Don't make me choose!) <p><button type="submit" name="submit" value="submit"><img src="check.gif" width="40" height="40" alt="Vote button" />Vote</button>
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.)
Tips
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.47. If your visitor clicks the reset button, all the fields are set to their default values.
Tip
The name-value pair for the reset 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 completely superfluous reset data which is usually something like "reset, Reset".
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.
[View full width]
<h2>Ready to vote?</h2> <form action="http://www.cookwood.com/cgibin/vote.cgi " method="post"> <input type="radio" name="cats" value="W" accesskey="w" />Woody<br /> <input type="radio" name="cats" value="C" accesskey="c" />Cookie<br /> <input type="radio" name="cats" value="X" accesskey="x" />Xixona<br /> <input type="radio" name="cats" value="L" accesskey="l" />Llumeta<br /> <input type="radio" name="cats" value="A" accesskey="a" />All of them (Don't make me choose!) <p><button type="submit" name="submit" value="submit"><img src="check.gif" width="40" height="40" alt="Vote button" />Vote</button> <button type="reset" name="reset" value="reset"> <img src="reset.gif" width="40" height="40" alt="Reset button" />Reset</button> </p>
</form>
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.
5. Type alt="description", where description will appear if the image does not. 6. Type the final /> to finish the active image definition for the form. Figure 16.50 If you use an active image, you don't need a submit button.
<form action="http://www.cookwood.com/cgibin/zonemap.cgi " method="post"><br> <input type="radio" name="infotype" value="time" />Local time <input type="radio" name="infotype" value="weather" />Local weather <input type="radio" name="infotype" value="directions" />Directions <input type="radio" name="infotype" value="statistics" />City statistics <p><input type="image" src="zonemap.gif" name="coord" alt="U.S. Map" /> </p></form>
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.
Tips
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.
<form action="processform.cgi" method="post"> <fieldset><legend>Personal Information</legend> <p>Name: <input type="text" name="firstname" size="15" /><br /> E-mail: <input type="text" name="email" size="25" /></p> </fieldset> <fieldset> <legend align="right">Comments </legend> Please let us know what you think:<br /> <textarea cols="40" rows="7" name="comments">I think your cats are... </textarea> </fieldset> <input type="submit" name="Submit" value="Send
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.
While the align attribute for legend has been deprecated, it's still supported by Netscape 6 and IE (from 4 on). It's default value is left. There were supposedly top and bottom values as well, but I've never seen a browser support them.
<form action="processform.cgi" method="post"> <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> <fieldset><legend align="right">Comments</legend> Please let us know what you think:<br /> <textarea cols="40" rows="7" name="comments">I think your cats are... </textarea></fieldset>
Figure 16.56. There's no outward difference in appearance when you use labels! unless you style them with CSS.
Tips
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.
<body> <a href="moreinfo.html" tabindex="4"> About our company</a> <h2>Please tell us more about yourself:</h2> <form method="post" action="processform.cgi"> Name: <input type="text" name="firstname" size="20" tabindex="1" /><br /> E-mail address: <input type="text" name="email" tabindex="2" /><br /> Hobbies: <input type="text" name="hobbies" tabindex="3" /></form> </body>
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.
You can also assign tab order to links (see page 127) and client-side image maps (see page 130). OK, I cannot tell a lie. The first time your visitor hits the Tab key, the Address or Location field where the current URL is displayed gets the focus (even if its toolbar is hidden). Then, the next tab brings the visitor where you say.
Figure 16.59 Add keyboard shortcuts to your form elements with the accesskey attribute.
[View full width]
<h2>Ready to vote?</h2> <p>Choose any option from the keyboard by pressing Alt (Ctrl for Macintosh) plus its first letter. So Alt-W/Ctrl-W would choose <em>Woody </em> (he's awful cute). (Use "T" for the comments box.)</p><hr /> <form action="http://www.cookwood.com/cgibin/vote.cgi " method="post"> <input type="radio" name="cats" value="W" accesskey="w" />Woody<br /> <input type="radio" name="cats" value="C" accesskey="c" />Cookie<br /> <input type="radio" name="cats" value="X" accesskey="x" />Xixona<br /> <input type="radio" name="cats" value="L" accesskey="l" />Llumeta<br /> <input type="radio" name="cats" value="A" accesskey="a" />All of them (Don't make me choose!) <p><textarea name="comments" cols="40" rows="3" accesskey="t" >Any special comments? </textarea></p>
Figure 16.60. It's a good idea to tell your visitors about any available keyboard shortcuts. Otherwise, they won't know they're there.
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.
In the form element's tag, type disabled="disabled". 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.
[View full width]
<form action="http://www.cookwood.com/cgibin/vote.cgi " method="post" name="vote"> <input type="radio" name="cats" value="W" onclick="document.vote.submit.disabled=false" accesskey="w"/>Woody <br /> <input type="radio" name="cats" value="C" onclick="document.vote.submit.disabled=false" accesskey="c" />Cookie <br /> <input type="radio" name="cats" value="X" onclick="document.vote.submit.disabled=false" accesskey="x" />Xixona <br /> [snip] <p><input name="submit" type="submit" value ="Vote!" accesskey="v" disabled="disabled" /> <input type="reset" value="Reset" accesskey="r" onclick="document.vote.submit. disabled=true" /> </p>
Figure 16.62. When the visitor first views the form, nothing is selected and the submit button is disabled.
Figure 16.63. When the visitor clicks on one of the buttons, the submit button becomes enabled.
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.
<form action="http://www.cookwood.com/cgibin/vote.cgi " method="post" name="vote"> <br>So far you've voted for <p><textarea name="votehistory" cols="40" rows="3" readonly="readonly" >Woody on Monday, Cookie on Tuesday, Xixona on Thursday, and Llumeta on Wednesday</ textarea></p> <input type="radio" name="cats" value="W" onclick="document.vote.submit.disabled=false" accesskey="w" />Woody <br /> <input type="radio" name="cats" value="C" onclick="document.vote.submit.disabled=false" accesskey="c" />Cookie <br /> <input type="radio" name="cats" value="X" onclick="document.vote.submit.disabled=false" accesskey="x" />Xixona <br /> <input type="radio" name="cats" value="L" onclick="document.vote.submit.disabled=false" accesskey="l"/>Llumeta <br /> <input type="radio" name="cats" value="A" onclick="document.vote.submit.disabled=false" accesskey="a" />All of them (Don't make me choose!)
Figure 16.65. In this example, the visitor's prior votes are displayed in the readonly text area. They can be viewed by the visitor and then submitted with the new vote.
Tips
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.
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.
Luckily, the object element is designed to be nested in order to allow several options to browsers (Figure 17.1). If the first object is unreadable, they can ignore it and try the next until they find one they understand. Alas, Explorer's support of the object tag is incomplete. Instead of ignoring the standard object elements it for some reason cannot understand, it shows big, ugly boxes (Figure 17.2). Netscape 6, for its part, handles nested object elements perfectly, ignoring the one with proprietary ActiveX controls and displaying the standard one (Figure 17.3). 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.
[View full width]
<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" width="240"height="196" codebase="http://www.apple.com/qtactivex/qtplugin.cab "> <param name="src" value="madmax.mov" /> <param name="autoplay" value="false" /> <param name="controller" value="true" /> <object data="madmax.mov" type= "video/quicktime" width="240" height="196" codebase="http: //www.apple.com/qtactivex/qtplugin.cab "> <param name="src" value="madmax.mov" /> <param name="autoplay" value="false" /> <param name="controller" value="true" /> </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.
Figure 17.3. Netscape properly ignores the ActiveX controlled object and displays just the one it understands.
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.
[View full width]
codebase="http://www.apple.com/qtactivex/qtpl ugin.cab"> <param name="src" value="madmax.mov"> <param name="autoplay" value="false"> <param name="controller" value="true"> <embed src="madmax.mov" width="240" height="196" autoplay="false" controller="true" pluginspage="http://www.apple.com/quicktime/download/ "> </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.
Nonetheless, this solution is far from satisfactory to those of us who would like to write standard, validated code. However, until Explorer offers complete support for the object tag, I think it's the best we've got.
Figure 17.8. On most browsers (other than IE5.5+ for Windows), a broken plugin icon or an alert about the missing plugin will appear. When the visitor clicks the broken icon...
Figure 17.9. ...they are immediately directed to the Web page where they can download the necessary software and then install it themselves.
You can add QuickTime movies to your Web site that are compatible with Explorer and Netscape on both Mac and Windows and that automatically stream from any server.
<body> <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"> <param name="src" value="madmax.mov"> <param name="autoplay" value="false"> <param name="controller" value="true"> <embed src="madmax.mov" width="240" height="196" autoplay="false" controller="true" pluginspage="http://www.apple.com/quicktime/download/ "> </embed>
</object>
Figure 17.11. The movie shows up in the big two browsers on both platforms. No small feat.
Figure 17.12 I've made the space for the movie bigger (using the width and height attributes in both the object and embed tags). Then, I add the scale param element to double the size of the movie itself.
[View full width]
<body> <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"> <param name="src" value="madmax.mov"> <param name="autoplay" value="false"> <param name="controller" value="true"> <param name="scale" value="2"> <embed src="madmax.mov" width="480" height="392" autoplay="false" controller="true" pluginspage="http://www.apple.com/quicktime/download/ " scale="2" > </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.
Tips
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.
1. After the initial object tag (step 2 on page 298), type <param name="scale" value="factor">, where factor is: 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. Type "> to complete the param tag. 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.
[View full width]
<body> <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"> <param name="src" value="madmax.mov"> <param name="autoplay" value="false"> <param name="controller" value="true"> <param name="scale" value="2"> <param name="loop" value="true"> <embed src="madmax.mov" width="480" height="392" autoplay="false" controller="true" pluginspage="http://www.apple.com/quicktime/download/ " scale="2" loop="true" > </embed> </object>
Figure 17.15. With a loop value of true, the movie automatically starts over when it reaches the end.
Tips
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.
2. Add the loop attribute to the embed tag with the same value as you've specified in step 1. Figure 17.16 Set the height to 16 if you're just embedding sounds.
[View full width]
<p>Listen to Barcelona street sounds:</p> <object classid="clsid:02bf25d5-8c17-4b23-bc80-d3488abddc6b" width="240" height="16" codebase="http://www.apple.com/qtactivex/qtpl ugin.cab"> <param name="src" value=" madmax_sound.mov"> <param name="autoplay" value="true"> <param name="controller" value="true"> <param name="loop" value="true"> <embed src="madmax_sound.mov" width="240" height="16" autoplay="true" controller="true" pluginspage="http://www.apple.com/quicktime/download/ " loop="true"> </embed> </object>
Figure 17.17. The 16 pixel high controller is shown.
<param name="hidden" value="true"> <embed src="madmax_sound.mov" width="240" height="16" autoplay="true" controller="true" pluginspage="http://www.apple.com/quicktime/download/ " loop="true" hidden>
Tip
<body> <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" width="240" height="252" type="application/x-oleobject"> <param name="autostart" value="false"> <param name="filename" value="madmax.avi"> <param name="showcontrols" value="true"> <param name="ShowStatusBar" value="true"> <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>
</object>
Figure 17.20. One of the purported advantages of Windows' reliance on ActiveX is that it allows visitors to easily download the plug-in should it not already be installed.
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.22. Once the plugin is installed, the movie plays correctly.
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).
Figure 17.24 This applet doesn't have any parameters to adjust. Everything is in the opening object tag.
<body> Does anybody really know what time it is? <object codetype="application/java" classid="java:Clock2.class" width="170" height="150"> </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".
Figure 17.27. Follow the link that gives more information about embedding the player.
Figure 17.28. Since companies want to make it easy to embed their player, they usually offer complete details, including the classid attribute and other controls.
Tips
I would also recommend advising Netscape 6 visitors to go to Microsoft's site to download version 7.1 of Windows Media Player. Microsoft's earlier installers (including 6.4) only recognize Netscape version 4.x and earlier and so do not properly install the plugin for Netscape 6. You can personalize the Windows Media Player with custom skins and scripting. See Microsoft's site for details. Internet 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 embedded embed tag. While the values of the two elements should probably match, it's not absolutely required. You could even use the object element described on this page in conjunction with the embed tag described for the QuickTime player (see page 298) .
To insert an applet:
1. Type <object codetype="application/java" classid="java:file.class", where file.class is the name of the applet you want to embed. 2. Then type width="w" height="h", where w and h are the applet's size in pixels. 3. Close the opening object tag with >. 4. Include any parameters, with <param name="parameter" value="value_of_parameter" />. 5. Finally, type </object> to finish. Figure 17.29 Create a link to the movie.
<head> <title>MadMax Movie</title> </head> <body> <p>Here's my <a href="madmax.mov"> movie</a>. </body> </html>
Figure 17.30. When the visitor clicks the link...
Figure 17.31. ...an independent QuickTime player appears. It is not within the browser window.
Tips
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.
<head> <meta http-equiv="refresh" content="5; url=page2.html" /> <style> p {width:200px}</style> <title>Slide Show Page 1</title> </head> <body> <p><img src="tree1.jpg" alt="Tree in September" width="200" height="293" /></p> <p>I love autumn in New England. Last year,
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.
<html> <head> <title>Untitled</title> </head> <body> <h1>The Quabbin Reservoir</h1> They had to flood four towns and three <snip> <marquee width="75%" height="15" behavior="scroll" direction="left" loop="infinite" bgcolor="yellow"> Attention: Quabbin Enthusiasts General Meeting Dec 9 at 7pm </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.
Figure 17.37. Netscape and other standards-supporting browsers completely ignore Microsoft's extensions.
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.
And now for something completely different!You can use a special feature of the meta attribute, within the head section, to automatically move the reader from one page to another. If you set up a series of pages in this way, you create a Web slide show.
<html><head> <title>Background Sound for Explorer Only</title></head> <body> <h1>Dakota</h1> <bgsound src="dakota.mp3" loop="2"> <p>Dakota is Kevin's lovable golden lab. I haven't actually met him, though I'm looking forward to it. But I know he sounds something like this. </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.
Tips
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. 2. To determine which direction the text starts from, type direction="left" or direction="right". 3. If desired, type loop="n", where n is the number of times the text will pass across the screen. Use loop="infinite" to have the text appear continuously. 4. Type scrollamount="n" to determine how much space, in pixels, is left between each pass of the text. 5. Type scrolldelay="n" to determine how much time, in milliseconds, passes before the text scrolls again.
6. 7. 8. 9.
Use the height, width, hspace, vspace, align, and bgcolor attributes as usual, if desired. Type the final >. Type the scrolling text. Type </marquee>.
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.
automatic scripts as you like on a page. They will run in the order they appear. (The second group, "triggered scripts", is discussed on page 316.)
<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> <p>Here's the rest of the page.</p> </body> </html>
Figure 18.2. This simple JavaScript script is output to the browser window itself. Other scripts send their results elsewhere.
Tips
The language attribute is deprecated and thus only valid in (X)HTML transitional (see page 38). Nevertheless it is often used to maintain compatibility with older browsers. The location of the script on the (X)HTML page determines when it will load. Scripts are loaded in the order in which they appear in the (X)HTML file. If you want your script to load before anything else, be sure to place it in the head section. For hiding scripts in XHTML pages from XML parsers, see page 321.
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> <p>Here's the rest of the page.</p> </body> </html>
Figure 18.5. External scripts work the same way as internal ones. But they are often much more convenient.
Tips
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> <p>Here's the rest of the page.</p> </body> </html>
2. Within the tag created in step 1, type event, where event is an intrinsic event as defined below (Figure 18.7). Unless otherwise noted, most events can be used with most (X)HTML tags. 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> <p>Here's the rest of the page.</p> </body> </html>
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.
Figure 18.9. Once the visitor clicks the link, the script runs. In this case, an alert appears, giving the current date and time.
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.
2. Type name="name", where name is the identifier for the button. 3. Type onclick="script", where script is the code (usually JavaScript) that will run when the visitor clicks the button. 4. If desired, type style="font: 14pt Lithos Regular; background:red" (or whatever) to change the appearance of the text on the button. 5. Type >. 6. If desired, type the text that should appear on the button. 7. Type </button>. 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.
[View full width]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>Associating scripts with a button</title> </head> <body> <button type="button" name="time" onclick="alert('Today is '+ Date())" style="font: 24px 'Helvetica', 'Arial', sans-serif; background:yellow;color:red;padding:4px">What time is it?</button> </body> </html>
Figure 18.11. Although the button tag is a standard part of (X)HTML, only current browsers support it (with or without scripts).
Figure 18.12. A click on the button executes the script, as shown here.
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.
Figure 18.13 The noscript tag helps you take care of visitors who use really old browsers or who have scripting turned off in their browser.
[View full width]
<title>Llumi's big cat dreams</title> <script type="text/javascript" language="javascript"> <!-littlecat = new Image(143,83) littlecat.src = "real.jpg" bigcat = new Image(143,83) bigcat.src = "dream.jpg" // --> </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.
Current browsers (and some older ones) allow your visitors to disable JavaScript. The noscript tag is perfect for telling those visitors what they're missing (Figure 18.15).
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.17 This JavaScript script comes from Figure 19.18 on page 330. It preloads the images into cache to ensure speedy rollovers.
[View full width]
<title>Llumi's big cat dreams</title> <script type="text/javascript" language="javascript"> <!-littlecat = new Image(143,83) littlecat.src = "real.jpg" bigcat = new Image(143,83) bigcat.src = "dream.jpg" // --> </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.)
Tips
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>
Figure 18.20 The meta tag is always placed in the head section of your (X)HTML document. It specifies the default scripting language for all of the scripts on a page.
<!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.
The scripting language indicated with the type attribute in the script tag (see page 314) overrides the meta tag specification. That means you can set the default scripting language, but still use scripts written in other languages, if desired. While this meta tag is theoretically required for pages that contain intrinsic events, its absence generates no validation errors nor problems in browsers.
Nothing makes your page seem more current than adding the date and the time. While they're a bit more complicated to format in a particular way, just adding them is not difficult at all.
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).
[View full width]
<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 righthand corner makes up for everything.
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.
[View full width]
<meta http-equiv="Content-Script-Type" content="text/javascript" /> <title>Status bar labels</title></head> <body> <img src="noho.gif" alt="Main Street, Northampton" align="left" width="384" height="256" border="0" hspace="5" vspace="0" onmouseover="window.status='Main Street, Northampton'; return true"/> <a href="noho.html" onmouseover="window.status='Click here for more information about Northampton\'s sights'; return true" >Northampton</a> is a great place to visit.
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.
You can also make text move through the status area like a marquee, but the code is a bit involved to go into here.
<h1>Wild Animals</h1>
<br /><a href="javascript:location='toc.html'; parent.topright.location='birdbuttons. html'; parent.bottomright.location='parrots.html'" > Birds</a> <br /> <a href="javascript:location='toc.html'; parent.topright.location='catbuttons.html'; parent.bottomright.location='tiger.html'" > Cats</a>
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 lefthand frame remains constant.
Tip
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.)
if (top.location !="http://www.cookwood.com/html5ed/examples/javascript/wilda nimals.html" & top.location !="http://www.cookwood.com/html5ed/examples/javascript/wilda nimals_geese. html") {top.location.href ="http://www.cookwood.com/html5ed/examples/j avascript/ wildanimals_geese.html"}
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).
Figure 19.14 Notice that the file names of the two images are enclosed in single quotes, since the script itself is contained in double quotes.
[View full width]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <meta http-equiv="Content-Script-Type" content="text/javascript" /> <title>Llumi's big cat dreams</title> </head> <body> Point at Llumi to see what she's thinking. <a href="llumipage.html" onmouseover= "document.catpic.src='dream.jpg'" onmouseout="document.catpic.src='real.jpg'" > <img src="real.jpg" name="catpic" width="143" height="83" alt="Llumi"/></a> </body> </html>
Tip
This script says "if the requested page isn't displayed in one of the allowed framesets, display this frameset instead".
11. Type name="imgname", where imgname identifies the space for the images that will be loaded. 12. Type width="w" height="h", where w and h represent the width and height of the images, respectively. 13. Type alt="alternate text", where the alternate text describes the initial image. 14. Add other attributes to the img tag as desired (see Chapter 6, Using Images). 15. Type /> to complete the img tag. 16. Type </a> to complete the link tag. 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).
Tips
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.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1 transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /> <meta http-equiv="Content-Script-Type" content="text/javascript" /> <title>Llumi's big cat dreams</title> <script type="text/javascript" language="javascript" src="loadimages.js"></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="Llumi"/></a> </body> </html>
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".
[View full width]
<h1>Nathaniel Hawthorne</h1> Nathaniel Hawthorne was one of the most important writers of 19th century America. His
most famous character is <a href="javascript:location='hawthorne.html'; window.open('hester.html', 'characters', 'height=150, width=150, scrollbars=yes')" > Hester Prynne</a>, a woman living in Puritan New England. Another famous object of Hawthorne's writing was <a href="http://www.ripon.edu/dept/pogo/presiden
Figure 19.21. When the visitor clicks a link....
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.
Global Reach (http://www.glreach.com/globstats/) estimates that only 40% of the Web surfing public speaks English. That means that roughly 60% hopes that your Web page is written in some other language. And while many languages (particularly in Western Europe and the United States) are written with the same alphabet, many are written with scripts of their own: Cyrillic, Greek, and Chinese, just to mention a few. In addition, there are many useful symbols common to English as well as other languages that are not available in the current default system, known as ASCII. 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.
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 Greek sigma is character 03B4 in Unicode.
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 doublebyte 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).
Figure 20.4. When I save the document, I am sure to choose the same encoding: shift-jis , in this case.
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-
8, as well as many regional encodings, although they often require the installation of an additional language kit of some sort. Older browsers may only be able to support individual regional encodings. 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.8. In BBEdit on the Mac, click the Options button in the Save As dialog box, and then check both Save as Unicode and UTF-8 Encoding to save in UTF-8. I don't recommend checking Include Byte-Order Mark since some browsers (notably Internet Explorer) choke on it.
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) .
Once a file is encoded, there's no easy way to figure out which encoding was used. I haven't seen a browser or text editor than can figure it out on its own. So, if you save a file with a particular encoding you have to manually open the file with that encoding in order to edit it. Otherwise, the characters that differ between your system's default encoding and the encoding in which you originally saved the file will turn into garbage.
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.11. Luckily, you know which encoding the file is in. Select it from the menu and the characters are again displayed properly.
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.
Tips
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.
1. In the head section of your page, type <meta http-equiv="Content-Type" content="text/html; . 2. Then type charset=code", where code is the name of the encoding with which you saved your page. 3. Type /> to complete the meta tag. 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.
Tips
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
in Unicode, you can use IE for Windows to convert the file to any of the encodings that it recognizes (by opening the file and choosing File > Save As). IE 6 for Windows, when browsing a page with an encoding it's not set up for, will automatically ask the visitor if they'd like to download the appropriate resources. This is an important reason to include the proper encoding. You can theoretically also add the charset attribute to a link or script to describe the associated files' encodings. However, this feature is not yet widely supported.
Or type #n, where n is the base 10 number for your character ( Figure 20.16). Figure 20.16. A numeric reference is comprised of an ampersand, a hash symbol (#), the numeric code for the character, and a semicolon. You can use numeric references to insert any character from the Universal Character Set. This reference is also for an .
Or type entity, where entity is the name of the entity that corresponds to your character (Figure 20.17). Figure 20.17. An entity reference, also known as character entity references or named references, is made up of an ampersand, the character's name, and a semicolon. There are 252 named references that you can use in your (X)HTML pages. They are case-sensitive. This reference is also for an .
3. Finally, type ; (a semicolon). 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.
[View full width]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/ xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=windows-1252" /> <title>Character References</title> <style>p {font-size:24px}</style> </head> <body> <p>“Parla vost é anglès?” he asked.</p> <p>“Yes, a little, ” she said.</p> <p>“How much is that in euros? ” he asked.</p> <p>“€ 25,”she replied.</p> </body> </html>
Figure 20.19. The characters display properly. Note that the visitor's browser must have an appropriate font for the characters.
Figure 20.20 Specify the principal language in the html tag. Here I've used fr for French. You can override that value in individual elements, as I've done for the English paragraph at the bottom of this Web page. Note that this page was encoded with UTF-8 so I wouldn't have had to use character references had there been any accented characters.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/2000/REC-xhtml1 20000126/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr" > <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>Quotes in French</title> <style>p {font-size:24px}</style> </head> <body> <p>Alceste dit <q>Mais enfin, vos soins sont superflus.</q> </p> <p xml:lang="en" lang="en" >Alceste says <q>But in the end, what you want is superfluous.</q></p> </body></html>
Figure 20.21. Internet Explorer for Mac displays guillemet quotes when the language specified is French but curly quotes if the language is English.
Tips
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-macroman 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).
Within the opening html tag, type xml:lang="xx" lang="xx", where xx is the two letter abbreviation for your page's main language.
Tips
The value of xml:lang overrides the value for lang. You may add the xml:lang and lang attributes to almost any element to define the language for that element and override the language noted in the html tag). Browsers may use this information to determine hyphenation, assist spell checkers and speech synthesizers, etc. Search engines may use this information, but they also use proprietary algorithms to determine which language a page is in. Note that since encodings often encompass more than one language, this tag lets you be more explicit about which language you've actually used. You can find a list, officially called ISO 639-2, of the two-letter abbreviations for most languages at: http://www.loc.gov/standards/iso639-2/langcodes.html and also at http://www.w3.org/WAI/ER/IG/ert/iso639.htm. Be sure to use the two-letter, not the three-letter abbreviations.
5. Type />. Figure 21.1 The basefont element should come directly after the opening body tag.
[View full width]
<body> <basefont size="5" color="red" face="Trebuchet MS"/> <h1>Barcelona Night Life</h1> <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 <a href="http://www.bcn.es/english/ihome.htm" target="_blank">Barcelona</a> than in the rest of the European community <i>combined</i>. Don't get me wrong, 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> <p>The opinions expressed on this page are mine and mine alone.</p> </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.3. Netscape 6 (like Opera, not shown) completely ignores the basefont element.
Figure 21.4. Netscape 4.x supports only the size attribute for basefont, but ignores the color and face attributes.
Figure 21.5 The font element is useful for localized formatting. Here we enlarge the initial B in the first paragraph, highlight a phrase in the text with a different color, and set a new font and size for the disclaimer at the bottom.
[View full width]
<body> <basefont size="5" color="red" face="Trebuchet MS"/> <h1>Barcelona Night Life</h1> <p><font size="+2"> B</font>arcelona 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 <a href="http://www.bcn.es/english/ihome.htm" target="_blank">Barcelona</a> than in the rest of the European community <i>combined</i>. <font color="#660000"> Don't get me wrong, </font> 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>
<p><font face="Copperplate, Univers, Arial Black" size="2">The opinions expressed on this page are mine and mine alone. </font></p> </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.
You may specify more than one font as a value for face. For more details, follow the syntax described under Formatting Bits of Text on page 347. Only use one basefont tag in each (X)HTML document. To change individual characters, use the font element (see page 347) , or preferably styles (see page 157) . Netscape 4 only supports the basefont element with the size attribute. Netscape 6 does not support the basefont element at all. Headers are not affected by the size attribute, though they do gain the color and face specified by the basefont element (though only in Explorer). Links are not affected by the color attribute, though they do gain the size and face specified by the basefont element. To change the color of links, see page 350. The font element (see page 347) overrides the basefont element which overrides the text attribute of the body tag (see page 349) . Where do styles fit in, you might ask? They override basefont (and text) but not font. In HTML, you can omit the forward slash from the end of the tag. In XHTML, of course, it's required. The basefont element is deprecated and as you can see is extremely inconsistent from one browser to the next. It should be avoided. Use style sheets instead (see page 157).
Figure 21.8. Netscape 6 supports the font element, but since it ignores the basefont element, the effect is very different in this example. (Netscape 4 also supports the font element.)
Figure 21.9 You can also set the default color for the text by using the text attribute in the body element.
[View full width]
<body text="red" > <h1>Barcelona Night Life</h1> <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 <a href="http://www.bcn.es/english/ihome.htm" target="_blank">Barcelona</a> than in the rest of the European community <i>combined</i>. Don't get me wrong, 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> <p>The opinions expressed on this page are mine and mine alone.</p> </body>
Figure 21.10. The text attribute is almost universally supported. Shown are Netscape 6 (above) and Explorer 6 (below), both for Windows.
Tips
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) .
The font element does affect the size of headers (in contrast with basefont , which does not see page 346). Note that font is an inline element and should only contain other inline elements or text. You cannot, therefore, span font information across paragraphs, table cells, or any other block-level element. When you get sick of writing <font> and </font>, you start using style sheets.
<body text="red" link="gray" vlink="green" alink="yellow" > <h1>Barcelona Night Life</h1> <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 <a href="http://www.bcn.es/english/ihome.htm" target="_blank">Barcelona</a> than in the rest of the European community <i>combined</i>. Don't get me wrong, 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> <p>The opinions expressed on this page are mine and mine alone.</p> </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).
Tips
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.
Figure 21.13 Note that besides adding the underline and strike through text, I've also removed the default red color!for simplicity's sake.
[View full width]
<body link="gray" vlink="green" alink="yellow" > <h1>Barcelona Night Life</h1> <p>Barcelona is such a <u>great</u> 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 <a href="http://www.bcn. es/english/ihome.htm" target="_blank">Barcelona</a> than in the rest of the European community <i>combined</i>. Don't get me wrong, 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> <p>The opinions expressed on this page are mine <strike> and mine alone</strike> .</p> </body>
Figure 21.14. Most browsers support the strike and u elements.
Tips
See page 46 and the inside back cover for a list of common colors and instructions for creating your own.
Make sure you test the colors of your text, links, and background together. Be careful when choosing different colors for links from page to page. If your visitors can't tell what to click on or which pages they've already visited, they may decide not to click on anything. The basefont and font elements can change a link's size or font face (see pages 344%348). The link, vlink, and alink attributes have been deprecated. You can use styles to control the colors of links (see pages 141 and 174) .
<body> <h1>Famous Catalans</h1> <p><font size="+3">E</font>ver heard of Montserrat Caballé, Josep Carreras, and Victòria dels Àngels? (You may know these last two by their Spanish names: José Carreras and Victoria de los Ángeles.) Did you know they were <blink>all Catalans</blink> ? The things you learn!</p> </body>
Figure 21.16. Blinking text appears normal (top), then disappears (bottom), then reappears.
Figure 21.17. Internet Explorer does not now and probably never will recognize the blink tag.
Tips
Both the strike and u tags have been deprecated. There is also a shorthand s tag for strike that has also been deprecated. There are two tags that have not been deprecated that you can use for strike out and underline text: del (for deleted) and ins (for inserted) respectively (see page 81). They are not supported by Netscape 4. Although fonts and colors let designers indicate links in new ways, most Web sites continue to use underlining to show links to other Web pages (see page 117) . You may confuse visitors by underlining text that is not a link. Lynx displays em and strong text with an underline. You can apply (or remove) underlining, strike out, and even overlining with styles. For more details, consult Decorating Text on page 174.
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.
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.
logical sections, positioning elements in layers, and determining when line breaks should, and shouldn't, occur. Note that all of the elements discussed in this chapter are either deprecated (see page 343) or nonstandard 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.
<body bgcolor="#FF00FF" > You can change the color of the background of your page--but make sure your 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.
For more information on setting the link colors, consult Changing the Color of Links on page 350. For more information on setting the text color, consult Choosing Default Characteristics for Text on page 344 or Another Way to Choose Default Colors on page 349. To use an image for the background, consult Using Background Images on page 355. Most browsers let your visitors override any background color set by you, the page designer (Figure 22.3). Figure 22.3. This is Netscape's preferences dialog box in which your visitors can choose not to use the colors that you, the designer, have specified for a page. (Explorer has a similar option.)
The bgcolor attribute has been deprecated. I recommend using styles to control the background (see page 182).
3.
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.
Figure 22.5 To keep text from overlapping my background image along the left side, I've placed the text in a table with two columns, and left the first column empty. For more information about tables, consult Chapter 14, Tables. Notice you can't add extra image attributes (like width or height, for example) to the body tag.
[View full width]
<body background="waveswide.gif" > <table cellspacing="2" cellpadding="1"> <tr> <td width="80" valign="top"> </td> <td valign="top"> <h2>The Mardi Gras Home Page</h2> Mardi Gras is gearing up to be the best ever this year. Come down to New Orleans and see how we throw a party! <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).
With an image editing program, try increasing the brightness and lowering the contrast to soften the background image so it doesn't distract from your page's content. Save your visitor loading time by using the same background image on a series of pages. After the image has been loaded for the first page, each subsequent page uses a cached version which loads much more quickly. The background attribute is deprecated. For details on using styles to create a background image, see page 182.
<body> <center><h2>The Earth's Core</h2> <p>At the center of the earth, more than 6000 kilometers from the surface, the temperature is a toasty 6500 degrees Kelvin.</p> </center> <p>Not bad for a little planet.</p> </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.
Tips
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.
[View full width]
<body leftmargin="0" topmargin="0" marginwidth="0" marginheight="0" > If you set all the margin attributes to 0, the page will start in the top leftcorner, leaving no margin at all. </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.
Figure 22.11 If you only use say, the attributes that Netscape recognizes (marginwidth and marginheight), then Netscape will display the margins properly but Explorer will not. And if you only use IE's proprietary attributes, then Explorer will understand and Netscape will not.
[View full width]
<body marginwidth="0" marginheight="0" > If you set all the margin attributes to 0, the page will start in the top leftcorner, leaving no margin at all. </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
You can set only the left or only the top margin if you wish. The leftmargin and topmargin tags were developed by Microsoft and are completely non-standard. The attributes marginwidth and marginheight are part of the standard (X)HTML specifications when used with frame (see page 249), but not with body. Thank goodness for CSS which lets us set the margins in a standard way that all current browsers understand. For more details, consult Setting the Margins around an Element on page 189.
<body> <h1><nobr>The Worldwide Conference on Keeping It Together</nobr></h1> <p>Opening Hymn:</p> <p>We have to keep it together<br /> Never come apart,<br /> Birds of a feather,<br />Close to our heart.</p> <p><em>12 December 1996. London.</em> The Worldwide Conference on Keeping It Together met today for the first time as a group. They had originally met separately in their respective states. Discussed today was whether or not the group should vote on a charter together or whether each sovereign state should vote separately. They couldn't quite keep it together.</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).
Figure 22.14. With the nobr tags, the headline is kept on one line, even when it extends past the width of a visitor's browser window.
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.
<body> <h1><nobr>The Worldwide Conference on <wbr>Keeping It Together</nobr></h1> <p>Opening Hymn:</p> <p>We have to keep it together<br /> Never come apart,<br /> Birds of a feather,<br />Close to our heart.</p> <p><em>12 December 1996. London.</em> The Worldwide Conference on Keeping It Together met today for the first time as a group. They had originally met separately in their respective states. Discussed today was whether or not the group should vote on a charter together or whether each sovereign state should vote separately. They couldn't quite keep it together.</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.
Tips
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. To specify the space between paragraphs: Place the cursor between the two lines to be separated. Type <spacer. Type type="vertical". Type size="n", where n is the amount of space, in pixels, that should appear between the two lines. 5. Type the final >. 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. 1. 2. 3. 4.
</head> <body> You can use vertical spacers to specify the exact amount of space between each paragraph. <spacer type="vertical" size="48"> However, they are only supported by Netscape 4.x and so should be avoided like the plague. </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) .
The spacer tag with a value of vertical for the type attribute creates an automatic line break. You do not need to use the p tag it will create the same amount of space it always has, in addition to the spacer element's space.
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:
1. 2. 3. 4. 5. 6. Place the cursor where you want the space to appear. Type <spacer. Type type="horizontal". Type size="n", where n is the desired indent size, in pixels. Type the final > tag. Type the text of the indented paragraph.
Figure 22.21 Use horizontal spacers for indenting paragraphs, or any place you need to add an invisible, horizontal block of space.
[View full width]
<html ><head> <title>Using spacers</title></head> <body> <spacer type="horizontal" size="36"> You can use spacers as a substitute of tabs (which don't exist in HTML) in order to indent paragraphs. <p><spacer type="horizontal" size="36"> However, since the spacer tag is only supported by Netscape 4.x, it should be avoided.</p> </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) .
Figure 22.24 You can use lists (without the li tag) to create indented paragraphs.
[View full width]
<body> <h2>Sneaky ways to create indents</h2> <p>Using lists to create indents is not exactly legal but it does work--in any browser. The W3 Consortium would prefer that you use styles. But until you do, list indents will come in handy.</p> <ul>The basic technique is to create a list for each section that you want to indent. Don't create any list items--since they are always marked with a bullet. Oh, and there's no way to make hanging indents or first-line indents. If you want to get fancy, use styles.</ul> </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.
Tips
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. 2. 3. 4.
<html><head><title>Creating blocks of space</title></head><body> <spacer type="block" width="100" height="100" align="left"> If you like to create big margins around your text, spacers are ideal for the job. <p>Just use the spacer tag as if it were an invisible image. And wrap the text right around it as usual. </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.)
Tips
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).
<p><b>Or, perhaps better yet, use a pixel shim. It has the advantage of being recognized by most browsers, and you can make it any color you want.</b></p> </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).
Creating Columns
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:
1. In your HTML document, type <multicol. 2. Type cols="n", where n is the number of columns desired. Each column will be the same size. 3. If desired, type gutter="n", where n is the width of the space between the columns, in pixels or as a percentage. 4. If desired, type width="n", where n is the width of the entire column set, including the gutter, in pixels or as a percentage of window size. 5. Type the final > to finish the column definition. 6. Create the elements (text or images) that will go into the columns. 7. Type </multicol>. 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.)
[View full width]
<html><head><title>Creating columns</title></head><body> <multicol cols="2" gutter="30" width="85%"> <p><font size="-1">A multicolumn layout is typical of newspaper articles. You start reading down the first column and when you read [snip]</font></p> <p><font size="-1">Use returns where necessary to start a new line. Or use a line break instead. Or insert images, or whatever.</font></p> <p><font size="-1">Hey, the headline's a joke, get it? </font></p> </multicol> <font size="-1">After the final multicol tag, you can
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.
Figure 22.33. Internet Explorer does not recognize the multicol tag. The last paragraph runs into the column text, since there was no p tag.
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.
If you don't use the gutter attribute, Netscape automatically leaves 10 pixels between columns. Only Netscape 4.x supports multicol .
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.
[View full width]
<body> <layer id="layer1" top="10" left="50" width="100" height="100" bgcolor="yellow" z-index="1">This is the very bottom layer. It's yellow.</layer> <layer id="layer2" top="20" left="60" width="160" height="80" bgcolor="orange" z-index="2">This is the second layer from the bottom. It's orange.</layer> <layer id="layer3" top="40" left="80" width="40" height="40" bgcolor="black" z-index="3"> <font color="white">This is layer 3. It's black.</font></layer> <layer id="layer4" top="70" left="200" width="100" height="100" bgcolor="red" z-index="1">This layer is at the same level as the first one, that is, the bottom.</ layer> <nolayer>This page contains elements positioned with layers. It only works in Netscape Communicator 4.</nolayer> </body>
Figure 22.35. There are four layers in this example. Layers become really useful when combined with JavaScript.
Figure 22.36. Explorer makes a total mess of layers with content!despite the nolayer option.
<body>
<layer id="layer1" top="10" left="300" width="50" height="60" bgcolor="aqua" zindex="1" src="layer1.html" ></layer> <layer id="layer2" top="50" left="30" width="300" height="80" bgcolor="magenta" zindex="2" src="layer2.html" ></layer> <nolayer>This page contains elements positioned with layers. It only works in Netscape Communicator 4.</nolayer> </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).
Figure 22.39. Since Explorer completely ignores layer tags, it won't try to insert the content of layers defined by the src attribute. Instead, it simply and cleanly displays the contents of the nolayer tags.
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.
To prepare an Apache server to serve WML files and images from a particular directory:
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.
5. Save the file as text only and upload it to the directory from which you wish to serve the WML files. Its name in the directory should be .htaccess (with that initial period). 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 addtype text/vnd.wap.wml wml addtype text/x-hdml hdml addtype image/vnd.wap.wbmp wbmp
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).
<?xml version="1.0"?> <!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.3//EN" "http://www.wapforum.org/DTD/wml13.dtd "> <wml>
</wml>
Tips
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.
<?xml version="1.0"?> <!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.3//EN" "http://www.wapforum.org/DTD/wml13.dtd "> <wml> <card id="welcome" title="Welcome" newcontext="true">
</card> </wml>
Figure 23.6. The title attribute is displayed at the top of the microbrowser. (Openwave on left, Nokia at right.)
Tips
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.
<?xml version="1.0"?> <!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.3//EN" "http://www.wapforum.org/DTD/wml13. dtd"> <wml> <card id="welcome" title="Welcome" newcontext="true"> <p align="center"> <big><b>The Cat and Otter<br /> Bistro/Pub</b></big> </p> </card> </wml>
Figure 23.8. Not all microbrowsers support all of the formatting options, though both of these simulators do.
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
Some browsers can display (very small) images. You must include alternate text for browsers which cannot.
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.
[View full width]
<?xml version="1.0"?> <!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.3//EN" "http://www.wapforum.org/DTD/wml13. dtd"> <wml> <card id="welcome" title="Welcome" newcontext="true"> <p align="center"> <img src="cat.wbmp" alt="logo" /> <br /> <big><b>The Cat and Otter<br /> Bistro/Pub</b></big> </p> </card> </wml>
Figure 23.10. Images should be no larger than 100 pixels across. Be restrained!
Tips
Most microbrowsers only support images in WBMP format. Adobe Photoshop 7 can create new or convert existing images to WBMP format. Once your image is ready, choose File > Save for Web. Then choose WBMP in the format menu under Settings on the right side of the window that appears. Use the smallest size images you can stand. For some perspective, the cat in Figure 23.10 is a scant 54 pixels wide and 45 pixels high. You can use percentages to specify the height and width. Note that percentages are relative to the screen size, not to the intrinsic size of the image itself. Make sure your server is prepared to serve WBMP images (see page 370).
Creating a Table
You can use a table to align several columns of text on a page.
To create a table:
1. After an initial p tag, type <table to begin. 2. Type columns="n", where n is the number of columns your table will have. 3. If desired, type align="xy...", where x sets the alignment for the first column, y sets the alignment for the second column, and so on, and each value is one of L (for left), R (for right), or C (for center). 4. Type > to complete the initial table tag. 5. Type <tr> to begin the row.
Type <td> to start the cell. Enter the contents of the cell. Type </td> to finish the cell. Repeat steps 6!8 for each cell in the row. Type </tr> to complete the row. Repeat steps 5!10 for each row. Type </table> to complete the 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.
<card id="specials" title="Today's Specials"> <p> <table columns="2" align="RL"> <tr><td><b>Soup</b></td><td>Cream of Mushroom</td></tr> <tr><td><b>Entree</b></td><td>Seafood Fideua, specialty of the house</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" ).
Tips
Not all microbrowsers support tables. You may not nest tables. You may not use any other table attributes besides the ones described here. You may have to set the enclosing paragraph's mode to nowrap (see page 373) in order for the table to display properly.
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.
<card id="welcome" title="Welcome" newcontext="true"> <p align="center"> <img src="cat.wbmp" alt="logo" /><br /> <big><b>The Cat and Otter<br /> Bistro/Pub</b></big> </p>
<p><a href="#specials" title="Go">Specials</a> <br /><anchor title="Reserve">Reservations<go href="#res"></go></anchor> <br /><anchor title="Where?">Directions<go href="#dir"></go></anchor> </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).
Tips
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,
assigns a link directly to one of the phone's physical buttons and does not affect the main content at all. In some browsers, the accesskey is output just before the link as a visual clue to the visitor. In others, it's invisible.
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). Or type <prev> to have the button go to the previous card viewed. Or type <refresh> to refresh the card, and any variables it contains. Or type <noop> to disable the button. 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.
<card id="welcome" title="Welcome" newcontext="true"> <p align="center"> <img src="cat.wbmp" alt="logo" /><br /> <big><b>The Cat and Otter<br /> Bistro/Pub</b></big> </p> <p><a href="#specials" title="Go">Specials</a>
<br /><anchor title="Reserve">Reservations<go href="#res"></go></anchor> <br /><anchor title="Where?">Directions<go href="#dir"></go></anchor> </p> <do type="accept" name="Help" label="Help"><go href="#help" /></do> </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
example, you use the accept type to program the left button and the prev type for the right button. Others list all the do elements, regardless of type, under a general Options button. The WML specifications do not require user agents to map types to particular buttons. No two do elements may have the same values for the name attribute. If you omit the name attribute, the value for the type attribute is used by default. The difference between the do element and the anchor element? See the last tip under Creating a Link on page 376. Some browsers override any URL specified in the go action of a do element with type prev and insist on creating a standard Back button that goes to the previously visited page. If you create two prev do elements, then you can specify the URL in the second one (although this isn't a real solution if what you wanted was to change the Back button's destination). You cannot set an accesskey for a do element. The default label for the prev type is BACK. For the accept type it's OK. While there are other valid types, these are the most common and best supported. If you do not create additional actions in step 6, you may combine steps 5!7 into a single tag: e.g., <go href="#cardid" /> or <noop />, or whatever.
<card id="welcome" title="Welcome" newcontext="true"> <onevent type="onenterforward"> <go href="#help" /></onevent> <p align="center"> <img src="cat.wbmp" alt="logo" /><br />
Figure 23.19. When your visitors go the main page, they are immediately shuttled to the Help screen.
Tips
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.
[View full width]
<card id="help" title="Help"> <onevent type="ontimer"> <prev /> </onevent> <timer value="30" /> <p>Choose the <b>Specials</b> link to see what delicious food we've got today. Choose the <b>Reservations</b> link to have us reserve you a table. Click <b>Where?</b> to get directions to our restaurant and click the <b>Help</b> button to get this screen. </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:
1. 2. 3. 4. 5. Within a card, type <onevent type="ontimer"> Create a go, prev, refresh, or noop action, as described in steps 5!7 on page 378. Type </onevent>. Within the same card, type <timer. If desired, type name="var", where var is the name of the variable that contains the amount of time (in tenths of seconds) that should pass before the action in step 2 occurs. 6. Type value="default", where default is the amount of time (in tenths of seconds) that should be used if the name attribute in step 5 is omitted, or if its corresponding variable is not set. 7. Type > to complete the timer element.
Tips
Only one timer element is permitted in each card. If you only want to send the visitor to another card when the timer goes off (and not, for example, set a variable or post field data), you can use this shortcut: <card ontimer="destination.url"> and then follow steps 4!7 above to set the timer.
Figure 23.21. Since your visitors return to the home page via a prev action, the onenterforward condition is not fulfilled (and they don't get whisked back to the Help page). I should probably add that sending your visitors around like this is a good way to annoy them. Instead, use onevents for setting variables (see page 383) and posting data to the server (see page 388).
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.
Click <b>Where?</b> to get directions to our restaurant and click the <b>Help</b> button to get this screen. If you get really stuck, just <anchor title="Call">call us<go href="#callcard" /></anchor>
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.
Tips
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.
<card id="res" title="Reserve a Table"> <onevent type="onenterforward"> <refresh><setvar name="number" value="2" /> </refresh> </onevent> <p> Would you like us to reserve a table for $(number)?</p> </card>
Figure 23.25. The content of the variable ("2", that we set earlier) is output instead of the variable name.
Tips
You can clear all variables in a new card by adding newcontext="true" to the opening card tag. You can also set (or let your visitor set) variables with text boxes (see page 384) and menus (see page 386) . One typically sets a variable within a refresh element. You can add a refresh element to an anchor (see page 376) , to a do element (see page 378) , or to an onevent element (see page 380) . Variables set or updated in one card work in other cards, and even in other decks. There are a slew of special codes for escaping (or not) the variables. You can find them in the WML specifications at http://www.wapforum.org or on my Web site (http://www.cookwood.com).
A (for an uppercase letter or symbol) a (for a lowercase letter or symbol) N (for a number) n (for a number or symbol) X (for an uppercase letter, number, or symbol) x (for a lowercase letter, number, or symbol) 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).
<card id="res" title="Reserve a Table"> <onevent type="onenterforward"> <refresh><setvar name="number" value="2" /> </refresh> </onevent>
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.
Since the *f format allows for any number of characters to be entered, including zero, it implies that no input is acceptable, regardless of the emptyok attribute. You may also specify the standard (X)HTML input attributes: size, maxlength , tabindex, and title. For more details about input attributes, consult Creating Text Boxes on page 272. If a variable with the same name as that specified in step 2 has already been set (see page 383) , its value will be the default value for the input box, and will override the contents of the value 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:
1. Type <select to begin. 2. Next type name="var", where var is the name of the variable that will hold the data from this input box. 3. If desired, type value="default", where default is the value of the menu's variable (named in step 2) if no option is chosen by the visitor. 4. If desired, type iname="var_index", where var_index is the name of the variable that will contain the number of the option that the visitor has selected. (Each option is numbered in order, starting with 1. If no option is selected, the var_index variable will contain "0".) 5. If desired, type ivalue="default_option", where default_option is the number of the option that should be selected by default. 6. If desired, type multiple="true" to allow the visitor to choose more than one option. The default is false. 7. If desired, type tabindex="n", where n indicates the order in which elements in the page should be tabbed through. For more details, see page 289. 8. Type >. 9. Next, type <option. 10. If desired, type value="var_value", where var_value is the value that the menu's variable (named in step 2) will get if the visitor chooses this option. 11. If desired, type title="label", where label may be used by the microbrowser to identify the option to the visitor. 12. If desired, type onpick="url", where url is the file that should be loaded if the visitor chooses this option. 13. Type >. 14. Enter text that identifies the option. 15. Type </option>. 16. Repeat steps 9!15 for each option. 17. Type </select> to complete the menu. Figure 23.28 Here we create a menu titled Smoking with two options, Yes or No.
[View full width]
<p>Number in party?<input type="text" name="number" format="2N" /> Smoking? <select name="smoke" title="Smoking?"> <option value="no">No</option> <option value="yes">Yes</option>
</select>
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 title="Meat"> <option value="chicken">Chicken Parmesian</option> <option value="steak">Filet Mignon</option> <option value="veal">Veal Cutlets</option> <option value="fish">Seafood Fideua</option> </optgroup> <optgroup title="Vegetarian"> <option value="rice">Rice and Beans</option> <option value="pasta">Pasta Primavera</option> <option value="ravioli">Spinach Ravioli</option> </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.
Tips
Different browsers treat the option element's title in distinct ways. (Surprise!) Some browsers use the title to label the button that activates the option, others use it to create the menu itself, or ignore it completely if you've added text in step 14. (However, if you don't set the text in step 14, some browsers will show nothing at all for that option in the menu.) You may group option elements with optgroup (see page 277). Use a title attribute for identification (and not a label attribute as for (X)HTML). Some browsers ignore optgroup elements. Add an onevent element with type="onpick" to an option element (instead of step 12 above) if you want to set a variable (see page 383) and/or post data to the server (see page 388) when the visitor chooses the option. If a variable with the same name as that specified in step 2 has already been set (see page 383), its value will be the default value for the input field, and will override the contents of the value attribute (but not the ivalue attribute).
<option value="ravioli">Spinach Ravioli</option> </optgroup> </select> <do type="accept"> <go href="http://www.cookwood.com/cgibin/reserve_table.cgi " method="post">
<postfield name="number" value="$(number)" /> <postfield name="smoke" value="$(smoke)" /> <postfield name="dinner_index" value="$(dinner_index)" /> </go> </do></p> </card>
Figure 23.33. When the visitor activates the OK button (created with the accepttype 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
use strict; use CGI ':standard'; print "Content-type: text/vnd.wap.wml\n\n "; print '<?xml version="1.0"?> <!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.1//EN" "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
You may also use the get method in step 2. It may be better-supported on some browsers but purportedly cannot handle more than 127 characters at a time. You can use Perl or ASP or any other scripting language to gather information and then use the results to dynamically generate a response. Note that the script has to create a well-formed WML document with the proper headers. For example, the content-type header should look like this: Content-type: text/vnd.wap.wml , followed by two new lines. Don't forget to create the proper DOCTYPE and opening and closing wml elements and card elements (Figure 23.34). You may also have to let your server know you may be serving WML MIME types from your cgi-bin directory (see page 370). You can test the results of a such a script on a regular Web browser. Pass variables to the script by affixing them to the URL in the form script.url?name=value&name2=value2 . The browser should tell you that it doesn't know what to do with a WML file, but it will let you save it. Save the result file and open it with your text editor to see the file that will be sent back to the mobile device. First and foremost, check its syntax to see if it's a well-formed WML document. Then check to see if it does what you want it to do. Once you get the major bugs worked out, you can start testing it on a simulator or real mobile device (both of which are a lot slower). For more information about testing WML pages, consult Testing WML Pages on page 392.
<?xml version="1.0"?> <!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.3//EN" "http://www.wapforum.org/DTD/wml13.dtd "> <wml> <template> <do type="prev"><prev /></do> </template> <card id="welcome" title="Welcome" newcontext="true">
<p align="center"> <img src="cat.wbmp" alt="logo" /><br /> <big><b>The Cat and Otter<br />
Figure 23.37. Now every card has a Back button.
Tips
You can have only one template element per deck. You may override template instructions by specifying identically named events in individual cards. You can theoretically deactivate programmed buttons on individual cards by using the <noop /> element (see the last part of step 5 on page 378) though I've had varying success doing so. You can also create conditional or scheduled actions in each card by adding one of the following attributes to the opening template tag:
onenterforward="url" , onenterbackward="url" , or ontimer= "url", in which case, skip step 2 above. The timer element goes in the individual card (see page 381), even if you set ontimer with the template element.
<?xml version="1.0"?> <!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.3//EN" "http://www.wapforum.org/DTD/wml13.dtd "> <wml> <head><access domain="www.cookwood.com" path="/html5ed" /> </head> <template> <do type="prev"><prev /></do> </template> <card id="welcome" title="Welcome" newcontext="true">
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.)
Tips
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/.
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.
Tips
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!
Tips
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).
Figure 24.2. The error found on Line 9 seems to be the problem!instead of a closing </h1> tag, I've put in another opening <h1> tag by mistake. Notice the erroneous message about line 13. This one will disappear when I fix the closing </h1> tag.
Many text editors, like BBEdit, have incorporated syntax checkers. They are great for catching errors before you get to the official validator. Use the DOCTYPE to tell the validator which specifications to judge your HTML and XHTML with (see page 60) . There are other validators out there. I think the ones from the W3C are the best.
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.
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).
Figure 24.5 If an attribute's value contains a single quote, you can just enclose it in double quotes as usual.
<img src="cookie.jpg" alt="Cookie's saying "Enough!"" /> <img src="tough_llumi.jpg" alt='Llumi replies, "This is _my_ jungle."' />
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.
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).
Figure 24.9 Bad! It's hard to break the habit of separating properties and values with the equals sign. But you must, otherwise it'll incapacitate your CSS.
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.
Don't forget to close your brackets. Don't quote values as you do in (X)HTML. The only values that have quotes in CSS are multiword font names (Figures 24.13 and 24.14). Figure 24.13 Bad! Get rid of those quotes around italic, CSS doesn't need them.
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).
Watch the spaces and punctuation between the selectors. Make sure the browser supports what you're trying to do (see page 402). Support for CSS varies widely.
Figure 24.16 The problem is the link to the CSS file!the file is named testpage.css and here I'm linking to testerpage.css. It should be no surprise that the browser can't find the CSS and thus displays the page wrong.
[View full width]
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>Mary Anna, the Iguana</title> <link rel="stylesheet" type="text/css" href=" testerpage.css " /> </head> <body> <img src="iguana.jpg" alt="Iguana" width="220" height="165" /> <h1>Mary Anna, the Iguana</h1> <p>There once was an iguana whose name was <em>Mary Anna</em> her skin was so dry that she'd have to cry Here's some cream: would you please put it onna?</p> </body> </html>
Figure 24.17. Now that the link to the CSS is corrected, the page is displayed properly.
Tips
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.
Figure 24.19. If you select View Source, you can see how Word coded your code, changing your < and > symbols to < and >, converting quotation marks to " and adding all sorts of extra junk.
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.
Figure 24.20. The file name for the image is iguana.jpg but here it is incorrectly referenced as Iguana.jpg, with a capital I.
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.
Figure 24.22. When the page is published to the server, which is case sensitive, the image cannot be found.
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.
h1 {font: 2em "Trebuchet MS", "Helvetica", "Arial Black"; border-bottom: 2px dashed red} img {border: none; float:right} p {white-space:pre} p:first-letter {font: bold 200% "Trebuchet MS";color:green} p>em {font-weight:bold}
Figure 24.24. Explorer 5 doesn't understand the dashed border, gets float a bit wrong (notice that some of the border is beyond the image), and doesn't recognize the first-letter selector.
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.
Tip
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.
<table border="0"> <tr><th colspan="2"> <h1>Mary Anna, the Iguana</h1> </th></tr> <tr> <td><img src="iguana.jpg" align="left" /> </td> <td>There once was an iguana<br /> whose name was Mary Anna<br /> her skin was so dry<br / > that she'd have to cry<br /> Here's some cream: would you please put it onna?</td> </tr></body></html>
Figure 24.28. Most browsers don't blink an eye if you leave off a closing </table> (or </frameset>) tag.
Figure 24.29. Netscape 4, on the other hand, is very strict. The entire table (or frameset) disappears from view.
Still Stuck?
If you've gotten to this page, you're probably frustrated. Don't think I'm being patronizing when I suggest you go take a break. Sometimes the best thing you can do for a problem is leave it alone for a minute. When you come back, the answer may be staring you in the face. If it's not, let me offer you these additional suggestions. 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 helphtml@cookwood.com. 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/)
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?
They also have one very important advantage. If you ever decide to change your Web host (or if they go out of business), you can move your domain to another server and all of your URLs will stay exactly the same.
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!)
2. In the WS_FTP Pro Site Profile Wizard boxes, name your connection so you can find it in the list (Figure 25.4), specify the FTP server (ask your ISP if you're not sure), and enter your user name and password. Click Next for each screen and click Finish when you're done. 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).
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.
5. On the left side of the window, navigate to the directory on your hard disk that has the files you want to upload. 6. Select the desired files in the left frame and click the right-pointing arrow in the middle of the screen. The files are transferred (Figure 25.8). 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):
1. Open your Internet connection. 2. Open Fetch. 3. Choose Customize > Preferences (Figure 25.9), click the Upload tab in the Preferences box that appears, and make sure the Add.txt suffix to Text Uploads box is not checked (Fig. 25.10). Figure 25.9. Choose Preferences in Fetch's Customize menu to open the Preferences dialog box.
Figure 25.10. Click the Upload tab and make sure that the Add .txt suffix option is unchecked.
4. Click OK. 5. Choose File > New Connection. 6. In the New Connection window, enter the server name in the Host box, your user name in the User ID box, your password in the Password box, and, if desired, the path to the directory where you plan to save the Web pages in the Initial directory box (Figure 25.11). 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.
7. Click OK to open the connection. Fetch will make the connection to the server you requested and open the designated directory (or the top directory if you haven't specified one). 8. If necessary, navigate to the desired directory where you wish to place your Web files (Figure 25.12). 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).
9. Click the Put Files button or press Command-T (Figure 25.13). 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
holding down the Command key. When you have selected all the files you wish to transfer, click Choose (Figure 25.14). 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.
Tips
(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) .
3. Create any desired directories (using the Create Directory button) and then navigate to where you want to upload the file (Figures 25.18 and 25.19). Figure 25.18. Create and navigate to the desired directory, if necessary.
Figure 25.19. If you click the Create Directory button, AOL will allow you to name the new directory.
4. Once you're in the desired directory, click the Upload button (Figure 25.20). 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.
Figure 25.22. Click Select File to choose the file that you want to upload from your hard disk.
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
The URL of your pages on AOL is http://members.aol.com/screenname/filename. You can publish up to 2MB per screenname (for a total of 14MB). If you publish files on AOL's Hometown (and thus allow AOL to advertise on your site), they give you a bit more space. It seems unreasonably laborious to me, but AOL's FTP tool only lets you upload one file at a time. Delete or rename files by selecting the desired file, clicking the Utilities button, and then choosing Delete or Rename. The remote file name that you specify in step 5 is the name that the file will have on the server (and in URLs that your visitors type). It doesn't necessarily have to match the name of the file on your hard disk. Of course it must match any URL that refers to it.
Many of AOL's dialog boxes just sit there on the screen instead of disappearing when you're done with them. Don't be afraid to click their close boxes. The good news is that you can also use external (and infinitely better) FTP clients like Fetch and WS_FTP to upload files to AOL. Follow the instructions on pages 408!411, using members.aol.com for the Host name, anonymous as the User name, and your AOL email address for your password. You must be connected to AOL when you use the external FTP program for security reasons. Also note that any files in your AOL server space (except those in the private folder) are visible to anyone who can use an external FTP client. They can't delete, change, or upload new files, but they can see what's there.
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).
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
Use keywords in your title (see page 64) . Use keywords in headers (see page 65). Keep the content of your page as specific and focused on your topic as possible, and be sure to include your keywords. Specify keywords in a meta tag (see page 417) . Use keywords in an image's alt tag, where applicable (see page 105) .
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.
[View full width]
<head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>Barcelona's Market</title> <link rel="stylesheet" type="text/css" href="barcaeng.css" /> </head> <body> <h1>Barcelona's Market</h1> <img src="mercat1.gif" height="167" width="144" alt="Entrance to Barcelona 's Boquer a Market " class="right" /> <p>This first picture shows the stalls in the entranceway to the <em>Mercat de la Boquer a</em>, the Barcelona central market that is just off the Rambles. It's an incredible place, full of every kind of fruit, meat, fish, or whatever you might happen to need. It took me a long time to get up the nerve to actually take a picture there. You might say I'm kind of a chicken, but since I lived there, it was just sort of strange. Do you take pictures of your supermarket?</p>
Figure 26.2. Use keywords as consistently and naturally as you can. If you do it right, there's no reason to cheat.
<head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <meta name="keywords" content="Barcelona, market" /> <title>Barcelona's Market</title> <link rel="stylesheet" type="text/css" href="barcaeng.css" /> </head> <body> <h1>Barcelona's Market</h1> <img src="mercat1.gif" height="167" width="144" alt="Entrance to Barcelona's Boquer a Market" class="right" /> <p>This first picture shows the stalls in the entranceway to the <em>Mercat de la Boquer a</em>, the Barcelona central market that is just off the Rambles. It's an incredible place, full of every kind of fruit, meat, fish, or whatever you might happen to need. It took me a long time to get up the nerve to actually take a picture there. You might say I'm kind of a chicken, but since I lived there, it was
Tips
Use a combination of very unique and more general words to describe the contents of your page. Chihuahua is unique, but dog may also net you some visitors who didn't realize they were interested in Chihuahuas (or couldn't spell it). Actually, adding misspelled keywords (in addition to correctly spelled ones) is not such a bad idea. You might offer several alternative spellings for foreign words. More words is not necessarily better. According to Paul Boutin (see page 415), the closer you match what a prospective visitor types (with no extra words), the higher up you'll get listed in the results. If you're using frames, include keywords in each frame and in the frameset itself. Some search engines offer specific tips on using the meta tag to describe your site. Check out: http://help.altavista.com/search/faq_web#9. Google ignores keywords specified with a meta tag. It's more interested in keywords that appear in the page's content.
<head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <meta name="keywords" content="Barcelona, market" /> <meta name="description" content="An insider's view of the Barcelona market, complete with photos." /> <title>Barcelona's Market</title> <link rel="stylesheet" type="text/css" href="barcaeng.css" /> </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.
Tips
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.
You can also add information to your page about who wrote it, what program was used (if any) to generate the (X)HTML code, and if it is copyrighted. Note, however, that search engines do not currently use this information (though they may some day), and browsers don't display it.
<head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <meta name="keywords" content="Barcelona, market" /> <meta name="description" content="An insider's view of the Barcelona market, complete with photos." /> <meta name="generator" content="BBEdit 6.5.2" /> <meta name="author" content="Liz Castro" /> <meta name="copyright" content="© 2002 Liz Castro" /> <title>Barcelona's Market</title> <link rel="stylesheet" type="text/css" href="barcaeng.css" /> </head> <body> <h1>Barcelona's Market</h1>
Figure 26.7. The meta information is always invisible in the browser.
Tips
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.)
<head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <meta name="copyright" content="© 2002 Liz Castro" /> <meta name="robots" content="noindex, nofollow" /> <title>Untitled</title> </head> <body> This is my personal page! I don't want it to be indexed by search engines. </body> </html>
Tips
Separate multiple values with a comma and a space. With about one billion Web pages in existence, the easiest way to keep people away from your page is to never create any link to that page from any other page on your or anyone else's site (and, obviously, don't submit it to a search engine). If a page has already been indexed, you'll have to go to the search engine's Web site and use the Remove URL page. You can use the values all and index to have robots add the current page (and its links) to the search engine's index. However, these are the default values and so leaving them out is the same as specifying them (but faster).
Figure 26.9. Some search engines, like Google shown here, keep a copy of most of the pages that they index so that visitors can see what's on the page even if the page is not available.
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).
[View full width]
<head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <meta name="copyright" content="© 2002 Liz Castro" /> <meta name="robots" content="noarchive" />
<title>Untitled</title> </head> <body> This is a page I update frequently (or perhaps it's a temporary page). I don't want search engines to keep a copy of it in their archives. </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.
3. Type the name of the crawler page (it appears in the right hand box). 4. Close the dialog box. 5. Navigate to the important pages on your site that you want to be sure the search engine finds. 6. Choose Favorites > Add to Favorites. 7. Select your crawler page folder from the list and then click OK (Figure 26.12). If your folder doesn't appear, click the Create in button to see the list of folders. 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). Figure 26.13. In the Import/Export Wizard, be sure to choose the Export to a File or Address option and then choose a simple name for your crawler file.
10. Upload the page to your server (see page 408) . 11. And then don't forget to submit it to the desired search engines (see page 424) .
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.
6. Choose Bookmarks > Add Bookmark (Ctrl/Command+D) to add the desired pages to your bookmarks folder. 7. When you've added all the desired pages, choose Bookmarks > Manage Bookmarks to open the Bookmarks window again. 8. Choose File > Export Bookmarks to save the bookmarks in an HTML file (Figure 26.16). Unfortunately, you can't choose a particular folder to save. 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
Crawler pages can double as site maps. I got the idea of using a crawler page from Paul Boutin (see page 415) .
Once you have carefully used keywords and added meta tags to all of the desired pages on your site and perhaps created a crawler page (as described on page 422) that lists those pages, you'll want to invite a search engine to visit your site in order to add your pages to its database.
Yahoo's is at http://docs.yahoo.com/info/suggest/ AltaVista's is at: http://www.altavista.com/sites/search/addurl/ 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.
Tips
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.20. You click on the link, and unbeknownst to you, see only an individual frame, instead of the entire frameset. You're missing a huge part of the site.
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).
Image maps
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.
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.
Even simpler than a Web ring is to exchange links with other sites that have similar content. Submit your page to my readers' gallery: www.cookwood.com/html/gallery/. Make sure your Web site's URL appears on your stationery, business cards, pamphlets and other promotional material, and advertisements. And of course, you can always pay someone to advertise your page for you.
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.
class
event
accesskey
event
href name
(X)HTML Elements and Attributes TAG/ATTRIBUTE(S) jump to (p. 120) DESCRIPTION VERS.
tabindex target
abbr acronym address applet
For defining the order in which the Tab key takes the visitor through links and form elements (p. 127) For specifying a particular window or frame for a link (pp. 122, 123) For explaining meaning of abbreviations (p. 82) For explaining meaning of acronyms (p. 82) For formatting the e-mail address of the Web page designer (p. 74) For inserting applets (p. 306) For specifying the URL of the applet's code For specifying width and height of an applet For specifying coordinates of image maps (p. 130) For adding a keyboard shortcut to a particular region of the map For giving information about an area For giving coordinates of area in image map For specifying destination URL of link in area in image map For making a click in image map have no effect For specifying shape of area in image map For specifying window or frame that link should be displayed in For displaying text in boldface (p. 74) D D D D D
href target
basefont
For specifying the URL to be used to generate relative URLs (p. 123) For specifying the default target for the links on the page (p. 123) D
For specifying default font specifications throughout page D (p. 344) For specifying the default color for text For specifying the default font for text For specifying the default size for text For inserting background sound for page (p. 311) For specifying how many times sound should play For specifying URL of sound For making text bigger than surrounding text (p. 75) For making text disappear and reappear (p. 351) N D D D IE IE IE
loop src
big blink
(X)HTML Elements and Attributes TAG/ATTRIBUTE(S) blockquote DESCRIPTION For setting off block of text on page (p. 78) For giving the URL of the source of the quote For enclosing main section of page (p. 62) For specifying color of active links, new links, and visited links (p. 349) For specifying a background image (p. 355) For specifying the background color (p. 354) For specifying left and top margins (p. 357) For specifying color of text (p. 348) For creating a line break (p. 70) For stopping text wrap (pp. 112, 223) For creating buttons (pp. 283, 285, 318) For adding a keyboard shortcut to a button To gray out a button until some other event occurs For associating the button with a script For identifying buttons (perhaps for a JavaScript function) For using the button as a form element For specifying what kind of button to create For creating a caption for a table (p. 217) For placing caption above or below table For centering text, images, or other elements (p. 356) For marking text as a citation (p. 74) For marking text as computer code (p. 76) For joining columns in a table into a non-structural group (p. 234) For specifying alignment of columns in column group For specifying number of columns in column group For specifying a column's width For joining columns in a table into a structural column group (p. 234) For specifying alignment of columns in column group For specifying number of columns in column group For specifying the default width for the enclosed col elements For marking a definition in a list (p. 211) D D D D D IE D VERS.
cite
body
clear
button
accesskey disabled
event
align
center cite code col
(X)HTML Elements and Attributes TAG/ATTRIBUTE(S) del div DESCRIPTION To mark deleted text by striking it out (p. 81) For dividing a page into logical sections (p. 68) For aligning a given section to left, right, or center For giving a name to each class of divisions For giving a unique name to a particular division For creating a definition list (p. 211) For marking a term to be defined in a list (p. 211) For emphasizing text, usually with italics (p. 74) For adding multimedia (pp. 298, 304, 307) For aligning controls For making multimedia event begin automatically For displaying play, pause, rewind buttons For determining if multimedia event should play more than once For specifying URL of multimedia file For specifying size of controls For grouping a set of form elements together (p. 287) For changing the size, face, and color of text (p. 346) For changing text color For changing text font For changing text size For creating fill-in forms (p. 269) For giving URL of CGI script for form For uploading files in the proper format (pp. 270, 279) For determining how form should be processed For creating frames (p. 242) For determining thickness of frame borders (p. 252) For determining color of frame borders (p. 251) For displaying or hiding frame borders (p. 253) For adding space between frames (p. 252) F N+IE N+IE F IE D D D D N+IE[*] N+IE[*] N+IE[*] N+IE[*] N+IE[*] N+IE[*] N+IE[*] D VERS.
align class id
dl dt em embed
For linking to a document with more information (p. 262) F For naming frame so it can be used as target (p. 242) For keeping users from resizing a frame (p. 254) For specifying a frame's left and right, and top and bottom margins (p. 249) F F F
(X)HTML Elements and Attributes TAG/ATTRIBUTE(S) DESCRIPTION For displaying or hiding a frame's scrollbars (p. 250) For specifying initial URL to be displayed in frame (p. 242) For specifying which frame a link should be opened in (pp. 255, 256) For indicating a frame's purpose (p. 262) For defining a frameset (p. 242) For determining thickness of frame borders (p. 252) For determining color of frame borders (p. 251) VERS. F F F F F N+IE N+IE
For determining number and size of frames (pp. 244, 245) F For displaying or hiding frame borders (p. 253) For adding space between frames (p. 252) F IE
For determining number and size of frames (pp. 244, 245) F For creating headers (p. 65) For aligning headers For creating head section of page (p. 62) For creating horizontal rules (p. 115) For aligning horizontal rules For displaying horizontal rules without shading For specifying height of horizontal rule For specifying width of horizontal rule For identifying a text document as an HTML document (p. 60) For displaying text in italics (p. 74) For creating floating frames (p. 248) For aligning floating frames For displaying or hiding frame borders (p. 253) For specifying the height of an iframe For specifying the name of the floating frame, to be used as a target For specifying size of floating frame For displaying or hiding scrollbars (p. 250) For specifying the URL of the initial page For inserting images on a page (p. 104) For aligning images (p. 114) and for wrapping text around images (pp. 110, 111) For offering alternate text that is displayed if image is not D D[*] D[*] D [*] D[*] D[*] D[*] D[*] D[*] D D D D D
align
head hr
align alt
For specifying the thickness of the border, if any (pp. 104, 128) For specifying amount of space above and below, and to the sides of an image (p. 113) For specifying URL of image (p. 104) For specifying the image map that should be used with the referenced image (p. 130) For specifying size of image so that page is loaded more quickly, or for scaling (pp. 106, 108) For creating form elements (pp. 272, 273, 274, 275, 279, 281, 282, 284) For adding a keyboard shortcut to a form element (p. 290) For aligning form elements For marking a radio button or check box by default (pp. 274, 275) For graying out form elements until some other event occurs (p. 291) For triggering a script with an event like ONFOCUS, ONBLUR, etc. For determining maximum amount of characters that can be entered in form element (pp. 272, 273) For identifying data collected by this element For specifying width of text or password box (pp. 272, 273) For specifying URL of active image (p. 286) For keeping visitors from changing certain form elements (p. 292) For specifying the order in which the Tab key should take a visitor through the links and form elements (p. 289) For determining type of form element For specifying initial value of form element For marking inserted text with an underline (p. 81) For marking keyboard text (p. 76) For labeling form elements (p. 288) For specifying which form element the label belongs to For positioning elements (p. 366) For labeling fieldsets (p. 287) For aligning legends For creating a list item (p. 204)
D D
for
layer legend
align
li
type value
link
For determining which symbols should begin the list item D For determining the initial value of the first list item For linking to an external style sheet (p. 149) For specifying the URL of the style sheet For noting a style sheet's purpose (p. 198) For labeling alternate style sheets (p. 150) For noting a style sheet's MIME type For indicating that a style sheet is primary or alternate (pp. 149, 150) For creating a client-side image map (p. 130) For naming map so it can be referenced later For creating moving text (p. 310) For controlling how the text should move (scroll, slide, alternate) IE IE D
name
marquee
For controlling if the text moves from left to right or right IE to left For specifying repetitions For specifying amount of space between each marquee repetition For specifying amount of time between each marquee repetition IE IE IE
content http-equiv
For adding extra information about the Web page itself (pp. 309, 322, 338, 417, 418, 419, 420) For creating automatic jumps to other pages (p. 309), setting the default scripting language (p. 322), and declaring the character encoding (p. 338) For identifying extra information to the Web page (pp. 417, 418, 419, 420) For keeping all the enclosed elements on one line (p. 358) N+IE For providing alternatives to frames (p. 259) For providing alternatives to scripts (p. 319) For embedding objects in Web pages (pp. 260, 298, 304, 306, 307) For aligning objects For creating (or hiding) a border around an object For identifying the kind of object being embedded For defining the base URL of the source object For identifying the source of the multimedia file to be D D F
name
nobr noframes noscript object
For specifying amount of space around an object For identifying the object For displaying a message as the object is loading For noting the an object's MIME type For specifying the dimensions of the object's box For creating ordered lists (p. 204) For specifying the symbols that should begin each list item For specifying the initial value of the first list item For dividing a menu into submenus (p. 277) For graying out menu options until some other event occurs For specifying how the option should appear in the menu For creating the individual options in a form menu (p. 276) For graying out menu options until some other event occurs For specifying how the option should appear in the menu For making a menu option be selected by default in a blank form For specifying the initial value of a menu option For creating new paragraphs (p. 66) For aligning paragraphs For setting properties of an object (pp. 298, 304, 306) For identifying the kind of property For setting the value of the named property For displaying text exactly as it appears in HTML document (p. 77) For quoting short passages of text (p. 78) For giving the URL of the source of the quote (Same as strike) For displaying text with a line through it (p. 350) For displaying sample text in a monospaced font (p. 76) For adding "automatic" scripts to a page (p. 314) For specifying the character set an external script is written in (p. 315) For specifying the scripting language the script is written
type start
optgroup
D D
disabled label
option
align
param
name value
pre q
cite
s samp script
charset language
src type
select
For referencing an external script (p. 315) For specifying the scripting language the script is written in For creating menus in forms (p. 276) For graying out menu options until some other event occurs For identifying the data collected by the menu For allowing users to choose more than one option in the menu For specifying the number of items initially visible in the menu For decreasing the size of text (p. 75) For creating custom character styles (p. 69) For naming individual custom character styles For identifying particular HTML elements For displaying text with a line through it (p. 350) For emphasizing text logically, usually in boldface (p. 74) For adding style sheet information to a page (p. 151) For indicating a style sheet's purpose For indicating a style sheet's MIME type For creating subscripts (p. 80) For creating superscripts (p. 80) For creating tables (p. 217) For aligning an entire table with respect to the window (p. D 222) For specifying a background image for the table (p. 228) For specifying the background color of the table (p. 228) For specifying the thickness, if any, of the border (p. 218) For specifying a solid color for the border (p. 218) For specifying the darker (shaded) color of the border (p. 218) For specifying the lighter (highlighted) color of the border (p. 218) For setting the space between a cell's contents and its borders (p. 230) For setting the amount of space between cells (p. 230) For displaying external borders (p. 237) IE IE IE N+IE D D
class id
strike (Same as s) strong style
media type
sub sup table
align background bgcolor border bordercolor bordercolordark bordercolorlight cellpadding cellspacing frame
(X)HTML Elements and Attributes TAG/ATTRIBUTE(S) DESCRIPTION For specifying the height of the table (p. 220) For displaying internal borders (p. 238) For specifying the size of the table (p. 220) For identifying the body of the table (p. 236) For aligning the contents of the body of the table For creating regular and header cells, respectively, in a table (p. 217) For aligning a cell's contents horizontally or vertically (p. 226) For changing the background color of a cell (p. 228) For aligning the contents of a cell with respect to a character (p. 227) For spanning a cell across more than one column (p. 232) For keeping a cell's contents on one line (p. 239) For spanning a cell across more than one row (p. 233) For specifying the size of the cell (p. 220) For creating text block entry areas in a form (p. 278) For adding a keyboard shortcut to a text area For graying out a text block until some other event occurs For identifying the data that is gathered with the text block For protecting a text area's contents (p. 292) For specifying the number of rows and columns in the text block For identifying the footer and header area of a table (p. 236) For aligning the footer or header cells (p. 226) Required. For creating the title of the page in title bar area (p. 64) For creating rows in a table (p. 217) For aligning contents of row horizontally or vertically (p. 226) For changing color of entire row (p. 228) For displaying text in monospaced font (p. 76) For displaying text with line underneath it (p. 350) For creating unordered lists (p. 204) For specifying the markers that should precede each list item D D D D D D VERS. N+IE
align, valign
td; th
align, valign
title tr
type
(X)HTML Elements and Attributes TAG/ATTRIBUTE(S) wbr DESCRIPTION For creating discretional line breaks (p. 359) VERS. N+IE
Page numbers are omitted for those attributes discussed on the same page as the tag to which they belong.
[*]
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
CSS Properties and Values PROPERTY/VALUES either a color, transparent , or (p. 182) initial value: transparent; not inherited background-image either a URL, none, or inherit initial value: none; not inherited background-position either one or two percentages or lengths (or one percentage and one length) or one of top, center, or bottom and/or one of left, center, or right. Or use inherit. for setting the physical position of a specified background image (p. 182) initial value: 0% 0%, if a single percentage is set, it is used For the horizontal position and the initial value of the vertical is set to 50%, if only one keyword is used, the initial value of the other is center; applies to block-level and replaced elements: not inherited; percentages refer to the size of the box itself for determining how and if background images should be tiled (p. 182) for setting just the background image of an element (p. 182) DESCRIPTION AND NOTES
inherit
background-repeat
one of repeat, repeat-x, repeat-y , initial value: repeat; not inherited no-repeat , or inherit border any combination of the values of borderwidth, border-style, and/or a color, or for defining all aspects of a border on all sides of an element (p. 186) initial value depends on individual properties; not inherited for setting only the color of the border on one or more sides of an element (p. 186) initial value: the element's color property; not inherited for specifying the amount of space between borders in a table (p. 230) initial value: 0; may be applied only to table elements; inherited border-style one to four of the following values: none, dotted, dashed, solid, double, groove, ridge, inset, outset, inherit border-top, border-right, border-bottom, border-left any combination of a single value each for for setting only the style of a border on one or more sides of an element (p. 186) initial value: none; not inherited
inherit
border-color from one to four colors, transparent , or
inherit
border-spacing either one or two lengths or inherit
for defining all three border properties at once on only one side of an element (p. 186) initial value depends on individual values; not
CSS Properties and Values PROPERTY/VALUES border-width, border-style, and/or a color, or use inherit . border-top-color, border-right-color, border-bottom-color, border-left-color one color or inherit inherited for defining just the border's color on only one side of an element (p. 186) 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 one of none, dotted, dashed, solid, double, groove, ridge, inset, outset, or inherit border-top-width, border-right-width, border-bottom-width, border-left-width one of thin, medium, thick or a for defining just the border's width on only one side of an element (p. 186) initial value: medium; not inherited for defining the border's width on one or more sides of an element (p. 186) initial value: medium; not inherited for keeping elements from floating on one or both sides of an element (p. 195) initial value: none; may only be applied to block-level elements; not inherited for setting the distance that an element should be offset from its parent element's bottom edge (pp. 179, 180, 181) initial value: auto; not inherited; percentages refer to height of containing block for setting the foreground color of an element (p. 184) initial value: parent's color, some colors are set by browser; inherited cursor one of auto, crosshair , default, pointer, move, e-resize, neresize, nw-resize, n-resize, for setting the cursor's shape (p. 185) initial value: auto; inherited DESCRIPTION AND NOTES
length
border-width one to four of the following values: thin, medium, thick or a length clear one of none, left, right, both, or
inherit
bottom either a percentage, length, auto, or
inherit
color a color or inherit
if desired, any combination of the values for font-style, font-variant and font-weight followed by the required font-size, an optional initial value depends on individual properties; value for lineheight and the also required inherited; percentages allowed for values of fontsize and line-height fontfamily, or use inherit font-family one or more quotation markenclosed font names followed by an optional generic font name, or use inherit font-size an absolute size, a relative size, a length, a percentage, or inherit font-style either normal, italic, oblique, or for choosing the font family for text (p. 158) initial value: depends on browser; inherited
for setting the size of text (p. 162) initial value: medium; the computed value is inherited; percentages refer to parent element's font size for making text italic (p. 160) initial value: normal; inherited for setting text in small caps (p. 173) initial value: normal; inherited for applying, removing, and adjusting bold formatting (p. 161) initial value: normal; the numeric values are considered keywords and not integers (you can't choose 150, for example); inherited
inherit
font-variant either normal, small-caps , or
inherit
font-weight either normal, bold, bolder, lighter, 100, 200, 300, 400, 500, 600, 700, 800, 900, or inherit
CSS Properties and Values PROPERTY/VALUES height either a length, percentage, auto, or DESCRIPTION AND NOTES for setting the height of an element (p. 190) initial value: auto; may be applied to all elements except non-replaced inline elements, table columns, and column groups; not inherited for setting the distance that an element should be offset from its parent element's left edge (pp. 179, 180, 181) initial value: auto; may only be applied to positioned elements; not inherited; percentages refer to width of containing block for setting the amount of space between letters (p. 168) initial value: normal; inherited line-height either normal, a number, a length, a percentage, or inherit list-style any combination of the values for list-styletype, list-style-position and/or list-styleimage, or use inherit list-style-image either a URL, none, or inherit for setting the amount of space between lines of text (p. 164) initial value:normal; inherited; percentages refer to the font size of the element itself for setting a list's marker (regular or custom) and its position (p. 210) initial value depends on initial values of individual elements; may only be applied to list elements; inherited for designating a custom marker for a list (p. 208) initial value: none; may only be applied to list elements; overrides list-style-type ; inherited for determining the position of a list's marker (p. 209) initial value: outside ; may only be applied to list elements; inherited list-style-type either disc, circle, square, decimal, lower-roman , upperroman, lower-alpha , upper-alpha , none, or inherit margin one to four of the following: length, percentage, or auto, or inherit for setting a list's marker (p. 206) initial value: disc; may only be applied to list elements; not used if list-style-type is valid; inherited for setting the amount of space between one or more sides of an element's border and its parent element (pp. 189, 201) initial value depends on browser and on value of
inherit
left either a length, percentage, auto, or
inherit
letter-spacing either normal, a length, or inherit
CSS Properties and Values PROPERTY/VALUES DESCRIPTION AND NOTES width; not inherited; percentages refer to width of containing block margin-top, margin-right, margin-bottom, margin-left either a length, percentage, auto, or for setting the amount of space between only one side of an element's border and its parent element (p. 189) initial value: 0; not inherited; percentages refer to width of containing block; the values for margin-right and margin-left may be overridden if sum of width, margin-right and margin-left are larger than parent element's containing block for printing crop marks and/or cross marks (p. 201) initial value: none; can only be applied in a
inherit
marks either crop, cross or both, or use none or inherit max-height, max-width either a length, percentage, none, or
@page rule
for setting the maximum height and/or width of an element, respectively (p. 190) initial value: none; may not be applied to nonreplaced inline elements or table elements; not inherited; percentages refer to height/width of containing block for setting the minimum height and/or width of an element, respectively (p. 190) initial value: 0; may not be applied to nonreplaced inline elements or table elements; not inherited; percentages refer to height/width of containing block orphans either an integer or inherit initial value: 2; may only be applied to block-level elements; inherited overflow either visible , hidden, scroll, auto, or inherit padding one to four lengths or percentages, or for determining where extra content should go if it does not fit in the element's content area (p. 193) initial value: visible ; may only be applied to block-level and replaced elements; not inherited for specifying the distance between one or more sides of an element's content area and its border (p. 188) initial value depends on browser: not inherited; percentages refer to width of containing block for specifying how many lines of an element may appear alone at the bottom of a page (p. 202)
inherit
inherit
CSS Properties and Values PROPERTY/VALUES padding-top, padding-right, paddingbottom, padding-left either a length, percentage, or inherit page 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 either always, avoid, auto, right, left, or inherit page-break-inside either avoid, auto, or inherit initial value: auto; may only be applied to block-level elements; inherited position either static, relative, absolute, fixed, or inherit for determining how an element should be positioned with respect to the document's flow (pp. 179, 180, 181) initial value: static; may not be applied to generated content; not inherited right either a length, percentage, auto, or for setting the distance that an element should be offset from its parent element's right edge (pp. 179, 180, 181) 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) for specifying when page breaks should or should not occur (p. 200) initial value: auto; may only be applied to block-level elements; not inherited for keeping page breaks from dividing an element across pages (p. 200) DESCRIPTION AND NOTES for specifying the distance between one side of an element's content area and its border (p. 188) initial value: 0; not inherited; percentages refer to width of containing block for specifying on which kind of page an element should be printed (p. 202)
inherit
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 one of fixed, auto, or inherit initial value: auto; not inherited text-align for aligning text (p. 171) for choosing the algorithm that should be used to determine the widths of cells (p. 240)
CSS Properties and Values PROPERTY/VALUES one of left, right, center, justify, a string, or inherit text-decoration any combination of underline , overline, line-through , and blink, or none or inherit text-indent either a length, percentage, or inherit initial value: 0; may only be applied to block-level elements; inherited; percentages refer to width of containing block text-transform either capitalize , uppercase , lowercase , none, or inherit top either a length, percentage, auto, or for setting the capitalization of an element's text (p. 172) initial value: none; inherited for setting the distance that an element should be offset from its parent element's top edge (pp. 179, 180, 181) initial value: auto; may only be applied to positioned elements; not inherited; percentages refer to height of containing block vertical-align either baseline, sub, super, top, text-top, middle, bottom, textbottom, a percentage, a length, or inherit visibility either visible , hidden, collapse, or inherit white-space either normal, pre, nowrap, or for aligning elements vertically (pp. 196, 226) initial value:baseline ; may only be applied to inline-level and table cell elements; not inherited; percentages refer to the element's line-height property for hiding elements without taking them out of the document's flow (p. 178) initial value: inherit , which rather makes the fact that it's not inherited a moot point for specifying how white space should be treated (p. 170) initial value:normal; may only be applied to block-level elements; inherited for specifying how many lines of an element may appear alone at the top of a page (p. 202) initial value: 2; may only be applied to block-level elements; inherited DESCRIPTION AND NOTES initial value depends on browser and writing direction; may only be applied to block-level elements; inherited for decorating text (mostly with lines) (p. 174) initial value: none; not inherited
for setting the amount of space the first line of a paragraph should be indented (p. 169)
inherit
inherit
widows either an integer or inherit
CSS Properties and Values PROPERTY/VALUES width either a length, percentage, auto, or DESCRIPTION AND NOTES for setting the width of an element (p. 190) initial value: auto; may not be applied to nonreplaced inline elements, table rows, or row groups; not inherited; percentages refer to width of containing block for setting the distance between words (p. 168) initial value:normal; inherited for setting the depth of an element with respect to overlapping elements (p. 192) initial value: auto; may only be applied to positioned elements; not inherited
inherit
word-spacing either normal, a length, or inherit z-index either auto, an integer, or inherit
onchange onclick
the visitor clicks on the All elements except applet, base, basefont, br, font, frame, frameset, specified area head, html, iframe, meta, param, script, style, title Same as for onclick the visitor double clicks the specified area the visitor selects, clicks, or tabs to the specified element the visitor types something in the specified element the visitor types something in the specified element the visitor lets go of the key after typing in the specified element
a, area, button, input, label, select, textarea input (of type name or password), textarea input (of type name or password), textarea input (of type name or password), textarea
Intrinsic Events EVENT onload WORKS WITH WHEN the page is loaded in the browser the visitor presses the mouse button down over the element the visitor moves the mouse over the specified element after having pointed at it the visitor moves the mouse away from the specified element after having been over it the visitor points the mouse at the element the visitor lets the mouse button go after having clicked on the element the visitor clicks the form's reset button the visitor selects one or more characters or words in the element the visitor clicks the form's submit button the browser loads a different page after the specified page had been loaded
body, frameset
onmouseout
onmouseover onmouseup
onreset onselect
form (not input of type reset) input (of type name or password), textarea form (not input of type submit) body, frameset
onsubmit onunload
Instructions for inserting these symbols and characters on your Web pages can be found in Adding Characters from Outside the Encoding on page 340. 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
Accented characters, accents, and other diacritics from Western European Languages
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
Find extra tips, the source code for examples, and more at www.cookwood.com
Notes:Rho: there is no Sigmaf, and no U+03A2 character either; bull: bullet is not the same as bullet operator; alefsym: alef symbol is not the same as Hebrew letter alef, U+05D0 although the same glyph could be used to depict both characters; prod: prod is not the same character as U+03A0, greek capital letter pi , though the same glyph might be used for both; sum: sum is not the same character as U+03A3, greek capital letter sigma though the same glyph might be used for both; sim: tilde operator is not the same character as the tilde, U+007E, although the same glyph might be used to represent both; sup: note that nsup, (not a superset of), U+2283, is not covered by the Symbol font encoding and is not included. sdot: dot operator is not the same character as U+00B7, middle dot ; lang: lang is not the same character as U+003C, less than, or U+2039, (single left-pointing angle quotation mark); rang: rang is not the same character as U+003E (greater than) or U+203A (single right-pointing angle quotation mark); spades: black here seems to mean filled as opposed to hollow; oelig: ligature is a misnomer, this is a separate character in some languages; lsaquo: lsaquo is proposed but not yet ISO standardized; rsaquo: rsaquo is proposed but not yet ISO standardized The information in these tables is Copyright % 1994-2002 W3C & (Massachusetts Institute of Technology, Institut National de Recherche en Informatique et en Automatique, Keio University), All Rights Reserved. http://www.w3.org/Consortium/Legal/ Find extra tips, the source code for examples, and more at www.cookwood.com
Appendix E. Hexadecimals
"Regular" numbers are based on the base 10 system, that is, there are ten symbols (what we call "numbers"): 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. To represent numbers greater than 9, we use a combination of these symbols where the first digit specifies how many ones, the second digit (to the left) specifies how many tens, and so on. 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 # 0 1 2 3 4 5 6 7 8 9 Hex. 00 01 02 03 04 05 06 07 08 09 # Hex. # Hex. # 96 97 98 99 Hex. 60 61 62 63 # Hex. # Hex. # Hex. # Hex.
32 20 33 21 34 22 35 23 36 24 37 25 38 26 39 27 40 28 41 29 42 2A
64 40 65 41 66 42 67 43 68 44 69 45 70 46 71 47 72 48 73 49 74 4A
128 80 129 81 130 82 131 83 132 84 133 85 134 86 135 87 136 88 137 89 138 8A
160 A0 161 A1 162 A2 163 A3 164 A4 165 A5 166 A6 167 A7 168 A8 169 A9 170 AA
192 C0 193 C1 194 C2 195 C3 196 C4 197 C5 198 C6 199 C7 200 C8 201 C9 202 CA
224 E0 225 E1 226 E2 227 E3 228 E4 229 E5 230 E6 231 E7 232 E8 233 E9 234 EA
10 0A
Hexadecimal Equivalents # Hex. # Hex. # Hex. # Hex. # Hex. # Hex. # Hex. # Hex.
11 0B 12 0C 13 0D 14 0E 15 0F 16 10 17 11 18 12 19 13 20 14 21 15 22 16 23 17 24 18 25 19 26 1A 27 1B 28 1C 29 1D 30 1E 31 1F
43 2B 44 2C 45 2D 46 2E 47 2F 48 30 49 31 50 32 51 33 52 34 53 35 54 36 55 37 56 38 57 39 58 3A 59 3B 60 3C 61 3D 62 3E 63 3F
75 4B 76 4C 77 4D 78 4E 79 4F 80 50 81 51 82 52 83 53 84 54 85 55 86 56 87 57 88 58 89 59 90 5A 91 5B 92 5C 93 5D 94 5E 95 5F
107 6B 108 6C 109 6D 110 6E 111 6F 112 70 113 71 114 72 115 73 116 74 117 75 118 76 119 77 120 78 121 79 122 7A 123 7B 124 7C 125 7D 126 7E 127 7F
139 8B 140 8C 141 8D 142 8E 143 8F 144 90 145 91 146 92 147 93 148 94 149 95 150 96 151 97 152 98 153 99 154 9A 155 9B 156 9C 157 9D 158 9E 159 9F
171 AB 172 AC 173 AD 174 AE 175 AF 176 B0 177 B1 178 B2 179 B3 180 B4 181 B5 182 B6 183 B7 184 B8 185 B9 186 BA 187 BB 188 BC 189 BD 190 BE 191 BF
203 CB 204 CC 205 CD 206 CE 207 CF 208 D0 209 D1 210 D2 211 D3 212 D4 213 D5 214 D6 215 D7 216 D8 217 D9 218 DA 219 DB 220 DC 221 DD 222 DE 223 DF
235 EB 236 EC 237 ED 238 EE 239 EF 240 F0 241 F1 242 F2 243 F3 244 F4 245 F5 246 F6 247 F7 248 F8 249 F9 250 FA 251 FB 252 FC 253 FD 254 FE 255 FF
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-andshoot cameras: just aim and fire, for a price. They are more expensive, and generally less flexible. What (X)HTML editors offer Disadvantages of (X)HTML editors
Dedicated (X)HTML editors offer the following These extra features come at a price, advantages over simple text editors (of course, not however. Some things that may annoy you every (X)HTML editor has every feature): about (X)HTML editors is that
they insert opening and closing tags with a single click they check and verify syntax in your (X)HTML and CSS they allow you to add attributes by clicking buttons instead of typing words in a certain order in a certain place in the document they offer varying degrees of WYSIWYG display of your Web page they correct mistakes in existing (X)HTML pages they make it easy to use special characters they color code elements, attributes, and values, making them easy to edit
they don't all support the full (X)HTML or CSS specs 100% they are more difficult to learn, and less intuitive than they promise they cost money (all simple text editors are included free with their respective system software) they use up more space on disk and more memory some add proprietary information (like their name, for example), and tags to the (X)HTML document some eliminate tags that they don't understand even if the tags are part of the standard (X)HTML specifications
(X)HTML Editors WYSIWYG Macromedia Dreamweaver (M, W) Adobe GoLive (M, W) $400. Probably the http://www.macromedia.com/software/dreamweaver.com/ most popular editor demo available among Web professionals. $400. Formerly GoLive CyberStudio. Dreamweaver's http://www.adobe.com/prodindex/golive/main.html.com demo available
(X)HTML Editors WYSIWYG main competition. NetObjects Fusion (M, W) $150. NetObjects WYSIWYG editor for professional Web masters. http://www.netobjects.com/products/html/nof.html demo available
Microsoft $170. WYSIWYG FrontPage (M, Editor from W) Microsoft Corporation. Netscape Composer
Much improved http://home.netscape.com/ editor included free with Netscape Communicator. $100, WYSIWYG editor that creates standard, universal (X)HTML and XML. Formerly from Softquad. http://www.hotmetalpro.com/ demo available
Text Based BBEdit (M) $120. Excellent http://www.barebones.com demo available HTML editor from Bare Bones Software. The most popular nonWYSIWYG HTML editor. $100, Sausage Software. "Express" version also available. http://www.sausage.com/
Macromedia $100. Formerly HomeSite (W) Allaire HomeSite. Popular text-based HTML editor for Windows, now included free with Dreamweaver. World Wide Web Weaver (M, W) $60, Miracle Software.
http://www.macromedia.com/software/homesite/
http://www.miracleinc.com/Products/W4
Find extra tips, the source code for examples, and more at www.cookwood.com Images and Graphics
Description List of sites with graphics Searchable database of images and sounds Site that searches the Web for images that fit your criteria
Graphics Tools Name Adobe Photoshop (M, W) Description $600. Excellent, all-purpose image editing program. Version 7 includes Image-Ready, Adobe's Web graphics program $100. A remarkably robust, consumer-end version of the excellent Adobe Photoshop URL http://www.adobe.com/prodindex/photoshop/main.html demo available
http://www.adobe.com/products/photoshopel/main.html
Macromedia Fireworks
$300. A specialized http://www.macromedia.com/software/fireworks/ demo 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 (W) $100. Jasc http://www.jasc.com/products/psp/ demo available Software. Powerful image editing program for Windows. Commercial and shareware versions available. Supports JPEG, PNG, GIF. $35. Thorsten Lemke's image editor for Macintosh. Reads and writes an incredible array of graphics formats, http://www.graphicconverter.net/ demo available
GraphicConverter (M)
Graphics Tools Name Description including Progressive JPEG, GIF89a (Animated), etc. LView Pro (W) $40. Popular http://www.lview.com shareware graphics program. URL