Sams Teach Yourself HTML and CSS in 24 Hours


ptg www.it-ebooks.info ptg 800 East 96th Street, Indianapolis, Indiana, 46240 USA Julie Meloni Michael Morrison 24in Hours SamsTeach Yourself HTML and CSS Eighth Edition www.it-ebooks.info ptg Sams Teach Yourself HTML and CSS in 24 Hours, Eighth Edition Copyright © 2010 by Sams Publishing All rights reserved. No part of this book shall be reproduced, stored in a retrieval system, or transmitted by any means, electronic, mechanical, photocopying, recording, or other- wise, without written permission from the publisher. No patent liability is assumed with respect to the use of the information contained herein. Although every precaution has been taken in the preparation of this book, the publisher and author assume no responsi- bility for errors or omissions. Nor is any liability assumed for damages resulting from the use of the information contained herein. International Standard Book Number: 0-672-33097-0 Library of Congress Cataloging-in-Publication Data Meloni, Julie C. Sams teach yourself HTML and CSS 24 hours / Julie Meloni, Michael Morrison. -- 8th ed. p. cm. Rev. ed. of: Sams teach yourself HTML and CSS in 24 hours / Dick Oliver, 7th ed., 2006. ISBN 978-0-672-33097-1 (pbk.) 1. HTML (Document markup language) 2. XHTML (Document markup language) 3. Cascading style sheets. I. Morrison, Michael, 1970- II. Oliver, Dick. Sams teach yourself HTML and CSS in 24 hours. III. Title. QA76.76.H94O4526 2010 006.7'4--dc22 2009046100 Printed in the United States of America First Printing: December 2009 Trademarks All terms mentioned in this book that are known to be trademarks or service marks have been appropriately capitalized. Sams Publishing cannot attest to the accuracy of this information. Use of a term in this book should not be regarded as affecting the validity of any trademark or service mark. Warning and Disclaimer Every effort has been made to make this book as complete and as accurate as possible, but no warranty or fitness is implied. The information provided is on an “as is” basis. The author and the publisher shall have neither liability nor responsibility to any person or entity with respect to any loss or damages arising from the information contained in this book or from the use of the CD or programs accompanying it. Bulk Sales Sams Publishing offers excellent discounts on this book when ordered in quantity for bulk purchases or special sales. For more information, please contact U.S. Corporate and Government Sales 1-800-382-3419 corpsales@pearsontechgroup.com For sales outside of the U.S., please contact International Sales international@pearson.com Acquisitions Editor Mark Taber Development Editor Michael Thurston Managing Editor Patrick Kanouse Project Editor Jennifer Gallant Indexer Ken Johnson Proofreader Dan Knott Technical Editor William Wolff Publishing Coordinator Vanessa Evans Composition Mark Shirar Book Designer Gary Adair www.it-ebooks.info ptg Contents PART I: Getting Started on the Web HOUR 1: Understanding How the Web Works A Brief History of HTML and the World Wide Web ..............................................1 Creating Web Content ......................................2 Understanding Web Content Delivery ................3 Selecting a Web Hosting Provider......................6 Testing with Multiple Web Browsers ..................8 HOUR 2: Publishing Web Content Creating the Sample File for this Hour ............13 Using FTP to Transfer Files..............................14 Understanding Where to Place Files on the Web Server ................................18 Distributing Content without a Web Server ......22 Testing Web Content ....................................24 HOUR 3: Understanding HTML and XHTML Connections Getting Started with a Simple Web Page..........28 HTML Tags Every XHTML Web Page Must Have ............................................32 Organizing a Page with Paragraphs and Line Breaks ............................................34 Organizing Your Content with Headings ............36 Validating Your Web Content ..........................39 The Scoop on HTML, XML, XHTML, and HTML 5 ..................................................41 HOUR 4: Understanding Cascading Style Sheets How CSS Works ............................................48 A Basic Style Sheet........................................49 A CSS Style Primer ........................................54 Using Style Classes ......................................58 Using Style IDs ..............................................61 Internal Style Sheets and Inline Styles ............62 PART II: Building Blocks of Practical Web Design HOUR 5: Working with Text Blocks and Lists Aligning Text on a Page ..................................68 The Three Types of HTML Lists ......................71 Placing Lists Within Lists................................73 HOUR 6: Working with Fonts Boldface, Italics, and Special Text Formatting......82 Tweaking the Font ..........................................85 Working with Special Characters ....................89 HOUR 7: Using Tables to Display Information Creating a Simple Table..................................96 Controlling Table Sizes ..................................99 Alignment and Spanning Within Tables ..........102 Page Layout with Tables................................105 HOUR 8: Using External and Internal Links Using Web Addresses ..................................111 Linking Within a Page Using Anchors ............114 Linking Between Your Own Web Content ........117 Linking to External Web Content....................120 Linking to an Email Address ........................120 Opening a Link in a New Browser Window......122 Using CSS to Style Hyperlinks ......................123 HOUR 9: Working with Colors Best Practices for Choosing Colors ..............131 Understanding Web Colors............................133 Using Hexadecimal Values for Colors ............135 Using CSS to Set Background, Text, and Border Colors ................................136 HOUR 10: Creating Images for Use on the Web Choosing Graphics Software ........................143 The Least You Need to Know About Graphics ....144 Preparing Photographic Images ....................145 Creating Banners and Buttons ......................151 Reducing the Number of Colors in an Image ....153 Working with Transparent Images ..................154 Creating Tiled Backgrounds ..........................154 Creating Animated Web Graphics ..................156 HOUR 11: Using Images in Your Web Site Placing Images on a Web Page ....................162 Describing Images with Text..........................163 Specifying Image Height and Width................165 Aligning Images............................................165 Turning Images into Links ............................169 Using Background Images ............................172 Using Imagemaps ........................................173 HOUR 12: Using Multimedia in Your Web Site Linking to Multimedia Files ..........................184 Embedding Multimedia Files ........................187 Additional Tips for Using Multimedia..............190 HOUR 13: Working with Frames What Are Frames?........................................197 Building a Frameset ....................................199 Linking Between Frames and Windows ..........202 Using Inline Frames ....................................204 www.it-ebooks.info ptg iv PART III: Advanced Web Page Design with CSS HOUR 14: Working with Margins, Padding, Alignment, and Floating Using Margins..............................................212 Padding Elements ........................................219 Keeping Everything Aligned ..........................223 Understanding the Float Property ..................224 HOUR 15: Understanding the CSS Box Model and Positioning The CSS Box Model ....................................231 The Whole Scoop on Positioning ..................235 Controlling the Way Things Stack Up..............239 Managing the Flow of Text ............................242 HOUR 16: Using CSS to Do More with Lists HTML List Refresher ....................................245 How the CSS Box Model Affects Lists ..........246 Placing List Item Indicators ..........................249 Creating Image Maps with List Items and CSS ..........................................251 HOUR 17: Using CSS to Design Navigation How Navigation Lists Differ from Regular Lists........................................259 Creating Vertical Navigation with CSS ............260 Creating Horizontal Navigation with CSS ........270 HOUR 18: Using Mouse Actions to Modify Text Display Creating a Tool Tip with CSS ........................277 Displaying Additional Rollover Text with CSS ....281 Accessing Events ........................................283 Using onclick to Change
Appearance....284 HOUR 19: Creating Fixed or Liquid Layouts Understanding Fixed Layouts ........................294 Understanding Liquid Layouts ......................295 Creating a Fixed/Liquid Hybrid Layout............298 PART IV: Advanced Web Site Functionality and Management HOUR 20: Creating Print-Friendly Web Pages What Makes a Page Print-Friendly? ................312 Applying a Media-Specific Style Sheet............315 Designing a Style Sheet for Print Pages ........317 Viewing a Web Page in Print Preview..............320 HOUR 21: Understanding Dynamic Web Sites Understanding the Different Types of Scripting ........................................325 Including JavaScript in HTML ........................326 Displaying Random Content ..........................328 Understanding the Document Object Model ......332 Changing Images Based on User Interaction ....333 HOUR 22: Working with Web-Based Forms How HTML Forms Work ................................339 Creating a Form ..........................................340 Accepting Text Input ....................................344 Naming Each Piece of Form Data ..................345 Including Hidden Data in Forms ....................345 Exploring Form Input Controls ......................346 Submitting Form Data ..................................349 HOUR 23: Organizing and Managing a Web Site When One Page Is Enough............................356 Organizing a Simple Site ..............................357 Organizing a Larger Site................................360 Writing Maintainable HTML Code ..................364 HOUR 24: Helping People Find Your Web Pages Publicizing Your Web Site..............................371 Listing Your Pages with the Major Search Sites ......................................373 Providing Hints for Search Engines................374 Additional Tips for Search Engine Optimization......................................379 www.it-ebooks.info ptg v PART V: Appendixes APPENDIX A: HTML and CSS Resources on the Internet General HTML, XHTML, and CSS Information ....385 Web Browsers..............................................386 Web Page Design ........................................386 Software......................................................386 Colors and Graphics ....................................387 Multimedia ..................................................388 Advanced Developer Resources ....................388 Web Site Hosting ........................................389 Web Site Services........................................389 APPENDIX B: HTML and CSS Quick Reference HTML Structure............................................392 HTML Text Phrases and Paragraphs ..............395 XHTML Text Formatting Elements ..................398 XHTML Lists ................................................399 XHTML Links................................................400 XHTML Tables ..............................................402 XHTML Embedded Content ..........................407 XHTML Style ................................................410 XHTML Forms ..............................................410 XHTML Scripts ............................................413 XHTML Common Attributes ..........................414 CSS Dimension Style Properties ..................415 CSS Text and Font Style Properties ..............416 CSS Background Style Properties..................419 CSS Border Style Properties ........................420 CSS Margin Style Properties ........................423 CSS Padding Style Properties ......................424 CSS Layout and Display Style Properties ......424 CSS List and Marker Style Properties............427 CSS Table Style Properties ..........................428 www.it-ebooks.info ptg vi About the Authors Julie C. Meloni is both the technical director for i2i Interactive, a multimedia company located in Los Altos, CA, and a scholar working in the field of Digital Humanities. She has written several books and articles on Web-based programming languages and database topics, including the best- selling Sams Teach Yourself PHP, MySQL, and Apache All in One. Michael Morrison is a writer, developer, toy inventor, and author of a variety of computer technolo- gy books and interactive web-based courses. In addition to his primary profession as a writer and freelance nerd for hire, Michael is the creative lead at Stalefish Labs, an entertainment company he co-founded with his wife, Masheed. We Want to Hear from You! As the reader of this book, you are our most important critic and commentator. We value your opin- ion and want to know what we’re doing right, what we could do better, what areas you’d like to see us publish in, and any other words of wisdom you’re willing to pass our way. You can email or write me directly to let me know what you did or didn’t like about this book—as well as what we can do to make our books stronger. Please note that I cannot help you with technical problems related to the topic of this book, and that due to the high volume of mail I receive, I might not be able to reply to every message. When you write, please be sure to include this book’s title and author as well as your name and phone or email address. I will carefully review your comments and share them with the author and editors who worked on the book. Email: webdev@samspublishing.com Mail: Mark Taber Associate Publisher Sams Publishing 800 East 96th Street Indianapolis, IN 46240 USA Reader Services Visit our web site and register this book at informit.com/register for convenient access to any updates, downloads, troubleshooting hints, or errata that might be available for this book. www.it-ebooks.info ptg vii Introduction In 2009, it is estimated that more than 1.5 billion people have access to the Internet, including 220 million in the U.S. alone. Throw in 338 million Chinese users, 55 million German users, 48 million British users, 38 million Russian users, and 67 million Brazilians, and you can see the meaning of the word “world” in the term World Wide Web. Many of these Internet users are also creating content for the Web—you can be one of them! Although accurate measurements of the total number of web pages are difficult to come by, Google’s most recent data indicates they hit the 1 trillion mark of indexed pages in the middle of 2008. In the next 24 hours, hundreds of millions of new pages will appear in accessible areas of the Internet. At least as many pages will be placed on private intranets, where they will be viewed by businesspeople connected via their local networks. Every one of those pages—like the more than 1 trillion pages already online—will use Hypertext Markup Language (HTML). As you complete the 24 one-hour lessons in this book, your web pages will be among those that appear on the Internet. These lessons will also help you develop one of the most valuable skills in the world today: mastery of HTML. Can you really learn to create top-quality web pages yourself, without any specialized software, in less time than it takes to schedule and wait for an appointment with a highly paid HTML wizard? Can this relatively short, easy-to-read book really enable you to teach yourself state-of-the-art web page publishing? Yes. In fact, within the first two lessons in this book, someone with no previous HTML experience at all can have a web page ready to place on the web. How can you learn the language of the Web so fast? By example. This book organizes HTML into simple steps and then shows you exactly how to tackle each step. Every HTML code example is listed directly before a picture of the web page it produces. You see how it’s done, you read a clear, concise explanation of how it works, and then you immediately do the same thing with your own page. Ten minutes later, you’re on to the next step. After 24 hours of work, you’re marveling at your own impressive pages on the Internet. Beyond HTML This book covers more than just HTML because HTML isn’t the only thing you need to know to cre- ate web content today. The goal of this book is to give you all the skills you need to create a mod- ern, standards-compliant web site in just 24 short, easy lessons. This book covers the following key skills and technologies: . XHTML (eXstensible Hypertext Markup Language) is the current standard for web page cre- ation. Every example in this book is fully XHTML-compatible. Where applicable, HTML 5 is also covered. www.it-ebooks.info ptg viii . All the examples in the book have been tested for compatibility with the latest version of every major web browser. That includes Apple Safari, Google Chrome, Microsoft Internet Explorer, Mozilla Firefox, and Opera. You’ll learn from the start to be compatible with the past, yet ready for the future. . There is extensive coverage of Cascading Style Sheets (CSS), which allows you to carefully control the layout, fonts, colors, and formatting of every aspect of your web pages, including both text and images. When it comes to creating eye-popping web pages, CSS goes far beyond what traditional HTML pages could do by themselves. For example, did you know that CSS allows you to specifically tailor the information on a page just for printing, in addition to normal web viewing? . Hours 10 through 12 introduce you to multimedia applications and their use, including where to find industry-standard software you can download and try free. . The technical stuff is not enough, so this book also includes the advice you need when set- ting up a web site to achieve your goals. Key details—designing an effective page layout, posting your page to the Internet with FTP software, organizing and managing multiple pages, and getting your pages to appear high on the query lists at all the major Internet search sites—are all covered in enough depth to get you beyond the snags that often frustrate beginners. Attention to many of these essentials are what made the first seven editions of this book best- sellers, and this updated edition—the first for this title since 2005—is no different. All of the examples have been updated and a significant portion of the content has been revised to match new examples and new technologies. Visual Examples Every example in this book is illustrated in two parts: . The text you type to make an HTML page is shown first, with all HTML and CSS code high- lighted. . The resulting web page is shown as it will appear to users who view it with the world’s most popular web browsers. You’ll often be able to adapt the example to your own pages without reading any of the accompany- ing text at all. All the examples in this book are standards-compliant and work with Apple Safari, Google Chrome, Microsoft Internet Explorer, Mozilla Firefox, and Opera. While all of the screenshots are taken in Firefox, rest assured that all of the code has been tested in all other browsers. www.it-ebooks.info ptg ix You will also find the use of colors within code examples and when elements of code appear in the explanatory text. These colors highlight the different bits and pieces of code both to enhance your familiarity with them and to call attention to their use. . HTML tags are displayed in dark blue. . HTML comments are displayed in brown. . CSS elements are displayed in green. . HTML attribute names are displayed in light blue. . HTML attribute values are displayed in magenta. Be aware that the colors of certain terms change depending on their context. For instance, when CSS elements are used within the style attribute of an HTML tag, they will be color-coded as HTML attribute values (magenta) rather than CSS elements (green). Special Elements As you complete each hour, margin notes help you immediately apply what you just learned to your own web pages. Q&A, Quiz, and Exercises Every hour ends with a short question-and-answer session that addresses the kind of “dumb ques- tions” everyone wishes they dared to ask. A brief but complete quiz lets you test yourself to be sure you understand everything presented in the hour. Finally, one or two optional exercises give you a chance to practice your new skills before you move on. TIP Tips and tricks to save you precious time are set aside in “Tip” boxes so that you can spot them quickly. WARNING When there’s something you need to watch out for, you’ll be warned about it in “Warning” boxes. NOTE “Note” boxes provide addition- al information about the topics being discussed. www.it-ebooks.info ptg This page intentionally left blank www.it-ebooks.info ptg Before learning the intricacies of HTML and CSS, it is important that you gain a solid understanding of the technologies that help transform these plain-text files to the rich multimedia displays you see on your computer or handheld device when browsing the World Wide Web. A file containing HTML and CSS is useless without a web browser to view it, and no one besides yourself will see your content unless a web server is involved. Web servers make your content available to others who, in turn, use their web browsers to navigate to an address and wait for the server to send information to them. You will be intimately involved in this process, as you must create files and then put them on a server to make them avail- able in the first place, and you must ensure that your content will appear to the end-user as you intended. A Brief History of HTML and the World Wide Web Once upon a time, back when there weren’t any footprints on the moon, some farsighted folks decided to see whether they could connect several major computer networks together. I’ll spare you the names and stories (there are plenty of both), but the eventual result was the “mother of all networks,” which we call the Internet. Until 1990, accessing information through the Internet was a rather techni- cal affair. It was so hard, in fact, that even Ph.D.-holding physicists were often frustrated when trying to swap data. One such physicist, the now- famous (and knighted) Sir Tim Berners-Lee, cooked up a way to easily cross-reference text on the Internet through “hypertext” links. HOUR 1 Understanding How the Web Works WHAT YOU’LL LEARN IN THIS HOUR: . A very brief history of the World Wide Web . What is meant by the term “web page,” and why that term doesn’t always reflect all the content involved . How content gets from your personal computer to someone else’s web browser . How to select a web hosting provider . How different web browsers and device types can affect your content www.it-ebooks.info ptg 2 HOUR 1: Understanding How the Web Works This wasn’t a new idea, but his simple Hypertext Markup Language (HTML) managed to thrive while more ambitious hypertext projects floun- dered. Hypertext originally meant text stored in electronic form with cross- reference links between pages. It is now a broader term that refers to just about any object (text, images, files, and so on) that can be linked to other objects. Hypertext Markup Language is a language for describing how text, graphics, and files containing other information are organized and linked together. By 1993, only 100 or so computers throughout the world were equipped to serve up HTML pages. Those interlinked pages were dubbed the World Wide Web (WWW), and several web browser programs had been written to allow people to view web pages. Because of the growing popularity of the Web, a few programmers soon wrote web browsers that could view graph- ical images along with text. From that point forward, the continued devel- opment of web browser software and the standardization of the HTML— and XHTML—languages has lead us to the world we live in today, one in which more than 110 million web servers answer requests for more than 25 billion text and multimedia files. These few paragraphs really are a brief history of what has been a remark- able period of time. Today’s college freshmen have never known a time in which the World Wide Web didn’t exist, and the idea of “always-on” infor- mation and ubiquitous computing will shape all aspects of our lives mov- ing forward. Instead of seeing web content creation and management as a set of skills possessed only by a few technically-oriented folks (ok, call them “geeks” if you will), by the end of this book you will see that these are skills that anyone can master, regardless of inherent geekiness. Creating Web Content You may have noticed the use of the term “web content” rather than “web pages”—that was intentional. Although we talk of “visiting a web page,” what we really mean is something like “looking at all the text and the images at one address on our computer.” The text that we read, and the images that we see, are rendered by our web browsers, which are given certain instructions found in individual files. Those files contain text that is marked up, or surrounded by, HTML codes that tell the browser how to display the text—as a heading, as a paragraph, in a red font, and so on. Some HTML markup tells the browser to display NOTE For more information about the history of the World Wide Web, see the Wikipedia article on this topic: http://en.wikipedia.org/ wiki/History_of_the_Web. www.it-ebooks.info ptg Understanding Web Content Delivery 3 an image or video file rather than plain text, which brings me back to the point—different types of content are sent to your web browser, so simply saying “web page” doesn’t begin to cover it. Here we use the term “web content” instead, to cover the full range of text, image, audio, video, and other media found online. In later lessons, you will learn the basics of linking to or creating the vari- ous types of multimedia web content found in web sites. All you need to remember at this point is that you are in control of the content a user sees when visiting your web site. Beginning with the file that contains text to display or codes that tell the server to send a graphic along to the user’s web browser, you have to plan, design, and implement all the pieces that will eventually make up your web presence. As you will learn throughout this book, it is not a difficult process as long as you understand all the little steps along the way. In its most fundamental form, web content begins with a simple text file containing HTML or XHTML markup. XHTML is another flavor of HTML; the “X” stands for eXtensible, and you will learn more about it as you con- tinue through the lessons. The most important thing to know from the out- set is that all the examples in this book are HTML 4 and XHTML compati- ble, meaning that they will be rendered similarly both now and in the future by any newer generations of web browsers. That is one of the bene- fits of writing standards-compliant code: you do not have to worry about having to go back to your code sometime in the future and change it because it “doesn’t work.” Your code will likely always “work” for as long as web browsers adhere to standards (hopefully a long time). Understanding Web Content Delivery Several processes occur, in many different locations, to eventually produce web content that you can see. These processes occur very quickly—on the order of milliseconds—and occur behind the scenes. In other words, while we might think all we are doing is opening a web browser, typing in a web address, and instantaneously seeing the content we requested, technology in the background is working hard on our behalf. Figure 1.1 shows the basic interaction between a browser and a server. www.it-ebooks.info ptg 4 HOUR 1: Understanding How the Web Works However, there are several steps in the process—and potentially several trips between the browser and server—before you see the entire content of the site you requested. Suppose you want to do a Google search, so you dutifully type http://www.google.com in the address bar or select the Google bookmark from your bookmarks list. Almost immediately, your browser will show you something like what’s shown in Figure 1.2. FIGURE 1.1 A browser request and a server response. FIGURE 1.2 Visiting www.google.com. Figure 1.2 shows a web site that contains text plus one image (the Google logo). A simple version of the processes that occurred to retrieve that text and image from a web server and display it on your screen is as follows: 1. Your web browser sends a request for the index.html file located at the http://www.google.com/ address. The index.html file does not have to be part of the address that you type in the address bar; you’ll learn more about the index.html file in Hour 2, “Publishing Web Content.” www.it-ebooks.info ptg Understanding Web Content Delivery 5 2. After receiving the request for a specific file, the web server process looks in its directory contents for the specific file, opens it, and sends the content of that file back to your web browser. 3. The web browser receives the content of the index.html file, which is text marked up with HTML codes, and renders the content based on these HTML codes. While rendering the content, the browser hap- pens upon the HTML code for the Google logo, which you can see in Figure 1.2. The HTML code looks like this: ”Google”/ The tag provides attributes that tell the browser the file source loca- tion (src), width (width), height (height), border type (border), and alternative text (alt) necessary to display the logo. You will learn more about attributes throughout later lessons. 4. The browser looks at the src attribute in the tag to find the source location. In this case the image logo.gif can be found in the “logos” directory at the same web address (www.google.com) from which the browser retrieved the HTML file. 5. The browser requests the file at the http://www.google.com/logos/logo.gif web address. 6. The web server interprets that request, finds the file, and sends the contents of that file to the web browser that requested it. 7. The web browser displays the image on your monitor. As you can see in the description of the web content delivery process, web browsers do more than simply act as picture frames through which you can view content. Browsers assemble the web content components and arrange those parts according to the HTML commands in the file. You can also view web content “locally,” or on your own hard drive, with- out the need for a web server. The process of content retrieval and display is the same as the process listed in the previous steps in that a browser looks for and interprets the codes and content of an HTML file, but the trip is shorter: the browser looks for files on your own computer’s hard drive rather than on a remote machine. A web server would be needed to inter- pret any server-based programming language embedded in the files, but that is outside the scope of this book. In fact, you could work through all the lessons in this book without having a web server to call your own, but then nobody but you could view your masterpieces. www.it-ebooks.info ptg 6 HOUR 1: Understanding How the Web Works Selecting a Web Hosting Provider Despite just telling you that you can work through all the lessons in this book without having a web server, we actually recommend that you work with a web server. Don’t worry— obtaining a hosting provider is usually a quick, painless, and relatively inexpensive process. In fact, you can get your own domain name and a year of web hosting for just slightly more than the cost of the book you are reading now. If you type web hosting provider in your search engine of choice, you will get millions of hits and an endless list of sponsored search results (also known as ads). There are not this many web hosting providers in the world, although it might seem like there are. Even if you are looking at a managed list of hosting providers, it can be overwhelming—especially if all you are looking for is a place to host a simple web site for yourself or your company or organization. You’ll want to narrow your search when looking for a provider and choose one that best meets your needs. Some selection criteria for a web hosting provider are . Reliability/server ”uptime”—if you have an online presence, you want to make sure people can actually get there consistently. . Customer service—look for multiple methods for contacting cus- tomer service (phone, email, chat) as well as online documentation for common issues. . Server space—does the hosting package include enough server space to hold all the multimedia files (images, audio, video) you plan to include in your web site (if any)? . Bandwidth—does the hosting package include enough bandwidth so that all the people visiting your site and downloading files can do so without you having to pay extra? . Domain name purchase and management—does the package include a custom domain name, or must you purchase and maintain your domain name separately from your hosting account? . Price—do not overpay for hosting. You will see a wide range of prices offered and should immediately wonder “what’s the difference?” Often the difference has little to do with the quality of the service and everything to do with company overhead and what the company thinks they can get away with charging people. A good rule of thumb is that if you are paying more than $75 per year for a basic hosting package and domain name, you are probably paying too much. www.it-ebooks.info ptg Selecting a Web Hosting Provider 7 Here are three reliable web hosting providers whose basic packages con- tain plenty of server space and bandwidth (as well as domain names and extra benefits) at a relatively low cost. If you don’t go with any of these web hosting providers, you can at least use their basic package descrip- tions as a guideline as you shop around. .A Small Orange (http://www.asmallorange.com)—their “Tiny” and “Small” hosting packages are perfect starting places for the new web content publisher. . DailyRazor (http://www.dailyrazor.com)—their RazorLIMIT and RazorSTARTER hosting packages are full-featured and reliable. . LunarPages (http://www.lunarpages.com)—the Basic hosting pack- age is suitable for many personal and small business web sites. One feature of a good hosting provider is that they provide a “control panel” for you to manage aspects of your account. Figure 1.3 shows the control panel for my own RazorPRO hosting account at Daily Razor. Many web hosting providers offer this particular control panel software, or some control panel that is similar in design—clearly labeled icons leading to tasks you can perform to configure and manage your account. FIGURE 1.3 A sample control panel. www.it-ebooks.info ptg 8 HOUR 1: Understanding How the Web Works You might never need to use your control panel, but having it available to you simplifies the installation of databases and other software, the viewing of web statistics, and the addition of e-mail addresses (among many other features). If you can follow instructions, you can manage your own web server—no special training required. Testing with Multiple Web Browsers Having just discussed the process of web content delivery and the acquisi- tion of a web server, it might seem a little strange to step back and talk about testing your web sites with multiple web browsers. However, before you go off and learn all about creating web sites with HTML and CSS, do so with this very important statement in mind: every visitor to your web site will potentially use hardware and software configurations that are dif- ferent than your own. Their device types (desktop, laptop, netbook, smart- phone, iPhone), their screen resolutions, their browser types, their browser window sizes, their speed of connections—remember that you cannot con- trol any aspect of what your visitors use when they view your site. Although all web browsers process and handle information in the same general way, there are some specific differences among them that result in things not always looking the same in different browsers. Even users of the same version of the same web browser can alter how a page appears by choosing different display options and/or changing the size of their view- ing windows. All the major web browsers allow users to override the back- ground and fonts specified by the web page author with those of their own choosing. Screen resolution, window size, and optional toolbars can also change how much of a page someone sees when it first appears on their screens. You can ensure only that you write standards-compliant HTML and CSS. Do not, under any circumstances, spend hours on end designing some- thing that looks “perfect” on your own computer—unless you are willing to be disappointed when you look at it on your friend’s computer, the computer in the coffee shop down the street, or on your iPhone. You should always test your web sites with as many of these web browsers as possible: . Apple Safari (http://www.apple.com/safari/) for Mac and Windows . Google Chrome (http://www.google.com/chrome) for Windows www.it-ebooks.info ptg Summary 9 . Mozilla Firefox (http://www.mozilla.com/firefox/) for Mac, Windows, and Linux . Microsoft Internet Explorer (http://www.microsoft.com/ie) for Windows . Opera (http://www.opera.com/) for Mac, Windows, and Linux/UNIX Summary This hour introduced you to the concept of using HTML to mark-up text files in order to produce web content. You also learned that there is more to web content than just the “page”—web content also includes image, audio, and video files. All of this content lives on a web server—a remote machine often far away from your own computer. On your computer or other device, you use a web browser to request, retrieve, and eventually display web content on your screen. You learned the criteria you should consider when determining if a web hosting provider fits your needs. You also learned the importance of test- ing your work in multiple browsers once you’ve placed it on a web server. Writing valid, standards-compliant HTML and CSS will help ensure your site looks reasonably similar for all visitors, but you still shouldn’t design without receiving input from potential users outside your development team—it is even more important to get input from others when you are a “design team” of one! www.it-ebooks.info ptg 10 HOUR 1: Understanding How the Web Works Q&A Q You’ve said “web content” instead of “web page,” but I hear people refer to “web pages.” So what do they mean? And how are these terms different from a “home page” or a “web site”? A The metaphor of the World Wide Web as a library has always been easy for people to understand; in that library, individual web sites are books, and the individual content files on web sites as “pages.” A “web site” is comprised of one or more pages that are created together and relat- ed in content. A “home page” usually means the first page people visit when they look at a web site. Problems arise, however, when people say “visit my web page” when really they mean “come to my web site”— sites are full of pages. Referring to a collection of web content as a page instead of a site can tip someone off that you really don’t under- stand how the web works—either because you don’t understand the way web content works together to create a site, or because you’ve planned, designed, and implemented a site in which your content really is all on one page! Q I’ve looked at the HTML “source” of some web pages on the Internet and it looks frighteningly difficult to learn. Do I have to think like a computer programmer to learn this stuff? A Although complex HTML pages can indeed look daunting, learning HTML is much easier than learning actual software programming languages (such as C++ or Java). HTML is a markup language rather than a pro- gramming language; you mark-up text so that the text can be rendered a certain way by the browser. That’s a completely different set of thought processes than developing a computer program. You really don’t need any experience or skill as a computer programmer to be a successful web content author. One of the reasons the HTML behind many commercial web sites looks complicated is because it was likely created by a visual web design tool—a “what you see is what you get” or “WYSIWYG” editor that will use whatever markup its software developer told it to use in certain cir- cumstances—as opposed to being hand-coded, in which you are com- pletely in control of the resulting markup. In this book, you are taught fundamental coding from the ground up, which typically results in clean, easy-to-read source code. Visual web design tools have a knack for making code difficult to read, and also for producing code that is convo- luted and non-standards compliant. www.it-ebooks.info ptg Workshop 11 Workshop The workshop contains quiz questions and exercises to help you solidify your understanding of the material covered. Try to answer all of the ques- tions before looking at the “Answers” section that follows. Quiz 1. Define the term web content. 2. How many files would you need to store on a web server to produce a single web page with some text and two images on it? 3. What are some of the features to look for in a web hosting provider? Quiz Answers 1. Web content is a term that describes the full range of text, image, audio, video, and other media files delivered from web servers to web browsers. 2. You would need three: one for the web page itself, which includes the text and the HTML markup, and one for each of the two images. 3. Look for reliability, customer service, web space and bandwidth, domain name service, site management extras, and price. Exercises . Get your web hosting in order—are you going to go through the les- sons in this book by viewing files locally on your own computer, or are you going to use a web hosting provider? Note that most web hosting providers will have you up and running the same day you purchase your hosting plan. www.it-ebooks.info ptg This page intentionally left blank www.it-ebooks.info ptg In the previous hour, you learned about the process of requesting web con- tent via a web browser and how the web server responds to those requests. In this hour you’ll learn where you, as the content creator, fit into making web content available online—you have to publish that content on a web server in order for other people to find it. Creating the Sample File for this Hour Before we begin, take a look at Listing 2.1. This listing represents a simple piece of web content—a few lines of HTML that print “Hello World! Welcome to My Web Server.” in large, bold letters on two lines centered within the browser window. Listing 2.1 Our Sample HTML File Hello World!

Hello World!
Welcome to My Web Server.

To make use of this content, open a text editor of your choice, such as Notepad (on Windows) or TextEdit (on a Mac). Do not use WordPad, Microsoft Word, or other full-featured word-processing software, as those create different sorts of files than the plain-text files we use for web content. HOUR 2 Publishing Web Content WHAT YOU’LL LEARN IN THIS HOUR: . How to create a basic HTML file using a text editor . How to transfer files to your web server using FTP . Where files should be placed on a web server . How to distribute web con- tent without a web server . How to use other publish- ing methods such as blogs NOTE You will learn more about text editors in Hour 3. Right now, we just want you to have a sample file that you can put on a web server! www.it-ebooks.info ptg 14 HOUR 2: Publishing Web Content Type the content that you see in Listing 2.1 and then save the file using sample.html as the file name. The .html extension tells the web server that your file is, indeed, full of HTML. When the file contents are sent to the web browser that requests it, the browser will also know that it is HTML and will render it appropriately. Now that you have a sample HTML file to use—and hopefully somewhere to put it, such as a web hosting account—let’s get to publishing your web content. Using FTP to Transfer Files As you’ve learned so far, you have to put your web content on a web serv- er in order to make it accessible to others. This process typically occurs by using File Transfer Protocol (FTP). To use FTP, you need an FTP client—a program used to transfer files from your computer to a web server. FTP clients require three pieces of information in order to connect to your web server; this information will have been sent to you by your hosting provider after you set up your account: . The hostname, or address, to which you will connect . Your account username . Your account password Once you have this information, you are ready to use an FTP client to transfer content to your web server. Selecting an FTP Client Regardless of the FTP client you use, FTP clients generally use the same type of interface. Figure 2.1 shows an example of FireFTP, which is an FTP client used with the Firefox web browser. The directory listing of the local machine (your computer) appears on the left of your screen and the direc- tory listing of the remote machine (the web server) appears on the right. Typically you will see right-arrow and left-arrow buttons—as shown in Figure 2.1. The right arrow sends selected files from your computer to your web server; the left arrow sends files from the web server to your comput- er. Many FTP clients also allow you to simply select files and then drag and drop those files to the target machines. www.it-ebooks.info ptg Using FTP to Transfer Files 15 There are many FTP clients freely available to you, but you can also trans- fer files via the web-based File Manager tool that is likely part of your web server’s control panel. However, that method of file transfer typically introduces more steps into the process and isn’t nearly as streamlined (or simple) as installing an FTP client on your own machine. Here are some popular free FTP clients: . Classic FTP (http://www.nchsoftware.com/classic/) for Mac and Windows . Cyberduck (http://cyberduck.ch/) for Mac . Fetch (http://fetchsoftworks.com/) for Mac . FileZilla (http://filezilla-project.org/) for all platforms . FireFTP (http://fireftp.mozdev.org/) Firefox extension for all plat- forms Once you have selected an FTP client and installed it on your computer, you are ready to upload and download files from your web server. In the next section, you’ll see how this process works using the sample file creat- ed at the beginning of this hour. Using an FTP Client The following steps show how to use Classic FTP to connect to your web server and transfer a file. However, all FTP clients use similar, if not exact, FIGURE 2.1 The FireFTP interface. www.it-ebooks.info ptg 16 HOUR 2: Publishing Web Content interfaces. If you understand the following steps, you should be able to use any FTP client. Remember, you first need the hostname, the account username, and the account password. 1. Start the Classic FTP program and click the Connect button. You will be prompted to fill out information for the site to which you wish to connect, as shown in Figure 2.2. FIGURE 2.2 Connecting to a new site in Classic FTP. 2. Fill in each of the items shown in Figure 2.2 as follows: . The site Label is the name you’ll use to refer to your own site. Nobody else will see this name, so enter whatever you want. . The FTP Server is the FTP address of the web server to which you need to send your web pages. This address will have been given to you by your hosting provider. It will probably be yourdomain.com, but check the information you received when you signed up for service. . The User Name field and the Password field should also be com- pleted using information given to you by your hosting provider. . Don’t change the values for Initial Remote Directory on First Connection and Initial Local Directory on First Connection until you are used to using the client and have established a workflow. www.it-ebooks.info ptg Using FTP to Transfer Files 17 3. When you’re finished with the settings, click OK to save the settings and establish a connection with the web server. You will see a dialog box indicating that Classic FTP is attempting to connect to the web server. Upon successful connection, you will see an interface like that which is shown in Figure 2.3, showing the con- tents of the local directory on the left and the contents of your web server on the right. FIGURE 2.3 A successful connection to a remote web server via Classic FTP. 4. You are now almost ready to transfer files to your web server. All that remains is to change directories to what is called the document root of your web server. The document root of your web server is the direc- tory that is designated as the top-level directory for your web con- tent—the starting point of the directory structure, which you will learn more about later in this hour. Often, this directory will be named public_html (as shown in Figure 2.3), www (also shown in Figure 2.3, as www has been created as an alias for public_html) or htdocs. This is not a directory that you will have to create, as your hosting provider will have created it for you. Double-click the document root directory name to open it. The dis- play shown on the right of the FTP client interface should change to show the contents of this directory (it will probably be empty at this point, unless your web hosting provider has put placeholder files in that directory on your behalf). www.it-ebooks.info ptg 18 HOUR 2: Publishing Web Content 5. The goal is to transfer the sample.html file you created earlier from your computer to the web server. Find the file in the directory listing on the left of the FTP client interface (navigate around if you have to) and click it once to highlight the file name. 6. Click the right-arrow button in the middle of the client interface to send the file to the web server. Once the file transfer is completed, the right side of the client interface should refresh to show you that the file has made it to its destination. 7. Click the Disconnect button to close the connection, and then exit out of the Classic FTP program. These steps are conceptually similar to the steps you will take anytime you want to send files to your web server via FTP. You can also use your FTP client to create subdirectories on the remote web server. To create a subdi- rectory using Classic FTP, click the Remote menu and then click New Folder. Different FTP clients will have different interface options to achieve the same goal. Understanding Where to Place Files on the Web Server An important aspect of maintaining web content is determining how you will organize that content—not only for the user to find, but also for you to maintain on your server. Putting files in directories will help you to man- age those files. Naming and organizing directories on your web server, and developing rules for file maintenance, is completely up to you. However, maintaining a well-organized server simply makes your management of its content more efficient in the long run. Basic File Management As you browse the web, you might have noticed that URLs change as you navigate through web sites. For instance, if you’re looking at a company’s web site and you click on graphical navigation leading to the company’s products or services, the URL will probably change from www.it-ebooks.info ptg Understanding Where to Place Files on the Web Server 19 http://www.companyname.com/ to http://www.companyname.com/products/ or http://www.companyname.com/services/ In the previous section, I used the term document root without really explaining what that is all about. The document root of a web server is essentially the trailing “slash” in the full URL. For instance, if your domain is yourdomain.com and your URL is http://www.yourdomain.com/, then the document root is the directory represented by the trailing slash (/). The document root is the starting point of the directory structure you create on your web server; it is the place where the web server begins looking for files requested by the web browser. If you put the sample.html file in your document root as previously direct- ed, then you will be able to access it via a web browser at the following URL: http://www.yourdomain.com/sample.html If you were to enter this URL into your web browser, you would see the rendered sample.html file as shown in Figure 2.4. FIGURE 2.4 The sample.html file accessed via a web browser. However, if you created a new directory within the document root and put the sample.html file in that directory, then the file would be accessed at this URL: http://www.yourdomain.com/newdirectory/sample.html www.it-ebooks.info ptg 20 HOUR 2: Publishing Web Content If you put the sample.html file in the directory you originally saw upon connecting to your server—that is, you did not change directories and place the file in the document root—then the sample.html file would not be accessible from your web server at any URL. The file will still be on the machine that you know as your web server, but since the file is not in the document root—where the server software knows to start looking for files—it will never be accessible to anyone via a web browser. The bottom line? Always navigate to the document root of your web server before you start transferring files. This is especially true with graphics and other multimedia files. A common directory on web servers is called “images,” where, as you can imagine, all the image assets are placed for retrieval. Other popular directories include “css” for stylesheet files (if you are using more than one) and “js” for exter- nal JavaScript files. Or, if you know you will have an area on your web site where visitors can download many different types of files, you might sim- ply call that directory “downloads.” Whether it’s a ZIP file containing your art portfolio or an Excel spreadsheet with sales numbers, it’s often useful to publish files on the Internet that aren’t simply web pages. To make a file available on the Web that isn’t an HTML file, just upload the file to your web site as if it were an HTML file, following the instructions earlier in this hour for uploading. After the file is uploaded to the web server, you can create a link to it (as you’ll learn in later hours). In other words, your web server can “serve” much more than HTML. Here’s a sample of the HTML code that you will learn in that hour. The following code would be used for a file named artfolio.zip, located in the downloads directory of your web site, and link text that reads “Download my art portfolio!”: Download my art portfolio! Using an Index Page When you think of an index, you probably think of the section in the back of a book that tells you where to look for various keywords and topics. The index file in a web server directory can serve that purpose—if you design it that way. In fact, that’s where the name originates. The index.html file (or just index file, as it’s usually referred to) is the name you give to the page you want people to see as the default file when they www.it-ebooks.info ptg Understanding Where to Place Files on the Web Server 21 navigate to a specific directory in your web site. If you’ve created that page with usability in mind, your users will be able to get to all content in that section from the index page. For example, Figure 2.5 shows the drop-down navigation and left-side navigation both contain links to three pages: Solutions Overview (the sec- tion index page itself), Connection Management, and Cost Management. The content of the page itself—called index.html and located within the solutions directory—also has links to those two additional pages in the solutions section. When users arrive at the index page of the solutions sec- tion in this particular web site, they can reach any other page in that sec- tion (and three different ways!). FIGURE 2.5 Showing a good section index page. Another function of the index page is that when users visit a directory on your site that has an index page, but they do not specify that page, they will still land on the main page for that section of your site—or for the site itself. For instance, in the previous example, a user could have typed either of the following URLs and landed on the main page of the solutions section of that web site: http://www.ipass.com/solutions/ http://www.ipass.com/solutions/index.html www.it-ebooks.info ptg 22 HOUR 2: Publishing Web Content Had there been no index.html page in the solutions directory, the results would depend on the configuration of the web server. If the server is con- figured to disallow directory browsing, the user would have seen a “Directory Listing Denied” message when attempting to access the URL without a specified page name. However, if the server is configured to allow directory browsing, the user would have seen a list of the files in that directory. These server configuration options will have already been determined for you by your hosting provider. If your hosting provider allows you to mod- ify server settings via a control panel, then you can change these settings so that your server responds to requests based on your own requirements. Not only is the index file used in subdirectories, it’s used in the top-level directory (or document root) of your web site as well. The first page of your web site—or home page or main page, or however you wish to refer to the web content you want users to see when they first visit your domain— should be named index.html and placed in the document root of your web server. This will ensure that when users type http://www.yourdomain.com/ into their web browsers, the server will respond with content you intended them to see (rather than “Directory Listing Denied” or some other unintended consequence). Distributing Content without a Web Server Publishing HTML and multimedia files online is obviously the primary reason to learn HTML and create web content. However, there are also sit- uations in which other forms of publishing simply aren’t viable. For exam- ple, you might want to distribute CD-ROMs, DVD-ROMs, or USB drives at a trade show with marketing materials designed as web content—that is, hyperlinked text viewable through a web browser, but without a web serv- er involved. You might also want to include HTML-based instructional manuals on removable media for students at a training seminar. These are just two examples of how HTML pages can be used in publishing scenar- ios that don’t involve the Internet. This process is also called creating local sites; even though there’s no web server involved, these bundles of hypertext content are still called sites. The local term comes into play since your files are accessed locally and not remotely (via a web server). www.it-ebooks.info ptg Distributing Content without a Web Server 23 Publishing Content Locally Let’s assume you need to create a local site that you want to distribute on a USB drive. Even the cheapest USB drives hold so much data these days— and basic hypertext files are quite small—that you can distribute an entire site and a fully-functioning web browser all on one little drive. Simply think of the directory structure of your USB drive just as you would the directory structure of your web server. The top-level of the USB drive directory structure can be your document root. Or if you are distrib- uting a web browser along with the content, you might have two directo- ries—for example, one named browser and one named content. In that case, the content directory would be your document root. Within the docu- ment root, you could have additional subfolders in which you place con- tent and other multimedia assets. It’s as important to maintain a good organization with a local site as it is with a remote web site, so that you avoid broken links in your HTML files. You will learn more about the specifics of linking together files in a later hour. Publishing Content on a Blog You might have a blog hosted by a third-party, such as Blogger or WordPress (among others), and thus have already published content with- out having a dedicated web server or even knowing any HTML. These services offer visual editors in addition to source editors, meaning that you can type your words and add visual formatting such as bold, italics, or font col- ors without knowing the HTML for these actions. But still, the content becomes actual HTML when you click the Publish button in these editors. However, with the knowledge you will acquire throughout this book, your blogging will be enhanced because you will able to use the source editor for your blog post content and blog templates, thus affording you more control over the look and feel of that content. These actions occur different- ly than the process you learned for creating an HTML file and uploading it via FTP to your own dedicated web server, but I would be remiss if I did not note that blogging is, in fact, a form of web publishing. NOTE Distributing a web browser isn’t required when creating and dis- tributing a local site, although it’s a nice touch. You can rea- sonably assume that users have their own web browsers and will open the index.html file in a directory to start browsing the hyperlinked content. However, if you would like to distribute a web browser on the USB drive, go to http://www.portableapps.com/ and look for Portable Firefox. www.it-ebooks.info ptg 24 HOUR 2: Publishing Web Content Testing Web Content Whenever you transfer files to your web server or place them on remov- able media for local browsing, you should immediately test every page thoroughly. The following checklist will help ensure that your web content behaves the way you expected. Note that some of the terms might be unfa- miliar to you at this point, but come back to this checklist as you progress through this book and create larger projects: . Before you transfer your files, test them locally on your machine to ensure that the links work and the content reflects the visual design you intended. After you transfer the pages to a web server or remov- able device, test them all again. . Perform these tests with as many browsers that you can—Chrome, Firefox, Internet Explorer, Opera, and Safari is a good list—and on both Mac and Windows platforms. If possible, check at low resolu- tion (800x600) and high resolution (1600x1200). . Turn off auto image loading in your web browser before you start testing so that you can see what each page looks like without the graphics. Check your alt tag messages and then turn image loading back on to load the graphics and review the page carefully again. . Use your browser’s font size settings to look at each page in various font sizes to ensure that your layout doesn’t fall to pieces if users override your font specifications with their own. . Wait for each page to completely finish loading and then scroll all the way down to make sure that all images appear where they should. . Time how long it takes each page to load. Does it take more than a few seconds to load? If so, is the information on that page valuable enough to keep users from going elsewhere before the page finishes loading? Granted, broadband connections are common, but that doesn’t mean you should load up your pages with 1 MB images. If your pages pass all those tests, you can rest easy; your site is ready for public viewing. www.it-ebooks.info ptg Summary 25 Summary You began this hour by creating a very simple HTML file to use as a test file for the process of transferring files to your web server. You learned how that file transfer process works and what type of software you need to perform those transfers (an FTP client). You also learned a little bit about web server directory structures and file management, as well as the very important purpose of the index.html file in a given web server directory. You also learned that you can distribute web content on removable media, and you learned how to go about structuring the files and directories to achieve the goal of viewing content without using a remote web server. Finally, you learned how to test your files before releasing your site for public consumption. Q&A Q All the tests you recommend would take longer than creating my pages! Can’t I get away with less testing? A If your pages aren’t intended to make money or provide an important service, it’s probably not a big deal if they look funny to some users or produce errors once in a while. In that case, just test each page with a couple of different browsers and call it a day. However, if you need to project a professional image, there is no substitute for rigorous testing. Q Seriously, who cares how I organize my web content? A Believe it or not, the organization of your web content does matter to search engines and potential visitors to your site—you’ll learn more about this in Hour 24, “Helping People Find Your Web Pages.” But over- all, having an organized web server directory structure will help you keep track of content that you are likely to update frequently. For instance, if you have a dedicated directory for images or multimedia, you will know exactly where to look for a file you wish to update—no need to hunt through directories containing other content. www.it-ebooks.info ptg 26 HOUR 2: Publishing Web Content Workshop The workshop contains quiz questions and exercises to help you solidify your understanding of the material covered. Try to answer all questions before looking at the “Quiz Answers” section that follows. Quiz 1. What three pieces of information do you need to connect to your web server via FTP? 2. What is the purpose of the index.html file? 3. Does your web site have to include a directory structure? Quiz Answers 1. The hostname, your account username, and your account password. 2. The index.html file is typically the default file for a directory within a web server. It allows users to access http://www.yourdomain.com/somedirectory/ without using a trail- ing file name and still end up in the appropriate place. 3. No. Using a directory structure for file organization is completely up to you, although it is highly recommended to use one because it sim- plifies content maintenance. Exercises . Using your FTP client, create a subdirectory within the document root of your web site. Paste the contents of the sample.html file into another file named index.html, change the text between the and tags to something new, and change the text between the

and

tags to something new. Save the file and upload it to the new subdirectory. Use your web browser to navigate to the new directory on your web server and see that the content in the index.html file appears. Then, using your FTP client, delete the index.html file from the remote subdirectory. Return to that URL with your web browser, reload the page, and see how the server responds without the index.html file in place. . Using the same set of files created in the exercise above, place these files on a removable media device—a CD-ROM or a USB drive, for example. Use your browser to navigate this local version of your sample web site, and think about the instructions you would have to distribute with this removable media so that others could use it. www.it-ebooks.info ptg The first two hours gave you a basic idea of the process behind creating web content and viewing it online or locally, if you do not yet have a web hosting provider. In this hour, we’ll get down to the business of explaining the various elements that must appear in an HTML file. At the end of the hour, you’ll learn how HTML differs from XHTML and why there are two different languages designed to do the same thing—cre- ate web content. In general, this hour provides a quick summary of HTML and XHTML basics and gives some practical tips to make the most of your time as a web page author and publisher. It’s not all theory, however; you do get to see a real web page and the HTML code behind it. Here’s a review of what you need to do before you’re ready to use the rest of this book: 1. Get a computer. I used a computer with Windows Vista to test the sample web content and capture the figures in this book, but you can use any Windows, Macintosh, or Linux/UNIX machine to create and view your web content. 2. Get a connection to the Internet. Whether you have a dial-up, wire- less, or broadband connection doesn’t matter for the creation and viewing of your web content, but the faster the connection, the better for the overall experience. The Internet Service Provider (ISP), school, or business that provides your Internet connection can help you with the details of setting it up properly. Additionally, many public spaces such as coffee shops, bookstores, and libraries offer free wireless Internet service that you can use if you have a laptop computer with Wi-Fi network support. HOUR 3 Understanding HTML and XHTML Connections WHAT YOU’LL LEARN IN THIS HOUR: . How to create a simple web page in HTML . How to include all the HTML Tags that every web page must have . How to organize a page with paragraphs and line breaks . How to organize your con- tent with headings . How to validate your web content . How to differentiate between HTML, XML, XHTML, and HTML 5 NOTE Not sure how to find an ISP? The best way is to comparison- shop online (using a friend’s computer or a public computer that’s already connected to the Internet). You’ll find a compre- hensive list of national and regional ISPs at http://www.the- list.com/. www.it-ebooks.info ptg 28 HOUR 3: Understanding HTML and XHTML Connections 3. Get web browser software. This is the software your computer needs in order to retrieve and display web content. As you learned in the first hour, the most popular browser software (in alphabetical order) is Apple Safari, Google Chrome, Mozilla Firefox, Microsoft Internet Explorer, and Opera. It’s a good idea to install several of these browsers so that you can experiment and make sure that your con- tent looks consistent across them all; you can’t make assumptions about the browsers other people are using. 4. Explore! Use a web browser to look around the Internet for web sites that are similar in content or appearance to those you’d like to create. Note what frustrates you about some pages, what attracts you and keeps you reading others, and what makes you come back to some pages over and over again. If there is a particular topic that interests you, consider searching for it using a popular search engine such as Google (http://www.google.com/) or Bing (http://www.bing.com/). Getting Started with a Simple Web Page In the first hour, you learned that a “web page” is just a text file that is “marked-up” by (or surrounded by) HTML codes that tell the browser how to display the text. To create these text files, use a text editor such as Notepad (on Windows) or TextEdit (on a Mac)—do not use WordPad, Microsoft Word, or other full-featured word-processing software, as those create different sorts of files than the plain-text files we use for web content. Before you begin working, you should start with some text that you want to put on a web page: 1. Find (or write) a few paragraphs of text about yourself, your family, your company, your softball team, or some other subject in which you’re interested. 2. Save this text as plain, standard ASCII text. Notepad and most sim- ple text editors always save files as plain text, but if you’re using another program, you might need to choose this file type as an option (after selecting File, Save As). As you go through this hour, you will add HTML markup (called tags) to the text file, thus making it into web content. NOTE Although all web browsers process and handle information in the same general way, there are some specific differences among them that result in things not always looking the same in different browsers. Be sure to check your web pages in multi- ple browsers to make sure that they look reasonably consistent. NOTE As discussed in Hour 1, if you plan to put your web content on the Internet (as opposed to pub- lishing it on CD-ROM or a local intranet), you’ll need to transfer it to a computer that is connected to the Internet 24 hours a day. The same company or school that provides you with Internet access might also provide web space; if not, you might need to pay a host- ing provider for the service. WARNING Do not create your first HTML file with Microsoft Word or any other HTML-compatible word processor; most of these pro- grams attempt to rewrite your HTML for you in strange ways, potentially leaving you totally confused. Additionally, I recom- mend that you do not use a graphical, what-you-see-is-what- you-get (WYSIWYG) editor, such as Microsoft FrontPage or Adobe Dreamweaver. You’ll like- ly find it easier and more edu- cational to start out with a sim- ple text editor while you’re just learning HTML. You can progress to visual tools (such as FrontPage and Dreamweaver) after you have a better under- standing of what’s going on “under the hood.” www.it-ebooks.info ptg Getting Started with a Simple Web Page 29 When you save files containing HTML tags, always give them a name end- ing in .html. This is important: if you forget to type the .html at the end of the filename when you save the file, most text editors will give it some other extension (such as .txt). If that happens, you might not be able to find the file when you try to look at it with a web browser; if you find it, it certainly won’t display properly. In other words, web browsers expect a web page file to have a file extension of .html. You might also encounter a web page with a file extension of .htm, which is also acceptable. You might find other file extensions used on the Web, such as .jsp (Java Server Pages), .asp (Microsoft Active Server Pages), or .php (PHP: Hypertext Preprocessor), but these file types use server-side technologies that are beyond the scope of HTML. Listing 3.1 shows an example of text you can type and save to create a sim- ple HTML page. If you opened this file with Firefox, you would see the page shown in Figure 3.1. Every web page you create must include the , , , and tag pairs. Listing 3.1 The , , , and <body> Tags <?xml version=”1.0” encoding=”UTF-8”?> <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN” “http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”> <html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en”> <head> <title>The First Web Page

In the beginning, Tim created the HyperText Markup Language. The Internet was without form and void, and text was upon the face of the monitor and the Hands of Tim were moving over the face of the keyboard. And Tim said, Let there be links; and there were links. And Tim saw that the links were good; and Tim separated the links from the text. Tim called the links Anchors, and the text He called Other Stuff. And the whole thing together was the first Web Page.

NOTE If you’re using TextEdit on a Macintosh computer, the steps for creating an HTML file are a little different than for using Notepad on a Windows comput- er—both are popular text edi- tors, but with the latter you must first click on the Format menu and select Make Plain Text and then change the pref- erences under the Saving head- er by unchecking the box for Append ‘.txt’ Extension to Plain Text Files. Also, the default pref- erences are set to show .html documents as they would appear in a browser, which won’t allow you to edit them. To fix this, check Ignore Rich Text Commands in HTML Files under the Rich Text Processing header. www.it-ebooks.info ptg 30 HOUR 3: Understanding HTML and XHTML Connections FIGURE 3.1 When you save the text in Listing 3.1 as an HTML file and view it with a web browser, only the actual title and body text are displayed. NOTE Technically speaking, HTML 5 will be the next web standard but it’s not quite at the point of full adoption. Current estimate put the full adoption of HTML somewhere in the year 2011. However, as you learn about important features of HTML and XHTML in this book, I will include notes about how HTML 5 features might differ. In Listing 3.1, as in every HTML page, the words starting with < and end- ing with > are actually coded commands. These coded commands are called HTML tags because they “tag” pieces of text and tell the web brows- er what kind of text it is. This allows the web browser to display the text appropriately. The first few lines of code in the web page serve as standard boilerplate code that you will include in all of your pages. This code actually identifies the page as an XHTML 1.1 document, which means that, technically, the web page is an XHTML page. All the pages developed throughout the book are XHTML 1.1 pages. Because XHTML is a more structured version of HTML, it’s still okay to generally refer to all the pages in the book as HTML pages. By targeting XHTML 1.1 with your code, you are developing web pages that adhere to the very latest web standards. This is a good thing! www.it-ebooks.info ptg Getting Started with a Simple Web Page 31 If you have obtained a web hosting account, you could use FTP at this point to transfer the firstpage.html file to the web server. In fact, from this hour forward, the instructions will assume you have a hosting provider and are comfortable sending files back and forth via FTP; if that is not the case, please review the first two hours before moving on. Or, if you are consciously choosing to work with files locally (without a web host), be prepared to adjust the instructions to suit your particular needs (such as ignoring “transfer the files” and “type in the URL”). Creating and Viewing a Basic Web Page Before you learn the meaning of the HTML tags used in Listing 3.1, you might want to see exactly how I went about creating and viewing the document itself. Follow these steps: 1. Type all the text in Listing 3.1, including the HTML tags, in Windows Notepad (or use Macintosh TextEdit or another text editor of your choice). 2. Select File, Save As. Be sure to select plain text (or ASCII text) as the file type. 3. Name the file firstpage.html. 4. Choose the folder on your hard drive where you would like to keep your web pages—and remember which folder you choose! Click the Save or OK button to save the file. 5. Now start your favorite web browser. (Leave Notepad running, too, so you can easily switch between viewing and editing your page.) In Internet Explorer, select File, Open and click Browse. If you’re using Firefox, select File, Open File. Navigate to the appropriate folder and select the firstpage.html file. Some browsers and operating systems will also allow you to drag and drop the firstpage.html file onto the browser window in order to view it. Voilà! You should see the page shown in Figure 3.1. TRY IT YOURSELF ▼ NOTE You don’t need to be connected to the Internet to view a web page stored on your own computer. By default, your web browser tries to connect to the Internet every time you start it, which makes sense most of the time. However, this can be a hassle if you’re developing pages locally on your hard drive (offline) and you keep getting errors about a page not being found. If you have a full-time web connection via a LAN, cable modem, or DSL, this is a moot point because the browser will never complain about being offline. Otherwise, the appropriate disci- plinary action will depend on your breed of browser; check the options under your browser’s “Tools” menu. www.it-ebooks.info ptg 32 HOUR 3: Understanding HTML and XHTML Connections HTML Tags Every XHTML Web Page Must Have The time has come for the secret language of HTML tags to be revealed to you. When you understand this language, you will have creative powers far beyond those of other humans. Don’t tell the other humans, but it’s really pretty easy. Before you get into the HTML tags, let’s first address the messy-looking code at the top of Listing 3.1. The first line indicates that the HTML docu- ment is, in fact, an XML document: The version of XML is set to 1.0, which is fairly standard, as is the type of character encoding (UTF-8). The second and third lines of code in Listing 3.1 are even more complicat- ed looking: Again, the specifics of this code aren’t terribly important as long as you remember to include the code at the start of your pages. This code identi- fies the document as being XHTML 1.1, which then allows web browsers to make sure the code meets all the requirements of XHTML 1.1. Most HTML tags have two parts: an opening tag, which indicates where a piece of text begins, and a closing tag, which indicates where the piece of text ends. Closing tags start with a /(forward slash) just after the < sym- bol. Another type of tag is the empty tag, which is unique in that it doesn’t include a pair of matching opening and closing tags. Instead, an empty tag consists of a single tag that starts with a < and ends with a / just before the > symbol. Following is a quick summary of these three tags just to make sure you understand the role each of them plays: . An opening tag is an HTML tag that indicates the start of an HTML command; the text affected by the command appears after the open- ing tag. Opening tags always begin with < and end with >, as in . .A closing tag is an HTML tag that indicates the end of an HTML com- mand; the text affected by the command appears before the closing tag. Closing tags always begin with , as in . NOTE It isn’t terribly important that you understand concepts such as character encoding at this point. What is important is that you include the appropriate boil- erplate code in your pages so that they adhere to the latest web standards. As of this writ- ing, XHTML 1.1 is a web stan- dard. HTML 5 is not yet a web standard, but if you were creat- ing an HTML 5 document, these lines at the beginning of your HTML file would not be neces- sary. NOTE The XML/XHTML boilerplate code isn’t strictly required in order for you to create web pages. You can delete the opening lines of code in the example so that the page starts with the tag and it will still open fine in a web browser. The extra code is included to ensure your pages are up to date with the current web standards. Additionally, the extra code allows you to vali- date your web pages for accura- cy, which you’ll learn how to do a bit later in this lesson. www.it-ebooks.info ptg HTML Tags Every XHTML Web Page Must Have 33 . An empty tag is an HTML tag that issues an HTML command with- out enclosing any text in the page. Empty tags always begin with < and end with />, as in
and . For example, the tag in Listing 3.1 tells the web browser where the actual body text of the page begins, and indicates where it ends. Everything between the and tags will appear in the main display area of the web browser window, as shown in Figure 3.1. The very top of the browser window (refer to Figure 3.1) shows title text, which is any text that is located between and . The title text is also used to identify the page on the browser’s Bookmarks or Favorites menu, depending on which browser you use. It’s important to provide titles for your pages so that visitors to the page can properly bookmark them for future reference. You will use the and tag pairs in every HTML page you cre- ate because every web page needs a title and body text. You will also use <html> and <head>, which are he other two tags shown in Listing 3.1. Putting <html> at the very beginning of a document simply indicates that the document is a web page. The </html> at the end indicates that the web page is over. Within a page, there is a head section and a body section. Each section is identified by <head> and <body> tags. The idea is that information in the head of the page somehow describes the page but isn’t actually displayed by a web browser. Information placed in the body, however, is displayed by a web browser. The <head> tag always appears near the beginning of the HTML code for a page, just after the opening <html> tag. The <title> tag pair used to identify the title of a page appears within the head of the page, which means it is placed after the opening <head> tag and before the closing </head> tag. (Upcoming hours reveal some other advanced header information that can go between <head> and </head>, such as style sheet rules that are used to format the page.) The <p> tag used in Listing 3.1 encloses a paragraph of text. You should enclose your chunks of text in the appropriate container tags whenever possible. NOTE You no doubt noticed in Listing 3.1 that there is some extra code associated with the <html> tag. This code consists of two attributes (xmlns and xml:lang), which are used to specify additional information related to the tag. These two attributes are standard require- ments of all XHTML web pages; the former defines the XML namespace, while the latter defines the language of the content. Throughout this book a standard namespace is defined, and the English lan- guage is used. If you are writing in a different language, replace the “en” (for English) with the language identifier relevant to you. TIP You might find it convenient to create and save a bare-bones page (also known as a skeleton page) with just the opening and closing <html>, <head>, <title>, and <body> tags, similar to the document used in Listing 3.1. You can then open that docu- ment as a starting point when- ever you want to make a new web page and save yourself the trouble of typing all those oblig- atory tags every time. www.it-ebooks.info ptg 34 HOUR 3: Understanding HTML and XHTML Connections Organizing a Page with Paragraphs and Line Breaks When a web browser displays HTML pages, it pays no attention to line endings or the number of spaces between words. For example, the top ver- sion of the poem shown in Figure 3.2 appears with a single space between all words, even though that’s not how it’s entered in Listing 3.2. This is because extra whitespace in HTML code is automatically reduced to a sin- gle space. Additionally, when the text reaches the edge of the browser win- dow, it automatically wraps to the next line, no matter where the line breaks were in the original HTML file. Listing 3.2 HTML Containing Paragraph and Line Breaks <?xml version=”1.0” encoding=”UTF-8”?> <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN” “http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”> <html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en”> <head> <title>The Advertising Agency Song

When your client’s hopping mad, put his picture in the ad. If he still should prove refractory, add a picture of his factory.


When your client’s hopping mad,
put his picture in the ad.

If he still should prove refractory,
add a picture of his factory.

www.it-ebooks.info ptg Organizing a Page with Paragraphs and Line Breaks 35 FIGURE 3.2 When the HTML in Listing 3.2 is viewed as a web page, line and paragraph breaks only appear where there are
and

tags. You must use HTML tags if you want to control where line and paragraph breaks actually appear. When text is enclosed within the

container tags, a line break will be assumed after the closing tag. In later hours, you will learn to control the height of the line break using CSS. The
tag forces a line break within a paragraph. Unlike the other tags you’ve seen so far,
doesn’t require a closing
tag—this is one of those empty tags discussed earlier. Although HTML 4 does not require the / in empty tags, XHTML does and future standards will, so it’s important for you to stick to the latest standards and create web pages that are coded properly. Always code empty tags so that they end with />. The poem in Listing 3.2 and Figure 3.2 shows the
and

tags being used to separate the lines and verses of an advertising agency song. You might have also noticed the


tag in the listing, which causes a horizontal rule line to appear on the page (see Figure 3.2). Inserting a hori- zontal rule with the
tag also causes a line break, even if you don’t include a
tag along with it. Like
, the
horizontal rule tag is an empty tag and therefore never gets a closing tag. WARNING You might find that a lot of web content that includes
instead of
. Or you might find that it does not include the closing

tag. Just remem- ber there is a lot of antiquated web content floating around the Internet, and just because you see it in use doesn’t mean it’s correct. Save yourself a lot of future work and frustration by adhering to the standards you learn in this book. Developing clean HTML coding habits is a very important part of becoming a successful web designer. www.it-ebooks.info ptg 36 HOUR 3: Understanding HTML and XHTML Connections Organizing Your Content with Headings When you browse through web pages on the Internet, you’ll notice that many of them have a heading at the top that appears larger and bolder than the rest of the text. Listing 3.3 is sample code and text for a simple web page containing an example of a heading as compared to normal paragraph text. Any text between

and

tags will appear as a large heading. Additionally,

and

make progressively smaller head- ings, and so on as far down as

. TRY IT YOURSELF▼ Formatting Text in HTML Take a passage of text and try your hand at formatting it as proper HTML: 1. Add My Title to the begin- ning of the text (using your own title for your page instead of My Title). Also include the boilerplate code at the top of the page that takes care of meeting the requirements of XHTML. 2. Add to the very end of the text. 3. Add a

tag at the beginning of each paragraph and a

tag at the end of each paragraph. 4. Use
tags anywhere you want single-spaced line breaks. 5. Use
to draw horizontal rules separating major sections of text, or wherever you’d like to see a line across the page. 6. Save the file as mypage.html (using your own filename instead of mypage). 7. Open the file in a web browser to see your web content. (Send the file via FTP to your web hosting account, if you have one.) 8. If something doesn’t look right, go back to the text editor to make corrections and save the file again (and send it to your web hosting account, if applicable). You then need to click Reload/Refresh in the browser to see the changes you made. WARNING If you are using a word processor to create the web page, be sure to save the HTML file in plain-text or ASCII format. www.it-ebooks.info ptg Organizing Your Content with Headings 37 Listing 3.3 Heading Tags My Widgets

My Widgets

My widgets are the best in the land. Continue reading to learn more about my widgets.

Widget Features

If I had any features to discuss, you can bet I’d do it here.

Pricing

Here, I would talk about my widget pricing.

Comparisons

Here, I would talk about how my widgets compare to my competitor’s widgets.

As you can see in Figure 3.3, the HTML that creates headings couldn’t be simpler. In this example, the phrase “My Widgets” is prominently dis- played using the

tag. To create the biggest (level-1) heading, just put an

tag at the beginning and a

tag at the end of the text you wish to use as a heading. For a slightly smaller (level-2) heading—for informa- tion that is of lesser importance than the title— use the

and

tags around your text. For content that should appear even less prominently than a level-2 heading, use the

and

tags around your text. Your headings should follow a content hierarchy; use only one level-1 heading, have one (or more) level-2 headings after the level-1 heading, use level-3 headings directly after level-2 headings, and so on. Theoretically, you can also use

,

, and
tags to make progres- NOTE By now you’ve probably caught on to the fact that HTML code is often indented by its author to reveal the relationship between different parts of the HTML document. This indenta- tion is entirely voluntary—you could just as easily run all the tags together with no spaces or line breaks and they would still look fine when viewed in a browser. The indentations are for you so that you can quickly look at a page full of code and understand how it fits together. Indenting your code is a very good web design habit and ulti- mately makes your pages easi- er to maintain. www.it-ebooks.info ptg 38 HOUR 3: Understanding HTML and XHTML Connections sively less important headings, but these aren’t used very often. Web browsers seldom show a noticeable difference between these headings and the

headings anyway, and content usually isn’t displayed in such a manner as to need six levels of headings in order to show the content hier- archy. It’s important to remember the difference between a title and a heading. These two words are often interchangeable in day-to-day English, but when you’re talking HTML, gives the entire page an identifying name that isn’t displayed on the page itself; it’s displayed only on the browser window’s title bar. The heading tags, on the other hand, cause some text on the page to be displayed with visual emphasis. There can be only one <title> per page and it must appear within the <head> and </head> tags, whereas you can have as many <h1>, <h2>, and <h3> headings as you want, in any order that suits your fancy. However, as I mentioned before, you should use the heading tags to keep tight control over content hierar- chy; do not use headings as a way to achieve a particular “look,” as that’s what CSS is for. You’ll learn to take complete control over the appearance of text on your FIGURE 3.3 The use of three levels of head- ings shows the hierarchy of con- tent on this sample product page. NOTE On many web pages nowadays, graphical images of ornately rendered letters and logos are often used in place of the ordi- nary text headings discussed in this hour. However, using text headings is one of many search engine optimization (SEO) tips that you will learn about in Hour 24, “Helping People Find Your Web Pages.” Search engines look at heading tags to see how you organize your content; they give higher preference to content that you have indicated is more important (for example, a level-1 heading) versus con- tent that you indicate is of less- er importance (lower-level head- ings). www.it-ebooks.info ptg Validating Your Web Content 39 web pages in Part II of this book. Short of taking exacting control of the size, family, and color of fonts, headings provide the easiest and most pop- ular way to draw extra attention to important text. Peeking at Other Designers’ Pages Given the visual and sometimes audio pizzazz present in many popular web pages, you probably realize that the simple pages described in this hour are only the tip of the HTML iceberg. Now that you know the basics, you might surprise yourself with how much of the rest you can pick up just by looking at other people’s pages on the Internet. You can see the HTML for any page by right-clicking and selecting View Source in any web browser. Don’t worry if you aren’t yet able to decipher what some HTML tags do or exactly how to use them yourself. You’ll find out about all those things in the next few hours. However, sneaking a preview now will show you the tags that you do know in action and give you a taste of what you’ll soon be able to do with your web pages. Validating Your Web Content In Hour 2, I discussed ways to test your pages; one very important way to test your pages is to validate them. Think of it this way: it’s one thing to design and draw a beautiful set of house plans, but it’s quite another for an architect to stamp it as a safe structure suitable for construction. Validating your web pages is a similar process; in this case, however, the architect is an application—not a person. In brief, validation is the process of testing your pages with a special appli- cation that searches for errors and makes sure your pages follow the strict XHTML standard. Validation is simple. In fact, the standards body respon- sible for developing web standards—the World Wide Web Consortium (W3C)—offers an online validation tool you can use. To validate a page, follow this URL: http://validator.w3.org/. The W3C Markup Validation Service is shown in Figure 3.4. WARNING Don’t forget that anything placed in the head of a web page is not intended to be viewed on the page, whereas everything in the body of the page is intended for viewing. www.it-ebooks.info ptg 40 HOUR 3: Understanding HTML and XHTML Connections If you’ve already published a page online, you can use the Validate by URI tab. Use the Validate by File Upload tab to validate files stored on your local computer file system. The Validate by Direct Input tab allows you to paste the contents of a file from your text editor. If all goes well, your page will get a passing report (see Figure 3.5). FIGURE 3.4 The W3C Markup Validation Service allows you to validate an HTML (XHTML) document to ensure it has been coded accurately. FIGURE 3.5 If a page passes the W3C Markup Validation Service, you know it is ready for prime time. www.it-ebooks.info ptg The Scoop on HTML, XML, XHTML, and HTML 5 41 If the W3C Markup Validation Service encounters an error in your web page, it will provide specific details (including the line numbers of the offending code). This is a great way to hunt down problems and rid your pages of buggy code. Validation not only informs you whether your pages are constructed properly, it also assists you in finding and fixing problems before you post pages for the world to see. The Scoop on HTML, XML, XHTML, and HTML 5 In its early days, HTML was great because it allowed scientists to share infor- mation over the Internet in an efficient and relatively structured manner. It wasn’t until later that graphical web browsers were created and HTML started being used to code more than scientific papers. HTML quickly went from a tidy little markup language for researchers to an online publishing language. After it was established that HTML could be jazzed up for graphical brows- ing, the creators of web browsers went crazy by adding lots of nifty features to the language. Although these new features were neat at first, they compro- mised the original design of HTML and introduced inconsistencies when it came to how browsers displayed web pages; new features worked on only one browser or another, and you were out of luck if you happened to be run- ning the wrong browser. HTML started to resemble a bad remodeling job on a —a job done by too many contractors and without proper planning. As it turns out, some of the browser-specific features created during this time have now been adopted as standards while others have been dropped completely. As with most revolutions, the birth of the Web was very chaotic, and the modifications to HTML reflected that chaos. Over the years, a significant effort has been made to reel in the inconsistencies of HTML and restore some order to the language. The problem with disorder in HTML is that it results in web browsers having to guess at how a page is to be displayed, which is not a good thing. Ideally, a web page designer should be able to define exact- ly how a page is to look and have it look the same regardless of what kind of browser or operating system someone is using. Better still, a designer should be able to define exactly what a page means and have that page look consis- tent across different browsers and platforms. This utopia is still off in the future somewhere, but a markup language called XML (Extensible Markup Language) began to play a significant role in leading us toward it. XML is a general language used to create specific languages, such as HTML. It might sound a little strange, but it really just means that XML TIP Some web development tools include built-in validation fea- tures you can use in lieu of the W3C Markup Validation Service. Some examples include brows- er extensions such as Firebug (http://getfirebug.com/) and HTML Validator (http://users.skynet.be/mg ueury/mozilla/), but many other programs offer similar functionality—check your user documentation. www.it-ebooks.info ptg 42 HOUR 3: Understanding HTML and XHTML Connections provides a basic structure and set of rules to which any markup language must adhere. Using XML, you can create a unique markup language to describe just about any kind of information, including web pages. Knowing that XML is a language for creating other markup languages, you could create your own version of HTML using XML. You could even create a markup language called BCCML (Bottle Cap Collection Markup Language), for example, which you could use to create and manage your extensive collection of rare bottle caps. The point is that XML lays the ground rules for organizing information in a consistent manner, and that information can be anything from web pages to bottle caps. You might be thinking that bottle caps don’t have anything to do with the Web, so why mention them? The reason is that XML is not entirely about web pages. XML is actually broader than the Web in that it can be used to represent any kind of information on any kind of computer. If you can visualize all the information whizzing around the globe among computers, mobile phones, handheld computers, televisions, and radios, you can start to understand why XML has much broader applications than just cleaning up web pages. However, one of the first applications of XML is to restore some order to the Web, which is why XML is relevant to learning HTML. If XML describes data better than HTML, does it mean that XML is set to upstage HTML as the markup language of choice for the Web? No. XML is not a replacement for HTML; it’s not even a competitor of HTML. XML’s impact on HTML has to do with cleaning up HTML. HTML is a relatively unstruc- tured language that benefits from the rules of XML. The natural merger of the two technologies resulted in HTML’s adherence to the rules and structure of XML. To accomplish this merger, a new version of HTML was formulated that follows the stricter rules of XML. The new XML-compliant version of HTML is known as XHTML. Fortunately for you, you’ll actually be learning XHTML throughout this book since it is really just a cleaner version of HTML. You might have heard about HTML 5, which is touted as the next web standard. It will be, but not for several years. When it does become a web standard, it will not render XHTML useless—HTML 5 is not a replacement for XHTML, but is a major revision of HTML 4. In other words, XHTML and HTML 5 can coexist on the web, and web browsers that currently sup- port XHTML will also (one day) support HTML 5 as well. The goal of this book is to guide you through the basics of web publishing, using XHTML and CSS as the core languages of those pages. However, whenever possible I will note elements of the languages that are not pres- ent in HTML 5, should you want to design your content for even further www.it-ebooks.info ptg Summary 43 sustainability. If you gain a solid understanding of web publishing and the ways in which CSS works with the overall markup language of the page (be it XHTML or HTML 5), you will be in a good position if, in a few years, you decide you want to move from XHTML to HTML 5. Summary This hour introduced the basics of what web pages are and how they work. You learned that coded HTML commands are included in a text file, and that typing HTML text yourself is better than using a graphical editor to create HTML commands for you—especially when you’re learning HTML. You were introduced to the most basic and important HTML tags. By adding these coded commands to any plain-text document, you can quickly transform it into a bona fide web page. You learned that the first step in creating a web page is to put a few obligatory HTML tags at the beginning and end, including a title for the page. You then mark where paragraphs and lines end and add horizontal rules and headings if you want them. Table 3.1 summarizes all the tags introduced in this hour. Table 3.1 HTML Tags Covered in Hour 3 Tag Function <html>…</html> Encloses the entire HTML document. <head>…</head> Encloses the head of the HTML document. Used with- in the <html> tag pair. <title>… Indicates the title of the document. Used within the tag pair. … Encloses the body of the HTML document. Used with- in the tag pair.

A paragraph; skips a line between paragraphs.
A line break.
A horizontal rule line.

A first-level heading.

A second-level heading.

A third-level heading.

A fourth-level heading (seldom used).
A fifth-level heading (seldom used).
A sixth-level heading (seldom used). www.it-ebooks.info ptg 44 HOUR 3: Understanding HTML and XHTML Connections Finally, you learned about XML and XHTML, and how they relate to HTML, as well as what “HTML 5” means in relation to what it is you’re learning here. Q&A Q I’ve created a web page, but when I open the file in my web browser, I see all the text including the HTML tags. Sometimes I even see weird gobbledygook characters at the top of the page! What did I do wrong? A You didn’t save the file as plain-text. Try saving the file again, being careful to save it as Text Only or ASCII Text. If you can’t quite figure out how to get your word processor to do that, don’t stress. Just type your HTML files in Notepad or TextEdit instead and everything should work just fine. (Also, always make sure that the filename of your web page ends in .html or .htm.) Q I’ve seen web pages on the Internet that don’t have tags at the beginning. You said pages always have to start with . What’s the deal? A Many web browsers will forgive you if you forget to include the tag and will display the page correctly anyway. However, it’s a very good idea to include it because some software does need it to identify the page as valid HTML. Besides, you want your pages to be bona fide XHTML pages so that they conform to the latest web standards. Workshop The workshop contains quiz questions and activities to help you solidify your understanding of the material covered. Try to answer all questions before looking at the “Answers” section that follows. Quiz 1. What four tags are required in every HTML page? 2. What HTML tags and text would you use to produce the following web content: .A small heading with the words We are Proud to Present .A horizontal rule across the page .A large heading with the one word Orbit www.it-ebooks.info ptg Workshop 45 . A medium-sized heading with the words The Geometric Juggler . Another horizontal rule 3. What code would you use to create a complete HTML web page with the title Foo Bar, a heading at the top that reads Happy Hour at the Foo Bar, followed by the words Come on down! in regular type? Answers 1. , , , and <body> (along with their closing tags, </html>, </head>, , and ). 2. Your code would look like this:

We are Proud to Present


Orbit

The Geometric Juggler


3. Your code would look like this: Foo Bar

Happy Hour at the Foo Bar

Come on Down!

www.it-ebooks.info ptg 46 HOUR 3: Understanding HTML and XHTML Connections Exercises . Even if your main goal in reading this book is to create web content for your business, you might want to make a personal web page just for practice. Type a few paragraphs to introduce yourself to the world and use the HTML tags you’ve learned in this hour to make them into a web page. . Throughout the book you’ll be following along with the code exam- ples and making pages of your own. Take a moment now to set up a basic document template containing the XML declaration, doctype declaration, and tags for the core HTML document structure. That way, you can be ready to copy and paste that information whenever you need it. www.it-ebooks.info ptg In the previous hour, you learned the basics of HTML and XHTML, includ- ing how to set up a skeletal HTML template for all your web content. In this hour, you will learn how to fine-tune the display of your web content using cascading style sheets(CSS). The concept behind style sheets is simple: You create a style sheet document that specifies the fonts, colors, spacing, and other characteristics that establish a unique look for a web site. You then link every page that should have that look to the style sheet, instead of specifying all those styles repeatedly in each separate document. Therefore, when you decide to change your official corporate typeface or color scheme, you can modify all your web pages at once just by changing one or two entries in your style sheet rather than changing them in all of your static web files. So a style sheet is a grouping of formatting instruc- tions that control the appearance of several HTML pages at once. Style sheets enable you to set a great number of formatting characteristics, including exacting typeface controls, letter and line spacing, and margins and page borders, just to name a few. Style sheets also enable sizes and other measurements to be specified in familiar units, such as inches, mil- limeters, points, and picas. You can also use style sheets to precisely posi- tion graphics and text anywhere on a web page, either at specific coordi- nates or relative to other items on the page. In short, style sheets bring a sophisticated level of display to the Web. And they do so—you’ll pardon the expression—with style. HOUR 4 Understanding Cascading Style Sheets WHAT YOU’LL LEARN IN THIS HOUR: . How to create a basic style sheet . How to use style classes . How to use style IDs . How to construct internal style sheets and inline styles NOTE If you have three or more web pages that share (or should share) similar formatting and fonts, you might want to create a style sheet for them as you read this hour. Even if you choose not to create a com- plete style sheet, you’ll find it helpful to apply styles to individ- ual HTML elements directly within a web page. www.it-ebooks.info ptg 48 HOUR 4: Understanding Cascading Style Sheets How CSS Works The technology behind style sheets is called CSS, which stands for Cascading Style Sheets. CSS is a language that defines style constructs such as fonts, colors, and positioning, which are used to describe how informa- tion on a web page is formatted and displayed. CSS styles can be stored directly in an HTML web page or in a separate style sheet file. Either way, style sheets contain style rules that apply styles to elements of a given type. When used externally, style sheet rules are placed in an external style sheet document with the file extension .css. A style rule is a formatting instruction that can be applied to an element on a web page, such as a paragraph of text or a link. Style rules consist of one or more style properties and their associated values. An internal style sheet is placed directly within a web page, whereas an external style sheet exists in a separate document and is simply linked to a web page via a special tag— more on this tag in a moment. The “cascading” part of the name CSS refers to the manner in which style sheet rules are applied to elements in an HTML document. More specifical- ly, styles in a CSS style sheet form a hierarchy in which more specific styles override more general styles. It is the responsibility of CSS to determine the precedence of style rules according to this hierarchy, which establishes a cascading effect. If that sounds a bit confusing, just think of the cascading mechanism in CSS as being similar to genetic inheritance, in which general traits are passed from parents to a child, but more specific traits are entire- ly unique to the child. Base style rules are applied throughout a style sheet but can be overridden by more specific style rules. A quick example should clear things up. Take a look at the following code to see whether you can tell what’s going on with the color of the text:
This text is green.

This text is blue.

This text is still green.

In the previous example, the color green is applied to the
tag via the color style property. Therefore, the text in the
tag is colored green. Because both

tags are children of the

tag, the green text style cas- cades down to them. However, the first

tag overrides the color style and changes it to blue. The end result is that the first line (not surrounded by a paragraph tag) is green, the first official paragraph is blue and the sec- ond official paragraph retains the cascaded green color. NOTE You might notice that I use the term element a fair amount in this hour (and I will for the rest of the book, for that matter). An element is simply a piece of information (content) in a web page, such as an image, a para- graph, or a link. Tags are used to code elements, and you can think of an element as a tag complete with descriptive infor- mation (attributes, text, images, and so on) within the tag. www.it-ebooks.info ptg A Basic Style Sheet 49 Like many web technologies, CSS has evolved over the years. The original version of CSS, known as Cascading Style Sheets Level 1 (CSS1) was created in 1996. The later CSS 2 standard was created in 1998 and CSS 2 is still in use today. All modern web browsers support CSS 2, and you can safely use CSS 2 style sheets without too much concern. So when I talk about CSS throughout the book, I’m referring to CSS 2. You’ll find a complete reference guide to CSS at http://www.w3.org/Style/CSS/. The rest of this hour explains how to put CSS to good use. A Basic Style Sheet Despite their intimidating power, style sheets can be simple to create. Consider the web pages shown in Figure 4.1 and Figure 4.2. These pages share several visual properties that could be put into a common style sheet: . They use a large, bold Verdana font for the headings and a normal size and weight Verdana font for the body text. . They use an image named logo.gif floating within the content and on the right side of the page. . All text is black except for subheadings, which are purple. . They have margins on the left side and at the top. . There is vertical space between lines of text. . The footnotes are centered and in small print. FIGURE 4.1 This page uses a style sheet to fine-tune the appearance and spacing of the text and images. www.it-ebooks.info ptg 50 HOUR 4: Understanding Cascading Style Sheets Listing 4.1 shows the code for style sheet specifying these properties. Listing 4.1 A Single External Style Sheet body { font-size: 10pt; font-family: Verdana, Geneva, Arial, Helvetica,sans-serif; color: black; line-height: 14pt; padding-left: 5pt; padding-right: 5pt; padding-top: 5pt; } h1 { font: 14pt Verdana, Geneva, Arial, Helvetica,sans-serif; font-weight: bold; line-height: 20pt; } p.subheader { font-weight: bold; color: #593d87; } img { padding: 3pt; float: right; } FIGURE 4.2 This page uses the same style sheet as the one shown in Figure 4.1, thus maintaining a consistent look and feel. www.it-ebooks.info ptg A Basic Style Sheet 51 Listing 4.1 A Single External Style Sheet a { text-decoration: none; } a:link, a:visited { color: #8094d6; } a:hover, a:active { color: #FF9933; } div.footer { font-size: 9pt; font-style: italic; line-height: 12pt; text-align: center; padding-top: 30pt; } This might initially appear to be a lot of code, but if you look closely, you’ll see that there isn’t a lot of information on each line of code. It’s fairly stan- dard to place individual style rules on their own line to help make style sheets more readable. Speaking of code readability, perhaps the first thing you noticed about this style sheet code is that it doesn’t look anything like normal HTML code. CSS uses a language all its own to specify style sheets. Of course, the listing includes some familiar HTML tags. As you might guess, body, h1, p, img, a, and div in the style sheet refer to the correspon- ding tags in the HTML documents to which the style sheet will be applied. The curly braces after each tag name contain the specifications for how all content within that tag should appear. In this case, all body text should be rendered at a size of 10 points, in the Verdana font (if possible), and with the color black and 14 points between lines. If the user does not have the Verdana font installed, the list of fonts in the style sheet represents the order in which the browser should search for fonts to use: Geneva, then Arial, then Helvetica. If the user has none of those fonts, the browser will use whatever default sans-serif font is avail- able. Additionally, the page should have left, right, and top margins of 5 points each. Any text within an

tag should be rendered in boldface Verdana at a size of 14 points. Moving on, any paragraph that uses only the

tag will www.it-ebooks.info ptg 52 HOUR 4: Understanding Cascading Style Sheets inherit all the styles indicated by the body element. However, if the

tag uses a special class named subheader, the text will appear bold and in the color #593d87 (a purple color). The pt after each measurement in Listing 4.1 means points (there are 72 points in an inch). If you prefer, you can specify any style sheet measure- ment in inches (in), centimeters (cm), pixels (px), or widths-of-a-letter-m, which are called ems (em). You might have noticed that each style rule in the listing ends with a semi- colon (;). Semicolons are used to separate style rules from each other. It is therefore customary to end each style rule with a semicolon so you can easily add another style rule after it. To link this style sheet to HTML documents, include a tag in the section of each document. Listing 4.2 shows the HTML code for the page shown in Figure 4.1. It contains the following tag: This assumes that the style sheet is stored under the name styles.css in the same folder as the HTML document. As long as the web browser sup- ports style sheets—and all modern browsers do support style sheets—the properties specified in the style sheet will apply to the content in the page without the need for any special HTML formatting code. This confirms the ultimate goal of XHTML, which is to provide a separation between the content in a web page and the specific formatting required to display that content. Listing 4.2 HTML Code for the Page Shown in Figure 4.1 About BAWSI

About BAWSI

”BAWSIThe Bay Area Women’s Sports Initiative (BAWSI) is a public benefit, nonprofit corporation with a mission to create programs and partnerships through which women athletes bring health, hope and wholeness to our community. Founded in 2005 by Olympic and World Cup soccer NOTE You can specify font sizes as large as you like with style sheets, although some display devices and printers will not correctly handle fonts larger than 200 points. www.it-ebooks.info ptg A Basic Style Sheet 53 Listing 4.2 HTML Code for the Page Shown in Figure 4.1 stars Brandi Chastain and Julie Foudy and Marlene Bjornsrud, former general manager of the San Jose CyberRays women’s professional soccer team, BAWSI provides a meaningful path for women athletes to become a more visible and valued part of the Bay Area sports culture.

BAWSI’s History

The concept of BAWSI was inspired by one of the most spectacular achievements in women’s sports history and born out of one its biggest disappointments...

[continue reading]

Copyright © 2005-2009 BAWSI (www.bawsi.org). All rights reserved. Used with permission.
The code in Listing 4.2 is interesting because it contains no formatting of any kind. In other words, there is nothing in the HTML code that dictates how the text and images are to be displayed—no colors, no fonts, nothing. Yet the page is carefully formatted and rendered to the screen, thanks to the link to the external style sheet, styles.css. The real benefit to this approach is that you can easily create a site with multiple pages that main- tains a consistent look and feel. And you have the benefit of isolating the visual style of the page to a single document (the style sheet) so that one change impacts all pages. TIP In most web browsers, you can view the style rules in a style sheet by opening the .css file and choosing Notepad or anoth- er text editor as the helper application to view the file. (To determine the name of the .css file, look at the HTML source of any web page that links to it.) To edit your own style sheets, just use a text editor. NOTE Although CSS is widely support- ed in all modern web browsers, it hasn’t always enjoyed such wide support. Additionally, not every browser’s support of CSS is flawless. To find out about how major browsers compare to each other in terms of CSS sup- port, take a look at this web site: http://www.quirksmode.org/css /contents.html. Create a Style Sheet of Your Own Starting from scratch, create a new text document called mystyles.css and add some style rules for the following basic HTML tags: ,

,

, and

. Once your style sheet has been created, make a new HTML file that contains these basic tags. Play around with different style rules and see for yourself how simple it is to change entire blocks of text in para- graphs with one simple change in a style sheet file. TRY IT YOURSELF ▼ www.it-ebooks.info ptg 54 HOUR 4: Understanding Cascading Style Sheets A CSS Style Primer You now have a basic knowledge of CSS style sheets and how they are based on style rules that describe the appearance of information in web pages. The next few sections of this hour provide a quick overview of some of the most important style properties and allow you to get started using CSS in your own style sheets. CSS includes various style properties that are used to control fonts, colors, alignment, and margins, to name just a few. The style properties in CSS can be generally grouped into two major categories: . Layout properties, which consist of properties that impact the posi- tioning of elements on a web page, such as margins, padding, align- ment, and so on. . Formatting properties, which consist of properties that affect the visual display of elements within a web site, such as the font type, size, color, and so on. Layout Properties CSS layout properties are used to determine how content is placed on a web page. One of the most important layout properties is the display prop- erty, which describes how an element is displayed with respect to other elements. There are four possible values for the display property: . block—The element is displayed on a new line, as in a new paragraph. . list-item—The element is displayed on a new line with a list-item mark (bullet) next to it. . inline—The element is displayed inline with the current paragraph. . none—The element is not displayed; it is hidden. It’s easier to understand the display property if you visualize each element on a web page occupying a rectangular area when displayed—the display property controls the manner in which this rectangular area is displayed. For example, the block value results in the element being placed on a new line by itself, whereas the inline value places the element next to the con- tent just before it. The display property is one of the few style properties that can be applied in most style rules. Following is an example of how to set the display property: display:block; NOTE The display property relies on a concept known as relative positioning, which means that elements are positioned rela- tive to the location of other ele- ments on a page. CSS also supports absolute positioning, which allows you to place an element at an exact location on a page independent of other elements. You’ll learn more about both of these types of positioning in Part III, “Advanced Web Design with CSS.” www.it-ebooks.info ptg A CSS Style Primer 55 You control the size of the rectangular area for an element with the width and height properties. Like many size-related CSS properties, width and height property values can be specified in several different units of meas- urement: . in—Inches . cm—Centimeters . mm—Millimeters . px—Pixels . pt—Points You can mix and match units however you choose within a style sheet, but it’s generally a good idea to be consistent across a set of similar style prop- erties. For example, you might want to stick with points for font properties or pixels for dimensions. Following is an example of setting the width of an element using pixel units: width: 200px; Formatting Properties CSS formatting properties are used to control the appearance of content on a web page, as opposed to controlling the physical positioning of the con- tent. One of the most popular formatting properties is the border property, which is used to establish a visible boundary around an element with a box or partial box. The following border properties provide a means of describing the borders of an element: . border-width—The width of the border edge. . border-color—The color of the border edge. . border-style—The style of the border edge. . border-left—The left side of the border. . border-right—The right side of the border. . border-top—The top of the border. . border-bottom—The bottom of the border. . border—All the border sides. www.it-ebooks.info ptg 56 HOUR 4: Understanding Cascading Style Sheets The border-width property is used to establish the width of the border edge. It is often expressed in pixels, as the following code demonstrates: border-width:5px; Not surprisingly, the border-color and border-style properties are used to set the border color and style. Following is an example of how these two properties are set: border-color:blue; border-style:dotted; The border-style property can be set to any of the following values: . solid—A single-line border. . double—A double-line border. . dashed—A dashed border. . dotted—A dotted border. . groove—A border with a groove appearance. . ridge—A border with a ridge appearance. . inset—A border with an inset appearance. . outset—A border with an outset appearance. . none—No border. The default value of the border-style property is none, which is why ele- ments don’t have a border unless you set the border property to a different style. The most common border styles are the solid and double styles. The border-left, border-right, border-top, and border-bottom properties allow you to set the border for each side of an element individually. If you want a border to appear the same on all four sides, you can use the single border property by itself, which expects the following styles separated by a space: border-width, border-style, and border-color. Following is an exam- ple of using the border property to set a border that consists of two (dou- ble) red lines that are a total of 10 pixels in width: border:10px double red; Whereas the color of an element’s border is set with the border-color prop- erty, the color of the inner region of an element is set using the color and background-color properties. The color property sets the color of text in an NOTE The exception to the default border-style of none is when an image is placed within an tag so that it serves as a linked image. In that case, a solid border is automatically set by default. That’s why you often see linked images with the style border-style:none, which turns off the automatic border. www.it-ebooks.info ptg A CSS Style Primer 57 element (foreground) and the background-color property sets the color of the background behind the text. Following is an example of setting both color properties to predefined colors: color:black; background-color:orange; You can also assign custom colors to these properties by specifying the col- ors in hexadecimal (covered in more detail in Hour 9, “Working with Colors”) or as RGB (Red Green Blue) decimal values, just as you do in HTML: background-color:#999999; color:rgb(0,0,255); You can also control the alignment and indentation of web page content without too much trouble. This is accomplished with the text-align and text-indent properties, as the following code demonstrates: text-align:center; text-indent:12px; After you have an element properly aligned and indented, you might be interested in setting its font. The following font properties are used to set the various parameters associated with fonts: . font-family—The family of the font. . font-size—The size of the font. . font-style—The style of the font (normal or italic). . font-weight—The weight of the font (light, medium, bold, and so on). The font-family property specifies a prioritized list of font family names. A prioritized list is used instead of a single value to provide alternatives in case a font isn’t available on a given system. The font-size property speci- fies the size of the font using a unit of measurement, usually points. Finally, the font-style property sets the style of the font and the font- weight property sets the weight of the font. Following is an example of set- ting these font properties: font-family: Arial, sans-serif; font-size: 36pt; font-style: italic; font-weight: medium; www.it-ebooks.info ptg 58 HOUR 4: Understanding Cascading Style Sheets Now that you know a whole lot more about style properties and how they work, refer back at Listing 4.1 and see whether it makes a bit more sense. Here’s a recap of the style properties used in that style sheet, which you can use as a guide for understanding how it works: . font—Lets you set many font properties at once. You can specify a list of font names separated by commas; if the first is not available, the next is tried, and so on. You can also include the words bold and/or italic and a font size. Each of these font properties can be specified separately with font-family, font-size, font-weight, and font-style if you prefer. . line-height—Also known in the publishing world as leading. This sets the height of each line of text, usually in points. . color—Sets the text color using the standard color names or hexadec- imal color codes (see Hour 9 for more details). . text-decoration—Useful for turning link underlining off—simply set it to none. The values of underline, italic, and line-through are also supported. The application of styles to links is covered in more detail in Hour 8, “Using External and Internal Links.” . text-align—Aligns text to the left, right, or center, along with justi- fying the text with a value of justify. . padding—Adds padding to the left, right, top, and bottom of an ele- ment; this padding can be in measurement units or a percentage of the page width. Use padding-left and padding-right if you want to add padding to the left and right of the element independently. Use padding-top or padding-bottom to add padding to the top or bottom of the element, as appropriate. You’ll learn more about these style prop- erties in Hours 14 and 15. Using Style Classes This is a “teach yourself” book, so you don’t have to go to a single class to learn how to give your pages great style, although you do need to learn what a style class is. Whenever you want some of the text on your pages to look different from the other text, you can create what amounts to a cus- tom-built HTML tag. Each type of specially formatted text you define is called a style class. A style class is a custom set of formatting specifications that can be applied to any element in a web page. www.it-ebooks.info ptg Using Style Classes 59 Before showing you a style class, I need to take a quick step back and clari- fy some CSS terminology. First off, a CSS style property is a specific style that can be assigned a value, such as color or font-size. You associate a style property and its respective value with elements on a web page by using a selector. A selector is used to identify tags on a page to which you apply styles. Following is an example of a selector, a property, and a value all included in a basic style rule: h1 { font: 36pt Courier; } In this code, h1 is the selector, font is the style property, and 36pt Courier is the value. The selector is important because it means that the font setting will be applied to all h1 elements in the web page. But maybe you want to differentiate between some of the h1 elements—what then? The answer lies in style classes. Suppose you want two different kinds of

headings for use in your documents. You would create a style class for each one by putting the fol- lowing CSS code in a style sheet: h1.silly { font: 36pt Comic Sans; } h1.serious { font: 36pt Arial; } Notice that these selectors include a period (.) after h1, followed by a descriptive class name. To choose between the two style classes, use the class attribute, like this:

Marvin’s Munchies Inc.

Text about Marvin’s Munchies goes here.

Or you could use this:

MMI Investor Information

Text for business investors goes here.

When referencing a style class in HTML code, simply specify the class name in the class attribute of an element. In the previous example, the words Marvin’s Munchies Inc. would appear in a 36-point Comic Sans font, assuming that you included a to the style sheet at the top of the web page and assuming that the user has the Comic Sans font installed. The words MMI Investor Information would appear in the 36- point Arial font instead. You can see another example of classes in action in Listing 4.2: look for the subheader

class and the footer

class. What if you want to create a style class that could be applied to any ele- ment, rather than just headings or some other particular tag? You can asso- www.it-ebooks.info ptg 60 HOUR 4: Understanding Cascading Style Sheets ciate a style class with the
tag, as in Listing 4.2, which is used to enclose any text in a block that is somewhat similar to a paragraph of text; the
tag is another useful container element. You can essentially create your own custom HTML tag by using the div selector followed by a period (.) followed by any style class name you make up and any style specifications you choose. That tag can control any number of font, spacing, and margin settings all at once. Wherever you want to apply your custom tag in a page, use a
tag with the class attribute followed by the class name you created. For example, the style sheet in Listing 4.1 includes the following style class specification: div.footer { font-size: 9pt; font-style: italic; line-height: 12pt; text-align: center; padding-top: 30pt; } This style class is applied in Listing 4.2 with the following tag:
Everything between that tag and the closing
tag in Listing 4.2 appears in 9-point, centered, italic text with 12-point vertical line spacing and 30 points of padding at the top of the element. What makes style classes so valuable is how they isolate style code from web pages, effectively allowing you to focus your HTML code on the actu- al content in a page, not how it is going to appear on the screen. Then you can focus on how the content is rendered to the screen by fine-tuning the style sheet. You might be surprised by how a relatively small amount of code in a style sheet can have significant effects across an entire web site. This makes your pages much easier to maintain and manipulate. TIP You might have noticed a change in the coding style when multiple properties are included in a style rule. For style rules with a single style, you’ll com- monly see the property placed on the same line as the rule, like this: div.footer { font-size: 9pt; } However, when a style rule con- tains multiple style properties, it’s much easier to read and understand the code if you list the properties one-per-line, like this: div.footer { font-size:9pt; font-style: italic; line-height:12pt; text-align: center; padding-top: 30pt; } www.it-ebooks.info ptg Using Style IDs 61 Using Style IDs When you create custom style classes, you can use those classes as many times as you would like—they are not unique. However, there will be some instances when you want to have precise control over unique ele- ments for layout or formatting purposes (or both). In such instances, look to IDs instead of classes. A style ID is a custom set of formatting specifications that can be applied only to one element in a web page. You can use IDs across a set of pages but only once per time within each page. For example, suppose you have a title within the body of all your pages. Each page has only one title, but all of the pages themselves include one instance of that title. Following is an example of a selector with an ID indi- cated, plus a property and a value: p#title {font: 24pt Verdana, Geneva, Arial, sans-serif} Notice that this selector includes a hash mark, or pound sign (#), after p, followed by a descriptive ID name. When referencing a style ID in HTML code, simply specify the ID name in the id attribute of an element, like so:

Some Title Goes Here

Everything between the opening and closing

tags will appear in 24- point Verdana text—but only once on any given page. You will often see style IDs used to define specific parts of a page for layout purposes, such as a header area, footer area, main body area, and so on. These types of areas in a page will appear only once per page, so using an ID rather than a class is the appropriate choice. Add Classes to Your Style Sheet Using the style sheet you created earlier in this hour, add some style class- es to your style sheet. To see the fruits of your labor, apply those classes to the HTML page you created as well. Use classes with your

and

tags to get the feel for things. TRY IT YOURSELF ▼ www.it-ebooks.info ptg 62 HOUR 4: Understanding Cascading Style Sheets Internal Style Sheets and Inline Styles In some situations, you might want to specify styles that will be used in only one web page, in which case you can enclose a style sheet between tags and include it directly in an HTML document. Style sheets used in this manner must appear in the of an HTML document. No tag is needed and you cannot refer to that style sheet from any other page (unless you copy it into the beginning of that document, too). This kind of style sheet is known as an internal style sheet, as you learned earlier in the hour. Listing 4.3 shows an example of how you might specify an internal style sheet. Listing 4.3 A Web Page with an Internal Style Sheet Some Page ...

Copyright 2009 Acme Products, Inc.
In the listing code, the div.footer style class is specified in an internal style sheet that appears in the head of the page. The style class is now available for use within the body of this page. And, in fact, it is used in the body of the page to style the copyright notice. www.it-ebooks.info ptg Internal Style Sheets and Inline Styles 63 Internal style sheets are handy if you want to create a style rule that is used multiple times within a single page. However, in some instances you might need to apply a unique style to one particular element. This calls for an inline style rule, which allows you to specify a style for only a small part of a page, such as an individual element. For example, you can create and apply a style rule within a

,

, or tag via the style attrib- ute. This type of style is known as an inline style because it is specified right there in the middle of the HTML code. Here’s how a sample style attribute might look:

This text is green, but this text is red. Back to green again, but...

...now the green is over, and we’re back to the default color for this page.

This code makes use of the tag to show how to apply the color style property in an inline style rule. In fact, both the

tag and the tag in this example use the color property as an inline style. What’s important to understand is that the color:red style property overrides the color:green style property for the text appearing between the and tags. Then in the second paragraph, neither of the color styles applies because it is a com- pletely new paragraph that adheres to the default color of the entire page. NOTE and are dummy tags that do nothing in and of themselves except specify a range of content to apply any style attributes that you add. The only difference between

and is that
is a block element and there- fore forces a line break, where- as doesn’t. Therefore, you should use to modi- fy the style of any portion of text that is to appear in the middle of a sentence or para- graph without any line break. Validate Your Style Sheets Just as it is important to vali- date your HTML or XHTML markup, it is important to vali- date your style sheet. A specific validation tool for CSS can be found at http://jigsaw.w3.org/css- validator/. Just like the vali- dation tool discussed in Hour 3, you can point the tool to a web address, upload a file, or paste content into the form field provided. The ultimate goal is a result such as that shown in Figure 4.3: valid! FIGURE 4.3 The W3C CSS Validator shows there are no errors in the style sheet contents of Listing 4.1. www.it-ebooks.info ptg 64 HOUR 4: Understanding Cascading Style Sheets Summary In this hour, you learned that a style sheet can control the appearance of many HTML pages at once. It can also give you extremely precise control over the typography, spacing, and positioning of HTML elements. You also learned that by adding a style attribute to almost any HTML tag, you can control the style of any part of an HTML page without referring to a sepa- rate style sheet document. You learned about three main approaches to including style sheets in your web site: a separate style sheet file with the extension .css that is linked to in the of your documents, a collection of style rules placed in the head of the document within the Allows an internal style sheet to be included within a document. Used between and . Attribute type=”contenttype” The Internet content type. (Always “text/css” for a CSS style sheet.) Links to an external style sheet (or other document type). Used in the section of the document. Attribute href=”url” The address of the style sheet. type=”contenttype” The Internet content type. (Always “text/css” for a CSS style sheet.) rel=”stylesheet” The link type. (Always “stylesheet” for style sheets.) Does nothing but provide a place to put style or other attributes. (Similar to
but does not cause a line break.) Attribute style=”style” Includes inline style specifications. (Can be used in ,
, , and most other HTML tags.) www.it-ebooks.info ptg Q&A 65 Q&A Q Say I link a style sheet to my page that says all text should be blue, but there’s a tag in the page some- where. Will that text display as blue or will it display as red? A Red. Local inline styles always take precedence over external style sheets. Any style specifications you put between tags at the top of a page will also take precedence over external style sheets (but not over inline styles later in the same page). This is the cascading effect of style sheets that I mentioned earlier in the hour. So you can think of cascading style effects as starting with an external style sheet, which is overridden by an internal style sheet, which is overridden by inline styles. Q Can I link more than one style sheet to a single page? A Sure. For example, you might have a sheet for formatting (text, fonts, colors, and so on) and another one for layout (margins, padding, align- ment, and so on)—just include a for both. Technically speak- ing, the CSS standard requires web browsers to give the user the option to choose between style sheets when multiple sheets are pre- sented via multiple tags. However, in practice, all major web browsers simply include every style sheet. The preferred technique for linking in multiple style sheets involves using the special @import com- mand. Following is an example of importing multiple style sheets with @import: @import url(styles1.css); @import url(styles2.css); Similar to the tag, the @import command must be placed in the head of a web page. You learn more about this handy little com- mand in Hour 20, “Creating Print-Friendly Designs,” when you learn how to create a style sheet specifically for printing web pages. www.it-ebooks.info ptg 66 HOUR 4: Understanding Cascading Style Sheets Workshop The workshop contains quiz questions and activities to help you solidify your understanding of the material covered. Try to answer all questions before looking at the “Answers” section that follows. Quiz 1. What code would you use to create a style sheet to specify 30-point blue Arial headings and all other text in double-spaced, 10-point blue Times Roman (or the default browser font)? 2. If you saved the style sheet you made for Question 1 as corporate.css, how would you apply it to a web page named intro.html? 3. How many different ways are there to ensure style rules can be applied to your content? Answers 1. Your style sheet would include: h1 { font: 30pt blue Arial; } body { font: 10pt blue; } 2. Put the following tag between the and tags of the intro.html document: 3. Three: externally, internally, and inline. Exercises . Develop a standard style sheet for your web site and link it into all your pages. (Use internal style sheets and/or inline styles for pages that need to deviate from it.) If you work for a corporation, chances are it has already developed font and style specifications for printed materials. Get a copy of those specifications and follow them for company web pages, too. . Be sure to explore the official style sheet specs at http://www.w3.org/Style/CSS/ and try some of the more esoteric style properties not covered in this hour. www.it-ebooks.info ptg In the early days of the Web, text was displayed in only one font and in one size. However, a combination of HTML and CSS now makes it possi- ble to control the appearance of text and how it is aligned and displayed on a web page. This hour will show you the basics of text alignment and will guide you through some advanced text tips and tricks, such as the use of lists. Because lists are so common, HTML provides tags that automati- cally indent text and add numbers, bullets, or other symbols in front of each listed item. You’ll learn how to format different types of lists, which are part of the many ways to display content in your web site. HOUR 5 Working with Text Blocks and Lists WHAT YOU’LL LEARN IN THIS HOUR: . How to align text on a page . How to use the three types of HTML lists . How to place lists within lists Preparing Sample Text You can make the most of learning how to style text throughout this hour if you have some sample text that could be indented, centered, or other- wise manipulated: . Any type of outline, bullet points from a presentation, numbered steps, glossary, or list of textual information from a database will serve as good material to work with. . Any text will do, but try to find (or type) some text you want to put onto a web page. The text from a company brochure or from your résumé might be a good choice. . If the text you’ll be using is from a word processing or database pro- gram, be sure to save it to a new file in plain-text or ASCII format. You can then add the appropriate HTML tags and style attributes to format it as you go through this lesson. . Before you use the code introduced in this chapter to format the body text, add the set of skeleton HTML tags you’ve used in previ- ous hours (the , , , and <body> tags). TRY IT YOURSELF ▼ www.it-ebooks.info ptg 68 HOUR 5: Working with Text Blocks and Lists Aligning Text on a Page It’s easy to take for granted the fact that most paragraphs are automatically aligned to the left when you’re reading information on the Web. However, there certainly are situations in which you might choose to align content to the right or even the center of a page. HTML gives you the option to align a single HTML block-level element, such as text contained within a <p></p> or <div></div> tag pair. Before we get into the details of aligning block ele- ments, however, let’s briefly note how attributes work. Using Attributes Attributes are used to provide additional information related to an HTML tag. Attributes are special code words used inside an HTML tag to control exactly what the tag does. They are very important in even the simplest bit of web content, so it’s important that you are comfortable using them. Attributes invoke the use of styles, classes, or IDs that are applied to par- ticular tags. If you define a particular class or ID in a style sheet—as you learned in Hour 4—then you can invoke that class or ID using class=”someclass” or id=”someid” within the tag itself. When the browser renders the content for display, it will look to the style sheet to determine exactly how the content will appear according to the associated style defi- nitions. Similarly, you can use the style attribute to include style informa- tion for a particular element without connecting the element to an actual style sheet. For example, when you begin a paragraph with the <p> tag, you can specify whether the text in that particular paragraph should be aligned to the left margin, the right margin, or to the center of the page by setting the style attribute. If you want to associate that particular para- graph with an existing class or ID, you set the class or id attribute. In the following example, each paragraph could be left-aligned: <p style=”text-align: left;”>Text goes here.</p> <p class=”leftAlignStyle”>Text goes here.</p> <p id=”firstLeftAlign”>Text goes here.</p> In the first paragraph, the style appears directly in the style attribute. In the second paragraph, the paragraph will be left-aligned if the style sheet entry for the leftAlignStyle class includes the text-align statement. Similarly, the third paragraph will be left-aligned if the style sheet entry for the firstLeftAlign class includes the text-align statement. www.it-ebooks.info ptg Aligning Text on a Page 69 In the previous example and in examples shown in previous hours, you might have noticed the use of lowercase for tags, attributes, and styles. The exacting XHTML standard requires tags and attributes to be lowercase; the XHTML standard also requires quotation marks around attribute val- ues. For example, the following code will be rendered by most popular web browsers: <P STYLE=TEXT-ALIGN:CENTER> However, this code does not conform to XHTML standards because the tag is uppercased, the style attribute and its value (text-align:center) is uppercased, and the value isn’t in quotation marks. If you want to stay compatible with the latest standards and software, you should always use the following instead: <p style=”text-align:center”> Aligning Block-Level Elements To align a block-level element such as <p> to the right margin without cre- ating a separate class or ID in a style sheet, simply place style=”text- align:right” inside the <p> tag at the beginning of the paragraph. Similarly, to center the element, use <p style=”text-align:center”>. To align a paragraph to the left, use <p style=”text-align:left”>. The text-align part of the style attribute is referred to as a style rule, which means that it is setting a particular style aspect of an HTML element. There are many style rules you can use to carefully control the formatting of web content. The text-align style rule is not reserved for just the <p> tag. In fact, you can use the text-align style rule with any block-level element, which includes <h1>, <h2>, the other heading tags, and the <div> tag, among others. The <div> tag is especially handy because it can encompass other block-level elements and thus allow you to control the alignment of large portions of your web content all at once. The div in the <div> tag is for division. Listing 5.1 demonstrates the style attribute and text-align style rule with both the <p> and the <div> tags. The results are shown in Figure 5.1. You’ll learn many more advanced uses of the <div> tag in Part III. NOTE Every attribute and style rule in HTML has a default value that is assumed when you don’t set the attribute yourself. In the case of the text-align style rule of the <p> tag, the default value is left, so using the bare- bones <p> tag has the same effect as using <p style=”text-align:left”>. Learning the default values for common style rules is an impor- tant part of becoming a good web page developer. www.it-ebooks.info ptg 70 HOUR 5: Working with Text Blocks and Lists Listing 5.1 The text-align Style Rule Used with the style Attribute <?xml version=”1.0” encoding=”UTF-8”?> <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN” “http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”> <html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en”> <head> <title>Bohemia

Bohemia

by Dorothy Parker

Authors and actors and artists and such
Never know nothing, and never know much.
Sculptors and singers and those of their kidney
Tell their affairs from Seattle to Sydney.

Playwrights and poets and such horses’ necks
Start off from anywhere, end up at sex.
Diarists, critics, and similar roe
Never say nothing, and never say no.

People Who Do Things exceed my endurance;
God, for a man that solicits insurance!

FIGURE 5.1 The results of using the text alignment in Listing 5.1. www.it-ebooks.info ptg The Three Types of HTML Lists 71 The use of
ensures that the content area, including the two headings, are centered. However, the text alignment of the individual paragraphs within the
override the setting and ensure that the text of the first paragraph is left-aligned, the second paragraph is centered, and the third paragraph is right-aligned. The Three Types of HTML Lists For clarity, it’s often useful to present information on a web page as a list of items. There are three basic types of HTML lists. All three are shown in Figure 5.2, and Listing 5.2 reveals the HTML used to construct them: . Ordered list—An indented list that has numbers or letters before each list item. The ordered list begins with the
    tag and ends with a closing
tag. List items are enclosed in the
  • tag pair and line breaks appear automatically at each opening
  • tag. The entire list is indented. . Unordered list—An indented list that has a bullet or other symbol before each list item. The unordered list begins with the
      tag and closes with
    . Like the ordered list, its list items are enclosed in the
  • tag pair. A line break and symbol appear at each open- ing
  • tag and the entire list is indented. . Definition list—A list of terms and their meanings. This type of list, which has no special number, letter, or symbol before each item, begins with
    and ends with
    . The
    tag pair encloses each term and the
    tag pair encloses each definition. Line breaks and indentations appear automatically. Listing 5.2 Unordered Lists, Ordered Lists, and Definition Lists How to Be Proper

    How to Be Proper

    Basic Etiquette for a Gentlemen Greeting a Lady Aquaintance

    • Wait for her acknowledging bow before tipping your hat.
    • Use the hand farthest from her to raise the hat.
    • www.it-ebooks.info ptg 72 HOUR 5: Working with Text Blocks and Lists Listing 5.2 Unordered Lists, Ordered Lists, and Definition Lists
    • Walk with her if she expresses a wish to converse; Never make a lady stand talking in the street.
    • When walking, the lady must always have the wall.

    Recourse for a Lady Toward Unpleasant Men Who Persist in Bowing

    1. A simple stare of iciness should suffice in most instances.
    2. A cold bow discourages familiarity without offering insult.
    3. As a last resort: “Sir, I have not the honour of your aquaintance.”

    Proper Address of Royalty

    Your Majesty
    To the king or queen.
    Your Royal Highness
    To the monarch’s spouse, children, and siblings.
    Your Highness
    To nephews, nieces, and cousins of the sovereign.
    FIGURE 5.2 The three basic types of HTML lists. NOTE Remember that different web browsers can display web con- tent quite differently. The HTML standard doesn’t specify exactly how web browsers should for- mat lists, so users with older web browsers might not see exactly the same indentation you see. You can use CSS to gain precise control over list items, which you will learn about later in this hour. www.it-ebooks.info ptg Placing Lists Within Lists 73 Placing Lists Within Lists Although definition lists are officially supposed to be used for defining terms, many web page authors use them anywhere they’d like to see some indentation. In practice, you can indent any text simply by putting
    at the beginning of it and
    at the end and skipping over the
    tag pair. However, a better approach to indenting text is to use the
    tag pair, which indents content without the presumption of a definition and allows for much more clear styling. With one set of attributes, you can set the width, height, background color, bor- der type and color of your element area, and other visual effects. Because of the level of control over the display of your items that you have when using CSS, there is no need to use nested lists to achieve the visual appearance of indentation. Reserve your use of nested lists for when the content warrants it. In other words, use nested lists to show a hierarchy of information, such as in Listing 5.3. Ordered and unordered lists can be nested inside one another, down to as many levels as you want. In Listing 5.3, a complex indented outline is con- structed from several unordered lists. You’ll notice in Figure 5.3 that Firefox automatically uses a different type of bullet for each of the first three levels of indentation, making the list very easy to read. This is com- mon in modern browsers. Listing 5.3 Using Lists to Build Outlines Vertebrates

    Vertebrates

    • Fish
      • Barramundi
      • Kissing Gourami
      • Mummichog
    • Amphibians NOTE Nesting refers to a tag that appears entirely within another tag. Nested tags are also referred to as child tags of the (parent) tag that contains them. It is a common (but not required) coding practice to indent nested tags so that you can easily see their relationship to the parent tag. www.it-ebooks.info ptg 74 HOUR 5: Working with Text Blocks and Lists Listing 5.3 Using Lists to Build Outlines
      • Anura
        • Goliath Frog
        • Poison Dart Frog
        • Purple Frog
      • Caudata
        • Hellbender
        • Mudpuppy
    • Reptiles
      • Nile Crocodile
      • King Cobra
      • Common Snapping Turtle
    FIGURE 5.3 In Firefox, multilevel unordered lists are neatly indented and bulleted for improved readability. www.it-ebooks.info ptg Placing Lists Within Lists 75 As shown in Figure 5.3, a web browser will normally use a solid disc for the first-level bullet, a hollow circle for the second-level bullet, and a solid square for all deeper levels. However, you can explicitly choose which type of bullet to use for any level by using
      ,
        , or
          instead of
            . You can even change the bullet for any single point within an unordered list by using the list-style-type style rule in the
          • tag. For example, the following codes displays a hollow circle in front of the words extra and super and a solid square in front of the word special:
            • extra
            • super
            • special
            The list-style-type style rule also works with ordered lists, but instead of choosing a type of bullet, you choose the type of numbers or letters to place in front of each item. Listing 5.4 shows how to use Roman numerals (list-style-type:upper-roman), capital letters (list-style-type:upper-alpha), lowercase letters (list-style-type:lower-alpha), and ordinary numbers in a multilevel list. Figure 5.4 shows the resulting outline, which is nicely for- matted. Although Listing 5.4 uses the list-style-type style rule only with the
              tag, you can also use it for specific
            1. tags within a list (though it’s hard to imagine a situation in which you would want to do this). You can also explicitly specify ordinary numbering with list-style-type:decimal and you can make lowercase Roman numerals with list-style-type:lower- roman. Listing 5.4 Using the list-style-type Style Rule with the style Attribute in Multitiered Lists Advice from the Golf Guru

              How to Win at Golf

              www.it-ebooks.info ptg 76 HOUR 5: Working with Text Blocks and Lists Listing 5.4 Using the list-style-type Style Rule with the style Attribute in Multitiered Lists
              1. Training
                1. Mental prep
                  1. Watch golf on TV religiously
                  2. Get that computer game with Tiger whatsisname
                  3. Rent “personal victory” subliminal tapes
                2. Equipment
                  1. Make sure your putter has a pro autograph on it
                  2. Pick up a bargain bag of tees-n-balls at Costco
                3. Diet
                  1. Avoid junk food
                    1. No hotdogs
                  2. Drink wine and mixed drinks only, no beer
              2. Pre-game
                1. Dress
                  1. Put on shorts, even if it’s freezing
                  2. Buy a new hat if you lost last time
                2. Location and Scheduling
                  1. Select a course where your spouse or boss won’t find you
                  2. To save on fees, play where your buddy works
                3. Opponent
                  1. Look for: overconfidence, inexperience
                  2. Buy opponent as many pre-game drinks as possible
                www.it-ebooks.info ptg Placing Lists Within Lists 77 Listing 5.4 Using the list-style-type Style Rule with the style Attribute in Multitiered Lists
              3. On the Course
                1. Tee off first, then develop severe hayfever
                2. Drive cart over opponent’s ball to degrade aerodynamics
                3. Say “fore” just before ball makes contact with opponent
                4. Always replace divots when putting
                5. Water cooler holes are a good time to correct any errors in ball placement
              FIGURE 5.4 A well-formatted outline can make almost any plan look more plausible. www.it-ebooks.info ptg 78 HOUR 5: Working with Text Blocks and Lists Summary In this hour, you learned that attributes are used to specify options and special behavior of many HTML tags and you also learned to use the style attribute with CSS style rules to align text. You also learned how to create and combine three basic types of HTML lists: ordered lists, unordered lists, and definition lists. Lists can be placed within other lists to create outlines and other complex arrangements of text. Table 5.1 summarizes the tags and attributes discussed in this hour. Don’t feel like you have to memorize all these tags, by the way! That’s why you have this book: You can look up the tags when you need them. Remember that all the HTML tags are listed in Appendix B, “Complete XHTML 1.1 and CSS 2 Quick Reference.” Table 5.1 HTML Tags and Attributes Covered in Hour 5 Tag/Attribute Function
              A region of text to be formatted.
              A definition list.
              A definition term, as part of a definition list.
              The corresponding definition to a definition term, as part of a definition list.
              An ordered (numbered) list.
              An unordered (bulleted) list.
            2. A list item for use with
                or
                  . Attributes style=”text-align:alignment” Align text to center, left, or right. (Can also be used with

                  ,

                  ,

                  ,

                  , and so on.) style=”list-style-type:numtype” The type of numerals used to label the list. Possible values are decimal, lower-roman, upper-roman, lower- alpha, upper-alpha, and none. style=”list-style-type:bullettype” The bullet dingbat used to mark list items. Possible values are disc, cir- cle, square, and none. style=”list-style-type:type” The type of bullet or number used to label this item. Possible values are disc, circle, square, decimal, lower- roman, upper-roman, lower-alpha, upper-alpha, and none. www.it-ebooks.info ptg Workshop 79 Q&A Q I’ve seen web pages that use three-dimensional little balls or other special graphics for bullets. How do they do that? A That trick is a little bit beyond what this hour covers. You’ll learn how to do it yourself in Hour 11. Q How do I “full justify” text so that both the left and right margins are flush? A You can use text-align:justify in your style declaration. Workshop The workshop contains quiz questions and activities to help you solidify your understanding of the material covered. Try to answer all questions before looking at the “Answers” section that follows. Quiz 1. How would you center everything on an entire page? 2. How would you indent a single word and put a square bullet in front of it? 3. What would you use to create a definition list to show that the word “glunch” means “a look of disdain, anger, or displeasure” and that the word “glumpy” means “sullen, morose, or sulky”? Answers 1. If you thought about putting a
                  immediately after the tag at the top of the page, and
                  just before the tag at the end of the page, then you’re correct. However, the text-align style is also supported directly in the tag, which means you can forego the
                  tag and place the style=”text-align:center” style directly in the tag. Presto, the entire page is centered! 2. You would use:
                  • supercalifragilisticexpealidocious
                  www.it-ebooks.info ptg 80 HOUR 5: Working with Text Blocks and Lists (Putting the style=”list-style-type:square” in the
                • tag would give the same result because there’s only one item in this list.) 3. You would use:
                  glunch
                  a look of disdain, anger, or displeasure
                  glumpy
                  sullen, morose, or sulky
                  Exercises . Use the text alignment style attributes to place blocks of text in vari- ous places on your web page. Try nesting your paragraphs and divi- sions (

                  and

                  ) to get a feel for how styles do or do not cascade through the content hierarchy. . Try producing an ordered list outlining the information you’d like to put on your web pages. This will give you practice formatting HTML lists and also give you a head start on thinking about the issues cov- ered in later hours of this book. www.it-ebooks.info ptg In the previous hour, you learned the basics of creating blocks of text and putting that text into list format. In this hour, you’ll take a closer look at the bits of text themselves, and learn how to change the visual display of the font—it’s font family, size, and weight, for example. You’ll learn to incorporate boldface, italics, superscripts, subscripts, and strikethrough text into your pages. You will also learn how to change typefaces and font sizes. NOTE When viewing other designers’ web content, you might notice methods of mark- ing up text that are different than those taught in this book. The “old way” of formatting text includes the use of the tag pair to indicate when a word should be bolded, the tag pair to indicate when a word should be in ital- ics, and the use of a tag pair to specify font family, size, and other attributes. However, there is no reason to learn it because it is being phased out of HTML, and CSS is considerably more powerful. HOUR 6 Working with Fonts WHAT YOU’LL LEARN IN THIS HOUR: . How to use boldface, ital- ics, and special text for- matting . How to tweak the font . How to use special charac- ters More Work with Sample Text Just like you created a sample file to work with in the previous hour, create one for this hour so you can follow along and make the most of learning how to style text throughout this hour. Since the information in this hour has to do with font-level styles, it does- n’t really matter what type of text you use. There are so many different stylistic possibilities to try that they would never appear all on the same web page anyway (unless you wanted to drive your visitors batty). Take this opportunity to get a feel for how text-level changes can affect the appearance of your content. TRY IT YOURSELF ▼ www.it-ebooks.info ptg 82 HOUR 6: Working with Fonts Boldface, Italics, and Special Text Formatting Way back in the age of the typewriter, we were content with plain-text and an occasional underline for emphasis. Today, boldface and italic text have become de rigueur in all paper communication. Naturally, you can add bold and italic text to your web content as well. There are several tags and style rules that make text formatting possible. The “old school” approach to adding bold and italic formatting to text involves the and tag pairs. For boldface text, put the tag at the beginning of the text and at the end. Similarly, you can make any text italic by enclosing it between and tags. Although this approach still works fine in browsers and is supported by XHTML, it isn’t as flexible or powerful as the CSS style rules for text formatting. Although you’ll learn much more about CSS style rules in Part III, it’s worth a little foreshadowing just so you understand the text formatting options. The font-weight style rule allows you to set the weight, or bold- ness, of a font using a style rule. Standard settings for font-weight include normal, bold, bolder, and lighter (with normal being the default). Italic text is controlled via the font-style rule, which can be set to normal, italic, or oblique. Style rules can be specified together if you want to apply more than one, as the following example demonstrates:

                  This paragraph is bold and italic!

                  In this example, both style rules are specified in the style attribute of the

                  tag. The key to using multiple style rules is that they must be separated by a semicolon (;). You aren’t limited to using font styles in paragraphs, however. The follow- ing code shows how to italicize text in a bulleted list:

                  • Important Stuff
                  • Critical Information
                  • Highly Sensitive Material
                  • Nothing All That Useful
                  You can also use the font-weight style rule within headings, but a heavier font usually doesn’t have an effect on headings because they are already bold by default. NOTE An alternative to style rules when it comes to bold and italic text involves the and tag pairs. The tag does the same thing as the tag in most browsers, whereas the tag acts just like the tag by for- matting text as italics. The and tags are considered by some to be an improvement over and because they imply only that the text should receive special emphasis, rather than dictating exactly how that effect should be achieved. In other words, a browser doesn’t necessarily have to interpret as meaning bold or as mean- ing italic. This makes and more fitting in XHTML because they add meaning to text, along with affecting how the text should be displayed. All four tags remain part of HTML 5, although their use becomes slightly more nuanced. www.it-ebooks.info ptg Boldface, Italics, and Special Text Formatting 83 Although using CSS allows you to apply richer formatting, there are a few other HTML tags that are good for adding special formatting to text when you don’t necessarily need to be as specific as CSS allows you to be. Following are some of these tags. Listing 6.1 and Figure 6.1 demonstrate each tag in action. . —Small text . —Big text; not present in HTML 5 because text size is bet- ter controlled by CSS. . —Superscript text . —Subscript text . or —Emphasized (italic) text . or —Strong (boldface) text . —Monospaced text (typewriter font) ; not present in HTML 5 because font appearance is better controlled by CSS. .
                   —Monospaced text, preserving spaces and line breaks  Listing 6.1 Special Formatting Tags          The Miracle Product      

                  New SuperStrength H2O plus will knock out any stain, big or small.
                  Look for new SuperStrength H2O plus in a stream near you.

                  NUTRITION INFORMATION (void where prohibited)

                    Calories   Grams   USRDA  /Serving   of Fat  Moisture  Regular           3          4        100%  Unleaded          3          2        100%   WARNING  There used to be a  tag for  creating underlined text, but  there are a couple of reasons  not to use it now. First off,  users expect underlined text to  be a link, so they might get con-  fused if you underline text that  isn’t a link. Secondly, the   tag is deprecated, which means  that it has been phased out of  the HTML/XHTML language, as  has the  tag.  Both  tags are still supported in web  browsers and likely will be for  quite a while, but using CSS is  the preferred approach to creat-  ing underlined and  strikethrough text. In HTML 5,  deleted text can be surrounded  by the  tag  pair, which will render as text  with a strikethrough.   www.it-ebooks.info  ptg  84 HOUR 6: Working with Fonts  Listing 6.1 Special Formatting Tags  Organic           2          3         99%  Sugar Free        0          1        110%  
                  The tag usually changes the typeface to Courier New, a monospaced font. (Monospaced means that all the letters and spaces are the same width.) However, web browsers let users change the monospaced font to the typeface of their choice (look on the Options menu of your browser). The monospaced font might not even be monospaced for some users, though the vast majority of users stick with the standard fonts that their browsers show by default. FIGURE 6.1 Here’s what the character format- ting from Listing 6.1 looks like. The
                   tag causes text to appear in the monospaced font, but it also does  something else unique and useful. As you learned in Hour 3, multiple  spaces and line breaks are normally ignored in HTML files, but 
                   caus-  es exact spacing and line breaks to be preserved. For example, without  
                  , the text at the end of Figure 6.1 would look like the following:  calories grams usrda /serving of fat moisture regular  3 4 100% unleaded 3 2 100% organic 2 3 99% sugar free 0 1 110%  Even if you added 
                  tags at the end of every line, the columns would- n’t line up properly. However, when you put
                   at the beginning and  
                  at the end, the columns line up properly because the exact spaces www.it-ebooks.info ptg Tweaking the Font 85 are kept—no
                  tags are needed. The
                   tag gives you a quick and  easy way to preserve the alignment of any monospaced text files you  might want to transfer to a web page with minimum effort.  CSS provides you with more robust methods for lining up text (and doing  anything with text, actually),  and you’ll learn more about them through-  out Part III.   Tweaking the Font  The , , and  tags give you some rudimentary control over  the size and appearance of the text on your pages. However, there might  be times when you’d just like a bit more control over the size and appear-  ance of your text. Before I get into the appropriate way to tinker with the  font in XHTML code, let’s briefly take a look at how things were done  prior to CSS because you might still find examples of this method when  you look at the source code for other web sites. Remember, just because  these older methods are in use doesn’t mean you should follow suit.  Before style sheets entered the picture, the now phased-out  tag was  used to control the fonts in web page text. For example, the following  HTML will change the size and color of some text on a page:  this text will be big and purple.  As you can see, the size and color attributes of the  tag made it pos-  sible to alter the font of the text without too much effort. Although this  approach worked fine, it was replaced with a far superior approach to font  formatting, thanks to CSS style rules. Following are a few of the main style  rules used to control fonts:  . font-family—Sets the family (typeface) of the font.  . font-size—Sets the size of the font.  . color—Sets the color of the font.  The font-family style rule allows you to set the typeface used to display  text. You can and usually should specify more than one value for this style  (separated by commas) so that if the first font isn’t available on a user’s  system, the browser can try an alternative. You’ve already seen this in pre-  vious lessons. Providing alternative font families is important because each  user potentially has a different set of fonts installed, at least beyond a core  NOTE  You’ll learn more about control-  ling the color of the text on your  pages in Hour 9, “Working with  Colors.” That hour also shows  you how to create your own cus-  tom colors and how to control  the color of text links.  www.it-ebooks.info  ptg  86 HOUR 6: Working with Fonts  set of common basic fonts (Arial, Times New Roman, and so forth). By pro-  viding a list of alternative fonts, you have a better chance of your pages  gracefully falling back on a known font when your ideal font isn’t found.  Following is an example of the font-family style used to set the typeface  for a paragraph of text:  

                  There are several interesting things about this example. First, arial is speci- fied as the primary font. Capitalization does not affect the font family, so arial is no different from Arial or ARIAL. Another interesting thing about this code is how single quotes are used around the times roman font name because it has a space in it. However, since ‘times roman’ appears after the generic specification of sans-serif, it is unlikely that ‘times roman’ would be used. Because sans-serif is in the second position, it says to the browser “if Arial is not on this machine, use the default sans-serif font.” The font-size and color style rules are also commonly used to control the size and color of fonts. The font-size style can be set to a predefined size (such as small, medium, or large) or you can set it to a specific point size (such as 12pt or 14pt). The color style can be set to a predefined color (such as white, black, blue, red, or green) or you can set it to a specific hexa- decimal color (such as #FFB499.) Following is the previous paragraph exam- ple with the font size and color specified:

                  The example web content in Listing 6.2 and shown in Figure 6.2 uses some font style rules to create the beginning of a basic online résumé. Listing 6.2 Using Font Style Rules to Create a Basic Résumé Résumé for Jane Doe

                  Jane Doe

                  1234 Main Street, Sometown, CA 93829
                  tel: 555-555-1212, e-mail: jane@doe.com

                  Summary of Qualifications

                  • Highly skilled and dedicated professional offering a solid background in whatever it is you need.
                  • Provide comprehensive direction for whatever it is that will get me a job.
                  • Computer proficient in a wide range of industry-related computer programs and equipment. Any industry.

                  Professional Experience

                  Operations Manager, Super Awesome Company, Some City, CA [Sept 2002 – present]

                  • Direct all departmental operations
                  • Coordinate work with internal and external resources
                  • Generally in charge of everything

                  Project Manager, Less Awesome Company, Some City, CA [May 2000 - Sept www.it-ebooks.info ptg 88 HOUR 6: Working with Fonts Listing 6.2 Using Font Style Rules to Create a Basic Résumé 2002]

                  • Direct all departmental operations
                  • Coordinate work with internal and external resources
                  • Generally in charge of everything

                  Education

                  • MBA, MyState University, May 2002
                  • B.A, Business Administration, MyState University, May 2000

                  References

                  • Available upon request.
                  FIGURE 6.2 Here’s what the code used in Listing 6.2 looks like. Using CSS, which organizes sets of styles into classes—as you learned in Hour 4—you can see how text formatting is applied to different areas of this content. If you look closely at the definition of the div.indented class, you will see the use of the margin-left style. This style, which you will learn more about in Part II, applies a certain amount of space (25 pixels, in this example) to the left of the element. That space accounts for the inden- tation shown in Figure 6.2. www.it-ebooks.info ptg Working with Special Characters 89 Working with Special Characters Most fonts now include special characters for European languages, such as the accented é in Café. There are also a few mathematical symbols and spe- cial punctuation marks, such as the circular . bullet. You can insert these special characters at any point in an HTML document using the appropriate codes shown in Table 6.1. You’ll find an even more extensive list of codes for multiple character sets at http://www. webstandards.org/learn/reference/named_entities.html. For example, the word café could be written using either of the following methods: café café Table 6.1 Commonly Used English Language Special Characters Character Numeric Code Code Name Description “" " Quotation mark && & Ampersand < < < Less than > > > Greater than ¢ ¢ ¢ Cent sign £ £ £ Pound sterling | ¦ ¦ or &brkbar; Broken vertical bar § § § Section sign © © © Copyright ® ® ® Registered trademark ° ° ° Degree sign +– ± ± Plus or minus 2 ² ² Superscript two 3 ³ ³ Superscript three ·· · Middle dot 1 ¹ ¹ Superscript one 1⁄4 ¼ ¼ Fraction one-fourth 1⁄2 ½ ½ Fraction one-half 3⁄4 ¾ ¾ Fraction three-fourths ÆÆ Æ Capital AE ligature www.it-ebooks.info ptg 90 HOUR 6: Working with Fonts Table 6.1 Commonly Used English Language Special Characters Character Numeric Code Code Name Description æ æ æ Small ae ligature ÉÉ É Accented capital E é é é Accented small e × × × Multiplication sign ÷ ÷ ÷ Division sign Although you can specify character entities by number, each symbol also has a mnemonic name that is often easier to remember. HTML/XHTML uses a special code known as a character entity to represent special characters such as © and ®. Character entities are always specified starting with & and ending with ;. Table 6.1 lists the most commonly used character entities, although HTML supports many more. Table 6.1 includes codes for the angle brackets, quotation, and ampersand. You must use those codes if you want these symbols to appear on your pages; otherwise, the web browser interprets them as HTML commands. In Listing 6.3 and Figure 6.3, several of the symbols from Table 6.1 are shown in use. Listing 6.3 Special Character Codes Punctuation Lines

                  Q: What should you do when a British banker picks a fight with you?
                  A: £ some ¢¢ into him.


                  Q: What do you call it when a judge takes part of a law off the books?
                  A: § violence.
                  Q: What did the football coach get from the locker room vending machine in the middle of the game?
                  A: A ¼ back at ½ time. TIP Looking for the copyright © and registered trademark ®sym- bols? Those codes are © and ®, respectively. To create an unregistered trade- mark ™ symbol, use ™. www.it-ebooks.info ptg Working with Special Characters 91 Listing 6.3 Special Character Codes
                  Q: How hot did it get when the police detective interrogated the mathematician?
                  A: x³°
                  Q: What does a punctilious plagiarist do?
                  A: ©

                  FIGURE 6.3 This is how the HTML page in Listing 6.3 looks in most web browsers. www.it-ebooks.info ptg 92 HOUR 6: Working with Fonts Summary In this hour you learned how to make text appear as boldface or italic and how to code superscripts, subscripts, special symbols, and accented letters. You saw how to make the text line up properly in preformatted passages of monospaced text and how to control the size, color, and typeface of any section of text on a web page. Table 6.2 summarizes the tags and attributes discussed in this hour. Remember that all the HTML tags are listed in Appendix B, “XHTML 1.1 and CSS 2 Quick Reference.” Table 6.2 HTML Tags and Attributes Covered in Hour 6 Tag/Attribute Function Emphasis (usually italic). Stronger emphasis (usually bold). Boldface text. Italic text. Typewriter (monospaced) font.
                  Preformatted text (exact line endings and spacing will be preserved—usually rendered in a mono- spaced font). Text is slightly larger than normal. Text is slightly smaller than normal. Subscript. Superscript. Attributes style=”font-family:typeface” The typeface (family) of the font, which is the name of a font, such as Arial. (Can also be used with

                  ,

                  ,

                  ,

                  , and so on.) style=”font-size:size” The size of the font, which can be set to small, medium, or large, as well as x-small, x-large, and so on. Can also be set to a specific point size (such as 12pt). style=”color:color” Changes the color of the text. www.it-ebooks.info ptg Q&A 93 Q&A Q How do I find out the exact name for a font I have on my computer? A On a Windows or Macintosh computer, open the Control Panel and click the Fonts folder—the fonts on your system are listed (Vista users might have to switch to “Classic View” in your Control Panel). When specifying fonts in the font-family style rule, use the exact spelling of font names. Font names are not case-sensitive, however. Q How do I put Kanji, Arabic, Chinese, and other non-European charac- ters on my pages? A First of all, users who need to read these characters on your pages must have the appropriate language fonts installed. They must also have selected that language character set and its associated font for their web browsers. You can use the Character Map program in Windows (or a similar program in other operating systems) to get the numerical codes for each character in any language font. To find Character Map, click Start, All Programs, Accessories, and then System Tools. If the character you want has a code of 214, use Ö to place it on a web page. If you cannot find the Character Map program, use your operating system’s built-in Help function to find the specific loca- tion. The best way to include a short message in an Asian language (such as We Speak Tamil—Call Us!) is to include it as a graphics image. That way every user will see it, even if they use English as their primary language for web browsing. But even to use a language font in a graph- ic, you will likely have to download a specific language pack for your operating system. Again, check your system’s Help function for specific instructions. www.it-ebooks.info ptg 94 HOUR 6: Working with Fonts Workshop The workshop contains quiz questions and activities to help you solidify your understanding of the material covered. Try to answer all questions before looking at the “Answers” section that follows. Quiz 1. How would you create a paragraph in which the first three words are bold, using styles rather than the or tags? 2. How would you represent the chemical formula for water? 3. How do you display “© 2009, Webwonks Inc.” on a web page? Answers 1. You would use:

                  First three words are bold.

                  2. You would use H2O.

                  First three words are bold.

                  3. You would use either of the following: © 2004, Webwonks Inc. © 2004, Webwonks Inc. Exercises . Apply the font-level style attributes you learned about in this chapter to various block-level elements such as

                  ,

                  ,
                    , and
                  • items. Try nesting your elements to get a feel for how styles do or do not cascade through the content hierarchy. www.it-ebooks.info ptg In this hour, you learn how to build HTML tables you can use to control the spacing, layout, and appearance of tabular data in your web content. Although you can achieve similar results using CSS, there are definitely times when a table is the best way to present information and you’ll find that tables are useful for arranging information into rows and columns. I will also explain how designers have used tables for page layout in the past, and how that isn’t always the best idea. Before we begin, just remem- ber a table is simply an orderly arrangement of content into vertical columns and horizontal rows. HOUR 7 Using Tables to Display Information WHAT YOU’LL LEARN IN THIS HOUR: . How to create simple tables . How to control the size of tables . How to align content and span rows and columns within tables Putting Your Content into Tables As you read this hour, think about how arranging text into tables could benefit your web content. The following are some specific ideas to keep in mind: . The most obvious application of tables is to organize tabular infor- mation, such as a multicolumn list of names and numbers. . Whenever you need multiple columns of text or images, tables are the answer. On your own, try adding a table modeled after the examples in this hour. The “Exercises” section at the end of this hour offers a couple of detailed suggestions along these lines as well. TRY IT YOURSELF ▼ www.it-ebooks.info ptg 96 HOUR 7: Using Tables to Display Information Creating a Simple Table A table consists of rows of information with individual cells inside. To make tables, you have to start with a tag. Of course, you end your tables with the
                    tag. If you want the table to have a border, use a border attribute to specify the width of the border in pixels. A border size of 0 or none (or leaving the border attribute out entirely) will make the bor- der invisible, which is often handy when you are using a table as a page layout tool. With the tag in place, the next thing you need is the tag. The tag creates a table row, which contains one or more cells of informa- tion before the closing . To create these individual cells, use the tags. A cell is a rectangular region that can contain any text, images, and HTML tags. Each row in a table is made up of at least one cell. Multiple cells within a row form columns in a table. There is one more basic tag involved in building tables. The
                    tag ( stands for table data). Place the table information between the and tag works exactly like a tag except indicates that the cell is part of the head- ing of the table. Most web browsers render the text in cells as centered and boldface. You can create as many cells as you want, but each row in a table should have the same number of columns as the other rows. The HTML code shown in Listing 7.1 creates a simple table using only the four table tags I’ve mentioned thus far. Figure 7.1 shows the resulting page as viewed in a web browser. Listing 7.1 Creating Tables with the , , and tag pair is still present in the first table row. In rows two through six, this additional col- umn contains an image (the tag). The second difference in Listing 7.2 is the addition of a specific width style for each , tag apply to all cells in that row. Depending on the size of your table, you can save yourself a considerable amount of time and effort by applying these attributes at the level and not in each
                    , and Tags Baseball Standings

                    Baseball Standings

                    TIP There are some style properties that allow you to take much more control over table borders. For example, you can set the border width (border-width), style (border-style), and color (border-color). These proper- ties work fine, but you have to apply them to each table ele- ment, which can be cumber- some even if you use classes for your table row or table cell elements. www.it-ebooks.info ptg Creating a Simple Table 97 Listing 7.1 Creating Tables with the
                    Team W
                    , ,
                    , and Tags L GB
                    Los Angeles Dodgers 62 38
                    San Francisco Giants 54 46 8.0
                    Colorado Rockies 54 46 8.0
                    Arizona Diamondbacks 43 58 19.5
                    San Diego Padres 39 62 23.5
                    TIP HTML ignores extra spaces between words and tags. However, you might find your HTML tables easier to read (and less prone to time-wasting errors) if you use spaces to indent
                    tags, as I did in Listing 7.1. www.it-ebooks.info ptg 98 HOUR 7: Using Tables to Display Information The table in the example contains baseball standings, which are perfect for arranging in rows and columns—if not a little plain. You’ll learn to jazz things up a bit during this hour. The headings in the table show the Team, Wins (W), Losses (L), and Games Behind (GB) in the standings. Although we did not apply any styles to the HTML in Listing 7.1, you can use any text style in a table cell. However, styles or HTML tags used in one cell don’t carry over to other cells, and tags from outside the table don’t apply within the table. For example, consider the following table:

                    hello there

                    In this example, the

                    tag is used around a table to demonstrate how tables are immune to outside tags. The word there would be neither bold- face nor italic because neither the font-weight:bold style outside the table nor the font-style:italic style from the previous cell affects it. In this example, the word hello is in italics, however. To boldface the words hello and there, change the table code to this:

                    hello there
                    tag. You can also control the size of each cell by putting width and height styles in the individual
                    tags. The width and height styles can be specified as either pixels or percentages. For exam- ple, the following code creates a table 500 pixels wide and 400 pixels high: To make the first cell of the table 20% of the total table width and the sec- ond cell 80% of the table width, type the following:
                    skinny cell fat cell
                    Notice that the table is sized to 100%, which ensures the table fills the entire width of the browser window. When you use percentages instead of fixed pixel sizes, the table will resize automatically to fit any size browser window while maintaining the aesthetic balance you’re after. In this case, the two cells within the table are automatically resized to 20% and 80% of the total table width, respectively. In Listing 7.2, the simple table from Listing 7.1 is expanded to show specif- ic control over table cell widths. NOTE There are actually width and height HTML attributes that were deprecated in the move to XHTML, and you might still see them when you look at another designer’s code. These attrib- utes still work in web browsers but you should use the width and height style properties instead, because they represent the appropriate use of XHTML. www.it-ebooks.info ptg 100 HOUR 7: Using Tables to Display Information Listing 7.2 Specifying Table Cell Widths Baseball Standings

                    Baseball Standings

                    www.it-ebooks.info ptg Controlling Table Sizes 101 Listing 7.2 Specifying Table Cell Widths
                    Team W L GB
                    ”Los Los Angeles Dodgers 62 38
                    ”San San Francisco Giants 54 46 8.0
                    ”Colorado Colorado Rockies 54 46 8.0
                    ”Arizona Arizona Diamondbacks 43 58 19.5
                    ”San San Diego Padres 39 62 23.5
                    FIGURE 7.2 The HTML code in Listing 7.2 cre- ates a table with six rows and five columns, with specific widths used for each column. There are two differences between the code from Listing 7.1 and the code used in Listing 7.2. First, an additional column has been added in Listing 7.2; this column does not have a heading, but the
                    element in the first row. The first column is defined as 35px wide, the second 175px wide, and the third, fourth, and fifth columns are each 25px wide. Also note that these widths are not repeated in the elements in subse- quent rows. Technically you must define only the widths in the first row; the remaining rows will follow suit because they are all part of the same table. However, if you used another formatting style (such as a style to change font size or color), that style must be repeated for each element that should have those display properties. www.it-ebooks.info ptg 102 HOUR 7: Using Tables to Display Information Alignment and Spanning Within Tables By default, anything you place inside a table cell is aligned to the left and vertically centered. Figures 7.1 and 7.2 show this default alignment. However, you can align the contents of table cells both horizontally and vertically with the text-align and vertical-align style properties. You can apply these alignment attributes to any
                    , or tag. Alignment attributes assigned to a
                    or tag. The HTML code in Listing 7.3 uses a combination of text alignment styles to apply a default alignment to a row, but overridden in a few individual cells. Figure 7.3 shows the result of the code in Listing 7.3. Following are some of the more commonly used vertical-align style prop- erty values: top, middle, bottom, text-top, text-bottom, and baseline (for text). These property values give you plenty of flexibility in aligning table data vertically. Listing 7.3 Alignment, Cell Spacing, Borders, and Background Colors in Tables Things to Fear

                    Things to Fear

                    www.it-ebooks.info ptg Alignment and Spanning Within Tables 103 Listing 7.3 Alignment, Cell Spacing, Borders, and Background Colors in Tables
                    Description Size Weight Speed
                    ”.38.38 Special Five-inch barrel. Twenty ounces. Six rounds in four seconds.
                    ”Rhinoceros” Rhinoceros Twelve feet, horn to tail. Up to two tons. Thirty-five miles per hour in bursts.
                    ”Broad Broad Axe Thirty-inch blade. Twelve pounds. Sixty miles per hour on impact.
                    FIGURE 7.3 The code in Listing 7.3 shows the use of the colspan attribute and alignment styles. www.it-ebooks.info ptg 104 HOUR 7: Using Tables to Display Information At the top of Figure 7.3, a single cell (Description) spans two columns. This is accomplished with the colspan attribute in the
                    tag for that cell. As you might guess, you can also use the rowspan attribute to create a cell that spans more than one row. Spanning is the process of forcing a cell to stretch across more than one row or column of a table. The colspan attribute causes a cell to span across mul- tiple columns; rowspan has the same effect on rows. Additionally, text styles are used in the second cell within the Description column to create bold text that is both vertically aligned to the middle and horizontally aligned to the center of the cell. There are a few tricks in Listing 7.3 that I haven’t explained yet. You can give an entire table—and each individual row or cell in a table—its own background, distinct from any background you might use on the web page itself. You can do this by placing the background-color or background-image style in the , , tags). Attributes border=”width” Indicates the width in pixels of the table borders. Using border=”0” or omitting the border attribute makes borders invisible. cellspacing=”spacing” The amount of space between the cells in the table, in pixels. cellpadding=”padding” The amount of space between the edges of the cell and its contents, in pixels. style=”width:width” The width of the table on the page, either in exact pixel values or as a percentage of the page width. style=”height:height” The height of the table on the page, either in exact pixel values or as a percentage of the page height. style=”background-color:color” Background color of the table and individual table cells that don’t already have a background color. style=”backgroundimage:url(imageurl)” A background image to display within the table and individual table cells that don’t already have a background image (if a back- ground color is also specified, the color will show through transpar- ent areas of the image). www.it-ebooks.info ptg Summary 107 Table 7.1 HTML Tags and Attributes Covered in Hour 7 Attributes … Defines a table row containing one or more cells ( Defines a table data cell. Defines a table heading cell. (Accepts all the same attributes and styles as
                    , or tag exactly as you would in the tag (see Hour 9, “Working with Colors”). To give an entire table a yellow background, for example, you would use or the equivalent
                    . In Listing 7.3, only the top row has a background color; it uses to apply a red background across the cells in that row. Additionally, the color style ensures that the text in that row is white. Similar to the background-color style property is the background-image prop- erty (not shown in this example), which is used to set an image for a table background. If you wanted to set the image leaves.gif as the background for a table, you would use
                    . Notice that the image file is placed within parentheses and preceded by the word url, which indicates that you are describing where the image file is located. Tweaking tables goes beyond just using style properties. As shown in Listing 7.3, you can control the space around the borders of a table with the cellpadding and cellspacing attributes. The cellspacing attribute sets the amount of space (in pixels) between table borders and between table cells themselves. The cellpadding attribute sets the amount of space around the edges of information in the cells, also in pixels. Setting the cellpadding value to 0 causes all the information in the table to align as closely as possi- ble to the table borders, possibly even touching the borders. The cell- padding and cellspacing attributes give you good overall control of the table’s appearance. TIP Keeping the structure of rows and columns organized in your mind can be the most difficult part of creating tables with cells that span multiple columns or rows. The tiniest error can often throw the whole thing into disarray. You’ll save yourself time and frustration by sketching your tables on paper before you start writing the HTML to implement them. NOTE You will often see alternating row colors in a table. For instance, one row might have a grey background and the next row might have a white back- ground. Alternating row colors helps users read the content of your table more clearly, espe- cially if the table is quite large. NOTE Although the cellpadding and cellspacing attributes are still allowed in XHTML, a CSS equiv- alent for them exists in the form of the padding and bor- der-spacing style properties. Review the information in Appendix B, “XHTML 1.1 and CSS 2 Quick Reference,” for information and examples. www.it-ebooks.info ptg Page Layout with Tables 105 Page Layout with Tables At the beginning of this Hour, I indicated that designers have used tables for page layout as well as to display tabular information. You will still find many examples of table-based layouts if you peek at another designer’s source code. This method of design grew out of the old (mid-1990s to early 2000s) inconsistencies in browser support for CSS. All browsers supported tables and in generally the same way, so web designers latched on to the table-based method of content creation to achieve the same visual page display across all browsers. However, now that support for CSS is relative- ly similar across all major browsers, designers can follow the long-standing standards-based recommendation not to use tables for page layout. The World Wide Web Consortium (W3C), the standards body that oversees the future of the Web, promotes style sheets as the proper way to lay out pages (instead of using tables). Style sheets are ultimately much more powerful than tables, which is why the bulk of this book teaches you how to use style sheets for page layout. The main reasons for avoiding using tables for layout include: . Mixing Presentation with Content—One of the goals of CSS and standards-compliant web design is to separate the presentation layer from the content layer. . Creating Unnecessarily Difficult Redesigns—To change a table-based layout, you would have to change the table-based layout on every single page of your site (unless it is part of a complicated, dynamically- driven site, in which case you would have to undo all the dynamic pieces and remake them). . Accessibility Issues—Screen reading software looks to tables for con- tent, and so will often try to read your layout table as a content table. . Rendering on Mobile Devices—Table layouts are often not flexible enough to scale downward to small screens (see Hour 19, “Creating Fixed or Liquid Layouts”). These are but a few of the issues in table-based web design. For a closer look at some of these issues, see the popular presentation “Why Tables for Layout is Stupid” at http://www.hotdesign.com/seybold/everything.html. www.it-ebooks.info ptg 106 HOUR 7: Using Tables to Display Information Summary In this hour, you learned to arrange text and images into organized arrangements of rows and columns called tables. You learned the three basic tags for creating tables and many optional attributes and styles for controlling the alignment, spacing, and appearance of tables. You also learned that tables can be used together and nested within one another for an even wider variety of layout options. Table 7.1 summarizes the tags and attributes covered in this hour. Table 7.1 HTML Tags and Attributes Covered in Hour 7 Tag/Attribute Function
                    Creates a table that can contain any number of rows (
                    tags). Attributes style=”text-align:alignment” The horizontal alignment of the contents of the cells within this row. Possible values are left, right, and center. style=”vertical-align:alignment” The vertical alignment of the con- tents of the cells within this row. Common used values include top, middle, and bottom. style=”background-color:color” Background color of all cells in the row that do not already have a background color. style=”backgroundimage:url(imageurl)” Background image to display with- in all cells in the row that do not already have their own background image. .) Attributes style=”text-align:alignment” The horizontal alignment of the contents of the cell. Possible val- ues are left, right, and center. style=”vertical-align:alignment” The vertical alignment of the con- tents of the cell. Commonly used values are top, middle, and bottom. rowspan=”numrows” The number of rows this cell will span. colspan=”numcols” The number of columns this cell will span. style=”width:width” The width of this column of cells, in exact pixel values or as a per- centage of the table width. www.it-ebooks.info ptg 108 HOUR 7: Using Tables to Display Information Table 7.1 HTML Tags and Attributes Covered in Hour 7 Attributes style=”height:height” The height of this row of cells, in exact pixel values or as a percent- age of the table height. style=”background-color:color” Background color of the cell. style=”backgroundimage:url(imageurl)” Background image to display with- in the cell. Q&A Q I made a big table and when I load the page, nothing appears on the page for a long time. Why the wait? A Complex tables can take a while to appear on the screen. The web browser has to figure out the size of everything in the table before it can display any part of it. You can speed things up a bit by always including width and height attributes for every graphics image within a table. Using width attributes in the and
                    tags also helps. Q Can I put a table within a table? A Yes, you can nest tables within other table cells. However, nested tables—especially large ones—take time to load and render properly. Before you create a nested table, think about the content you are plac- ing on the page and ask yourself if it could be displayed using CSS. You might not know all the answers until you finish this book, but here’s a hint: In most cases, the answer will be “yes.” Workshop The workshop contains quiz questions and activities to help you solidify your understanding of the material covered. Try to answer all questions before looking at the “Answers” section that follows. Quiz 1. How would you create a simple two-row, two-column table with a standard border? 2. Expanding on Question 1, how would you add 30 pixels of space between the table border and the cells? www.it-ebooks.info ptg Exercises 109 3. Continuing with the table you’ve built in Questions 1 and 2, how would you make the top-left cell green, the top-right cell red, the bot- tom-left cell yellow, and the bottom-right cell blue? Answers 1. Use the following HTML:
                    Top left... Top right...
                    Bottom left... Bottom right...
                    2. Add cellspacing=”30” to the tag. 3. Add style=”background-color:green” to the top left
                    tag, add style=”background-color:red” to the top right tag, add style=”background-color:yellow” to the bottom left tag, and add style=”background-color:blue” to the bottom right tag. Exercises . Do you have any pages that have information visitors might be inter- ested in viewing as lists or tables? Use a table to present some tabu- lar information. Make sure each column has its own heading (or per- haps its own graphic). Play around with the various types of align- ment and spacing that you have learned in this hour. . You will often see alternating row colors in a table, with one row having a grey background and the next a white background. The goal of alternating colors in table rows is so that the individual rows are easier to discern when looking quickly at the table full of data. Create a table with alternating row colors and text colors (if neces- sary). Although the lesson on colors comes in Hour 9, you have enough information in this lesson to begin trying out the process. www.it-ebooks.info ptg This page intentionally left blank www.it-ebooks.info ptg So far, you have learned how to use HTML tags to create some basic web pages. However, at this point, those pieces of content are islands unto themselves, with no connection to anything else (although it is true that in Hour 4 I sneaked a few page links into the examples). To turn your work into “real” web content, you need to connect it to the rest of the Web—or at least to your other pages within your own personal or corporate sites. This hour shows you how to create hypertext links to content within your own document and how to link to other external documents. Additionally, you will learn how to style hypertext links so that they display in the color and decoration that you desire—not necessarily the default blue under- lined display. Using Web Addresses The simplest way to store web content for an individual web site is to place the files all in the same folder together. When files are stored together like this, you can link to them by simply providing the name of the file in the href attribute of the tag. An attribute is an extra piece of information associated with a tag that pro- vides further details about the tag. For example, the href attribute of the tag identifies the address of the page to which you are linking. Once you have more than a few pages, or once you start to have an organi- zation structure to the content in your site, you should put your files into directories (or “folders,” if you will) whose names reflect the content with- in them. For example, all your images could be in an “images” directory, corporate information could be in an “about” directory, and so on. HOUR 8 Using External and Internal Links WHAT YOU’LL LEARN IN THIS HOUR: . How to use anchor links . How to link between pages on your own site . How to link to external con- tent . How to link to an e-mail address . How to use window target- ing with your links . How to style your links with CSS NOTE Before we begin, you might want a refresher on the basics of where to put files on your server and how to manage files within a set of directories. This information is important to know when creating links in web content. Refer back to Hour 2, specifically the section entitled “Understanding Where to Place Files on the Web Server.” www.it-ebooks.info ptg 112 HOUR 8: Using External and Internal Links Regardless of how you organize your documents within your own web server, you can use relative addresses, which include only enough informa- tion to find one page from another. A relative address describes the path from one web page to another, instead of a full (or absolute) Internet address. If you recall from Hour 2, the document root of your web server is the directory designated as the top-level directory for your web content. In web addresses, that document root is represented by the forward slash (/). All subsequent levels of directories are separated by the same type of for- ward slash. For example: /directory/subdirectory/subsubdirectory/ Suppose you are creating a page named zoo.html in your document root and you want to include a link to pages named african.html and asian.html in the elephants subdirectory. The links would look like the following: Learn about African elephants. Learn about Asian elephants. These specific addresses are actually called relative-root addresses in that they are relative addresses that lack the entire domain name, but they are specifically relative to the document root specified by the forward slash. Using a regular relative address, you can skip the initial forward slash. This type of address allow the links to become relative to whatever directo- ry they are in—it could be the document root or it could be another direc- tory one or more levels down from the document root: Learn about African elephants. Learn about Asian elephants. Your african.html and asian.html documents in the elephants subdi- rectory could link back to the main zoo.html page in either of these ways: Return to the zoo. Return to the zoo. Return to the zoo. The first link is an absolute link. With an absolute link there is absolutely no doubt where the link should go, because the full URL is provided— domain name included. The second link is a relative-root link. It is relative to the domain you are WARNING The / forward slash is always used to separate directories in HTML. Don’t use the \ back- slash (which is normally used in Windows) to separate your directories. Remember, every- thing in the web moves forward, so use forward slashes. www.it-ebooks.info ptg Using Web Addresses 113 currently browsing and therefore does not require the protocol type (for example, http://) and the domain name (for example, www.yourdomain.com), but the initial forward slash is provided to show that the address begins at the document root. In the third link, the double dot (..) is a special command that indicates the folder that contains the current folder—in other words, the parent folder. Anytime you see the double dot, just think to yourself “go up a level” in the directory structure. If you use relative addressing consistently throughout your web pages, you can move the pages to another folder, disk drive, or web server with- out changing the links. Relative addresses can span quite complex directory structures if necessary. Hour 23, “Organizing and Managing a Web Site,” offers more detailed advice for organizing and linking large numbers of web pages. TIP The general rule surrounding relative addressing (elephants/african.html) versus absolute addressing (http://www.takeme2thezoo.com /elephants/african.html) is that you should use relative addressing when linking to files that are stored together, such as files that are all part of the same web site. Absolute addressing should be used when you’re linking to files somewhere else—another com- puter, another disk drive, or, more commonly, another web site on the Internet. Hopefully by now you’ve created a page or two of your own while work- ing through the lessons. Follow these steps to add a few more pages and link them together: 1. Use a “home” page as a main entrance and as a central hub to which all of your other pages are connected. If you created a page about yourself or your business, use that page as your home page. You also might like to create a new page now for this purpose. 2. On the home page, put a list of links to the other HTML files you’ve created (or placeholders for the HTML files you plan to create soon). Be sure that the exact spelling of the filename, including any capital- ization, is correct in every link. 3. On every other page besides the home page, include a link at the bot- tom (or top) leading back to your home page. That makes it simple and easy to navigate around your site. 4. You might also want to include a list of links to related or interesting sites, either on your home page or on a separate links page. People often include a list of their friends’ personal pages on their own home page. Businesses, however, should be careful not to lead poten- tial customers away to other sites too quickly—there’s no guarantee they’ll remember to use relative addressing for links between your own pages and absolute addressing for links to other sites. TRY IT YOURSELF ▼ www.it-ebooks.info ptg 114 HOUR 8: Using External and Internal Links Linking Within a Page Using Anchors The tag—the tag responsible for hyperlinks on the web—got its name from the word “anchor,” which means a link serves as a designation for a spot in a web page. In examples shown throughout this book so far, you’ve learned how to use the tag to link to somewhere else, but that’s only half of its usefulness. Let’s get started working with anchor links that link to content within the same page. Identifying Locations in a Page with Anchors The tag can be used to mark a spot on a page as an anchor, allowing you to create a link that points to that exact spot. Listing 8.1, which is pre- sented a bit later in the hour, demonstrates a link to an anchor within a page. To see how such links are made, let’s take a quick peek ahead at the first tag in the listing: The tag normally uses the href attribute to specify a hyperlinked target. The is what you click and is where you go when you click there. In this example, the tag is still specifying a target but no actual link is created. Instead, the tag gives a name to the specific point on the page where the tag occurs. The tag must be included and a unique name must be assigned to the id attribute, but no text between and is necessary. Linking to Anchor Locations Listing 8.1 shows a site with various anchor points placed throughout a single page. Take a look at the last tag in Listing 8.1 to see an example: Return to Index. The # symbol means that the word top refers to a named anchor point within the current document, rather than to a separate page. When a user clicks Return to Index, the web browser displays the part of the page starting with the tag. NOTE Instead of using id, older ver- sions of HTML used name. Newer versions of HTML and XHTML have done away with the name attribute and instead use id. www.it-ebooks.info ptg Linking Within a Page Using Anchors 115 Listing 8.1 Setting Anchor Points by Using the Tag with an id Attribute Alphabetical Shakespeare

                    First Lines of Shakespearean Sonnets

                    Don’t you just hate when you go a-courting, and you’re down on one knee about to rattle off a totally romantic Shakespearean sonnet, and zap! You space it. ”Um... It was, uh... I think it started with a B...”

                    Well, appearest thou no longer the dork. Simply refer to this page, click on the first letter of the sonnet you want, and get an instant reminder of the first line to get you started. ”Beshrew that heart that makes my heart to groan...”

                    Alphabetical Index

                    A B C D E F G H I J K L M N O P Q R S T U V W X Y Z


                    A

                    • A woman’s face with nature’s own hand painted,
                    • Accuse me thus, that I have scanted all,
                    • Against my love shall be as I am now
                    • Against that time (if ever that time come)
                    • Ah wherefore with infection should he live,
                    • Alack what poverty my muse brings forth,
                    • Alas ‘tis true, I have gone here and there,
                    • As a decrepit father takes delight,
                    • As an unperfect actor on the stage,
                    • As fast as thou shalt wane so fast thou grow’st,

                    Return to Index.


                    This text (an HTML comment) will appear in your source code but will not be displayed by the browser. You can learn more about commenting your code in Hour 23. www.it-ebooks.info ptg 116 HOUR 8: Using External and Internal Links Listing 8.1 Setting Anchor Points by Using the Tag with an id Attribute

                    (No sonnets start with Z.)

                    Return to Index.

                    Each of the links in Listing 8.1 makes an underlined link leading to a corresponding anchor—or it would if I had filled in all the text. Only A and Z will work in this example since only the A and Z links have corresponding text to link to, but feel free to fill in the rest on your own! Clicking the letter Z under Alphabetical Index in Figure 8.1, for example, takes you to the part of the page shown in Figure 8.2. WARNING Anchor names specified via the id attribute in the tag must start with an alphanumeric character. So if you want to sim- ply number the IDs of anchors, be sure to start them with text (as in photo1, photo2, and so on) instead of just 1, 2, and so on. Purely numeric anchor IDs will work in browsers but they don’t qualify as valid XHTML code. FIGURE 8.1 The tags in Listing 8.1 don’t appear at all on the web page. The tags appear as underlined links. Having mastered the concept of linking to sections of text within a single page, you can now learn to link together other pieces of web content. www.it-ebooks.info ptg Linking Between Your Own Web Content 117 Linking Between Your Own Web Content As you learned earlier in this hour, you do not need to include http:// before each address specified in the href attribute when linking to content within your domain (or on the same computer, if you are viewing your site locally). When you create a link from one file to another file within the same domain or on the same computer, you don’t need to specify a com- plete Internet address. In fact, if the two files are stored in the same folder, you can simply use the name of the HTML file by itself: Go to Page 2. As an example, Listing 8.2 and Figure 8.3 show a quiz page with a link to the answers page shown in Listing 8.3 and Figure 8.4. The answers page contains a link back to the quiz page. Because the page in Listing 8.2 links to another page in the same directory, the filename can be used in place of a complete address. FIGURE 8.2 Clicking the letter Z on the page shown in Figure 8.1 takes you to the appropriate section of the same page. www.it-ebooks.info ptg 118 HOUR 8: Using External and Internal Links Listing 8.2 The historyanswers.html file History Quiz

                    History Quiz

                    Complete the following rhymes. (Example: William the Conqueror Played cruel tricks on the Saxons in... ten sixty-six.)

                    1. Columbus sailed the ocean blue in...
                    2. The Spanish Armada met its fate in...
                    3. London burnt like rotten sticks in...

                    Check Your Answers!

                    Listing 8.3 The historyanswers.html file which historyquiz.html Links To History Quiz Answers

                    History Quiz Answers

                    1. ...fourteen hundred and ninety-two.
                    2. ...fifteen hundred and eighty eight.
                    3. ...sixteen hundred and sixty-six.

                    Return to the Questions

                    www.it-ebooks.info ptg Linking Between Your Own Web Content 119 Using filenames instead of complete Internet addresses saves you a lot of typing. More important, the links between your pages will work properly no matter where the group of pages is stored. You can test the links while the files are still on your computer’s hard drive. You can then move them to a web server, a CD-ROM, a DVD, or a memory card and all the links will still work correctly. There is nothing magic about this simplified approach to identifying web pages—it all has to do with web-page addressing, as you’ve already learned. FIGURE 8.3 This is the historyquiz.html file listed in Listing 8.2 and referred to by the link in Listing 8.3. FIGURE 8.4 The Check Your Answers! link in Figure 8.3 takes you to this answers page. The Return to the Questions link takes you back to what’s shown in Figure 8.3. www.it-ebooks.info ptg 120 HOUR 8: Using External and Internal Links Linking to External Web Content The only difference between linking to pages within your own site and linking to external web content is that when linking outside your site, you need to include the full address to that bit of content. The full address includes the http:// before the domain name and then the full pathname to the file (for example, an HTML file, image file, multimedia file, and so on). For example, to include a link to Google from within one of your own web pages, you would use this type of absolute addressing in your link: Go to Google You can apply what you learned in previous sections to creating links to named anchors on other pages. Linked anchors are not limited to the same page. You can link to a named anchor on another page by including the address or file name followed by # and the anchor name. For example, the following link would take you to an anchor named photos within the african.html page inside the elephants directory on the domain www.takeme2thezoo.com. Check out the African Elephant Photos! If you are linking from another page already on the www.takemetothezoo.com domain (because you are, in fact, the site maintainer), then your link might simply be: Check out the African Elephant Photos! The http:// and the domain name would not be necessary in that instance, as you have already learned. Linking to an Email Address In addition to linking between pages and between parts of a single page, the tag allows you to link to email addresses. This is the simplest way to enable your web page visitors to “talk back” to you. Of course, you could just provide visitors with your email address and trust them to type it into whatever email programs they use, but that increases the likelihood for errors. By providing a clickable link to your email address, you can make it almost completely effortless for them to send you messages and eliminate the chance for tyops. WARNING As you might know, you can leave out the http:// at the front of any address when typ- ing it into most web browsers. However, you cannot leave that part out when you type an Internet address into an link on a web page. WARNING Be sure to include the # symbol only in link tags. Don’t put the # symbol in the tag; links to that name won’t work in that case. www.it-ebooks.info ptg Linking to an Email Address 121 An HTML link to an email address looks like the following: Send me an email message. The words Send me an email message will appear just like any other link. If you want people to see your actual email address (so that they can make note of it or send a message using a different email program), include it both in the href attribute and as part of the message between the and tags, like this: yourusername@yourdomain.com In most web browsers, when someone clicks the link, she gets a window into which she can type a message that is immediately sent to you—what- ever email program the person uses to send and receive email will auto- matically be used. You can provide some additional information in the link so that the subject and body of the message also have default values. You do this by adding subject and body variables to the mailto link. You sepa- rate the variables from the email address with a question mark (?), the value from the variable with an equal sign (=), and then separate each of the variable and value pairs with an ampersand (&). You don’t have to understand the variable/value terminology at this point. Here is an exam- ple of specifying a subject and body for the preceding email example: author@somedomain.com When a user clicks this link, an email message is created with author@somedomain.com as the recipient, Book Question as the subject of the message, and When is the next edition coming out? as the mes- sage body. Before you run off and start plastering your email address all over your web pages, I have to give you a little warning and then let you in on a handy trick. You’re no doubt familiar with spammers that build up data- bases of email addresses and then bombard them with junk mail advertise- ments. One way spammers “harvest” email addresses is by using pro- grams that automatically search web pages for mailto links. Fortunately, there is a little trick that will thwart the vast majority of spam- TIP If you want to specify only an email message subject and not the body, you can just leave off the ampersand and the body variable, equal sign, and value text string as follows: author@somedomain.co m www.it-ebooks.info ptg 122 HOUR 8: Using External and Internal Links mers. This trick involves using character entities to encode your email address, which confuses “scraper” programs that attempt to “harvest” your email address from your web pages. As an example, take the email address, jcmeloni@gmail.com. If you replace the letters in the address with their character entity equivalents, most email harvesting programs will be thrown off. Lowercase ASCII character entities begin at a for letter a and increase through the alphabet in order. For example, letter j is j, c is c, and so on. Replacing all the characters with their ASCII attributes produces the following: Send me an email message. Since the browser interprets the character encoding as, well, characters, the end result is the same from the browser’s perspective. However, automat- ed email harvesting programs search the raw HTML code for pages, which in this case is showing a fairly jumbled-looking email address. If you don’t want to figure out the character encoding for your own address, just type email address encoder in your search engine and you will find some serv- ices online that will produce an encoded string for you. Opening a Link in a New Browser Window Now that you have a handle on how to create addresses for links—both internal (within your site) and external (to other sites)—there is one addi- tional method of linking: forcing the user to open links in new windows. You’ve no doubt heard of pop-up windows, which are browser windows— typically advertising products or services—that are opened and displayed automatically without the user’s approval. However, the concept of open- ing another window or targeting another location does serve a valid pur- pose in some instances. For example, you might want to present informa- tion in a smaller secondary browser window but allow the user to still see the information in the main window. This is often the case when clicking on a link to an animated demo, movie clip, or other multimedia element. You could also want to target a new browser window when you are link- ing to content off-site. However, opening a new browser window on behalf of your user—espe- TIP It is customary to put an email link to the web page author at the bottom of every web page. Not only does this make it easy for others to contact you, it gives them a way to tell you about any problems with the page that your testing might have missed. Just don’t forget to use the email address char- acter entity trick so that your address flies under the radar of spammers. www.it-ebooks.info ptg Using CSS to Style Hyperlinks 123 cially when it’s a full-size new window—goes against some principles of usability and accessibility. When people opened new windows, typically it happened through the use of the target attribute of the tag. The target attribute has been removed from the tag in the strict XHTML 1.1 speci- fication. There are valid ways to achieve the same result while still adhering to principles of usability and accessibility, but these methods require a little JavaScript and other advanced techniques. You will learn these methods in Hour 18, “Using Mouse Actions to Modify Text Display,” which will also cover standards-compliant and accessible ways to invoke new windows with your external links. Using CSS to Style Hyperlinks The default display of a text-based hyperlink on a web page is underlined blue text. You might also have noticed that links you have previously visit- ed appear as underlined purple text—that color is also a default. If you’ve spent any time at all on the web, you will also have noticed that not all links are blue or purple—and for that, I think, we are all thankful. Using a little CSS and knowledge of the various pseudoclasses for the link, you can make your links look however you want. A pseudoclass is a class that describes styles for elements that apply to cer- tain circumstances, such as various states of user interaction with that ele- ment. For example, the common pseudoclasses for the tag are link, visited, hover, and active. You can remember them with the mnemonic “Love- Hate”—LV (love) HA (hate), if you wish. . a:link describes the style of a hyperlink that has not been visited previously . a:visited describes the style of a hyperlink that has been visited pre- viously and is present in the browser’s memory . a:hover describes the style of a hyperlink as a user’s mouse hovers over it (and before it has been clicked) . a:active describes the style of a hyperlink that is in the act of being clicked but has not yet been released. For example, let’s say you want to produce a link with the following styles: NOTE You can use graphics as links (instead of using text as links) by putting an tag between the opening and closing tags. You’ll learn how to use graphics as links in Hour 11, “Using Images in Your Web Site.” www.it-ebooks.info ptg 124 HOUR 8: Using External and Internal Links .A font that is bold and Verdana (and not underlined, meaning it has no text decoration) .A base color that is light blue .A color of red when users hover over it or when they are clicking it .A color of grey after users have visited it. Your style sheet entries might look like the following: a { font-family: Verdana, sans-serif; font-weight: bold; text-decoration: none; } a:link { color: #6479A0; } a:visited { color: #CCCCCC; } a:hover { color: #E03A3E; } a:active { color: #E03A3E; } Since the example link will be Verdana bold (and not underlined) regard- less of the state it is in, those three property and value pairs can reside in the rule for the a selector. However, since each pseudoclass must have a specific color associated with it, we use a rule for each pseudoclass as shown in the code example. The pseudoclass inherits the style of the par- ent rule, unless the rule for the pseudoclass specifically overrides that rule. In other words, all the pseudoclasses in the previous example will be Verdana bold, (and not underlined). If, however, we had used the follow- ing rule for the hover pseudoclass, the text would display in Comic Sans when users hovered over it (if, in fact, the user has the Comic Sans font installed): a:hover { font-family: “Comic Sans MS”; color: #E03A3E; } Additionally, since the active and hover pseudoclasses use the same font NOTE The colors in this example are indicated by their hexadecimal values, which you will learn about in Hour 9, “Working with Colors.” www.it-ebooks.info ptg Using CSS to Style Hyperlinks 125 color, you can combine style rules for them: a:hover, a:active { color: #E03A3E; } Listing 8.4 puts these code snippets together to produce a page using styled pseudoclasses; the results of this code can be seen in Figure 8.5. Listing 8.4 Using Styles to Display Link Pseudoclasses Sample Link Style

                    Sample Link Style

                    The first time you see me, I should be a light blue, bold, non-underlined link in the Verdana font.

                    If you view the example in your web browser, indeed the link should be a light blue, bold, non-underlined Verdana font. If you hover over the link, or click the link without releasing it, it should turn red. If you click and release the link, the page will simply reload because the link points to the file with the same name. However, at that point the link will be in your browser’s www.it-ebooks.info ptg 126 HOUR 8: Using External and Internal Links You can use CSS to apply a wide range of text-related changes to your links. You can change fonts, sizes, weights, decoration, and so on. Sometimes you might want several different sets of link styles in your style sheet. In that case, you can create classes; you aren’t limited to working with only one set of styles for the tag. The following example is a set of style sheet rules for a footerlink class for links I might want to place in the footer area of my web site: a.footerlink { font-family: Verdana, sans-serif; font-weight: bold; font-size: 75%; text-decoration: none; } a.footerlink:link, a.footerlink:visited { color: #6479A0; } a.footerlink:hover, a.footerlink:active { color: #E03A3E; } As you can see in the example that follows, the class name (footerlink) appears after the selector name (a), separated by a dot, and before the pseudoclass name (hover), separated by a colon: selector.class:pseudoclass a.footerlink:hover Spend some time with Appendix B, “XHTML 1.1 and CSS 2 Quick Reference” for an idea of the styles you can apply to your links. FIGURE 8.5 A link can use particular styles to control the visual display. memory and thus will be displayed as a visited link—and it will appear grey instead of blue. www.it-ebooks.info ptg Summary 127 Summary The tag is what makes hypertext “hyper.” With it, you can create links between pages as well as links to specific anchor points on any page. This hour focused on creating and styling simple links to other pages using either relative or absolute addressing to identify the pages. You learned that when you’re creating links to other people’s pages, it’s important to include the full Internet address of each page in an tag. For links between your own pages, include just the filenames and enough directory information to get from one page to another. You also learned how to create named anchor points within a page and how to create links to a specific anchor. You also learned how to link to your email address so that users can easily send you messages. You even learned how to protect your email address from spammers. Finally, you learned methods for controlling the display of your links using CSS. Table 8.1 summarizes the tag discussed in this hour. Table 8.1 HTML Tags and Attributes Covered in Hour 8 Tag/Attribute Function With the href attribute, creates a link to another document or anchor; with the id attribute, creates an anchor that can be linked to. Attributes href=”address” The address of the document or anchor point to link to. id=”name” The name for this anchor point in the document. Q&A Q What happens if I link to a page on the Internet and then the person who owns that page deletes or moves it? A That depends on how the maintainer of that external page has set up his web server. Usually, you will see a page not found message or something to that effect when you click a link that has been moved or deleted. You can still click the Back button to return to your page. As a site maintainer, you can periodically run link-checking programs to ensure your internal and external links are valid. An example of this is the Link Checker service at http://validator.w3.org/checklink. www.it-ebooks.info ptg 128 HOUR 8: Using External and Internal Links Q One of the internal links on my web site works fine on my computer, but when I put the pages on the Internet, the link doesn’t work any- more. What’s up? A These are the most likely culprits: . Capitalization problems. On Windows computers, linking to a file named MyFile.html with will work. On most web servers, the link must be (or you must change the name of the file to MyFile.html). To make matters worse, some text editors and file transfer programs actually change the capitalization without telling you! The best solution is to stick with all-lowercase filenames for web pages. . Spaces in filenames. Most web servers don’t allow filenames with spaces. For example, you should never name a web page my page.html. Instead, name it mypage.html or even my_page.html (using an underscore instead of a space). . Local absolute addresses. If, for some reason, you link to a file using a local absolute address, such as C:\mywebsite\news.html, the link won’t work when you place the file on the Internet. You should never use local absolute addresses; when this occurs, it is usually an accident caused by a temporary link that was created to test part of a page. So, be careful to remove any test links before publishing a page on the Web. Q Can I put both href and id in the same tag? Would I want to for any reason? A You can, and it might save you some typing if you have a named anchor point and a link right next to each other. It’s generally better, however, to use and separately to avoid confusion because they play very different roles in an HTML document. Q What happens if I accidentally misspell the name of an anchor or for- get to put the # in front of it? A If you link to an anchor name that doesn’t exist within a page or mis- spell the anchor name, the link goes to the top of that page. Workshop The workshop contains quiz questions and exercises to help you solidify your understanding of the material covered. Try to answer all questions before looking at the “Answers” section that follows. www.it-ebooks.info ptg Exercises 129 Quiz 1. Your best friend from elementary school finds you on the Internet and says he wants to trade home page links. How do you put a link to his site at www.supercheapsuits.com/~billybob/ on one of your pages? 2. What HTML would you use to make it possible for someone clicking the words “About the Authors” at the top of a page to skip down to a list of credits somewhere else on the page? 3. If your email address is bon@soir.com, how would you make the text “goodnight greeting” into a link that people can click to compose and send you an email message? Answers 1. Put the following on your page: Billy Bob’s site 2. Type this at the top of the page: About the Authors Type this at the beginning of the credits section: 3. Type the following on your web page: Send me a goodnight greeting! Exercises . Create an HTML file consisting of a formatted list of your favorite web sites. You might already have these sites bookmarked in your web browser, in which case you can visit them to find the exact URL in the browser’s address bar. . If you have created any pages for a web site, look through them and consider whether there are any places in the text where you’d like to make it easy for people to contact you. Include a link in that place to your email address. You can never provide too many opportunities for people to contact you and tell you what they need or what they think about your products—especially if you’re running a business. www.it-ebooks.info ptg This page intentionally left blank www.it-ebooks.info ptg All the sample pages shown in this book thus far have used a standard white background and black text. That’s not a requirement, although some variation of dark text on a light background is the most common color combination you’ll find online. After a brief overview of some best prac- tices in color selection, you’ll learn when you can use colors, how to pick colors, and how to specify colors when creating various elements of your web site. Best Practices for Choosing Colors I can’t tell you exactly which colors to use in your web site, but I can help you understand the considerations you should make when selecting those colors on your own. The colors you use can greatly influence your visitors; if you are running an e-commerce site, you will want to use colors that entice your users to view your catalog and eventually purchase something. To that end, you want to make sure colors are used judiciously and with respect. You might wonder how “respect” enters into the mix when talking about colors, but remember the World Wide Web is an international com- munity and interpretations differ; for instance, pink is a very popular color in Japan, but very unpopular in Eastern European countries. Similarly, green is “the color of money” in the United States, but the vast majority of other countries have multi-colored paper bills such that “the color of money” isn’t a single color at all and thus the metaphor would be of no value to them. HOUR 9 Working with Colors WHAT YOU’LL LEARN IN THIS HOUR: . How to choose colors for your website . How colors work on the Web . How to use hexadecimal values for color . How to use CSS to set background, text, and border colors www.it-ebooks.info ptg 132 HOUR 9: Working with Colors Besides using colors that are culturally sensitive, other best practices include: . Use a natural palette of colors. This doesn’t mean you should use earth tones, but instead refers to using colors that one would natural- ly see on a casual stroll around town—avoid ultrabright colors that can cause eye strain. . Use a small color palette. You don’t need to use 15 different colors to achieve your goals. In fact, if your page includes text and images in 15 different colors, you might reevaluate the message you’re attempt- ing to send. Focus on three or four main colors with a few compli- mentary colors, at the most. . Consider your demographics. You are likely not able to control your demographics and thus have to find a middle ground that accommo- dates everyone. The colors enjoyed by younger people are not neces- sarily those appreciated by older people, just as there are color biases between men and women and people from different geographic regions and cultures. With just these few tips in mind, it might seem as if your color options are limited. Not so—it simply means you should think about the decisions you’re making before you make them. A search for “color theory” in the search engine of your choice should give you more food for thought, as will the use of the color wheel. The color wheel is a chart that shows the organization of colors in a circular manner. The method of display is an attempt to help you visualize the rela- tionships between primary, secondary, and complementary colors. Color schemes are developed from working with the color wheel; understanding color schemes can help you determine the color palette to use consistently throughout your web site. For example, knowing something about color relationships will hopefully allow you to avoid using orange text on a light blue background, or bright blue text on a brown background. Some common color schemes in web design are: . Analogous—Colors that are adjacent to each other on the color wheel, such as yellow and green. One color is the dominant color and its analogous friend is used to enrich the display. . Complementary—Colors that are opposite from each other on the color wheel, such as a warm color (red) and a cool color (green). . Triadic—Three colors that are equally spaced around the color wheel. The triadic scheme provides balance while still allowing rich color use. www.it-ebooks.info ptg Understanding Web Colors 133 There are entire books and courses devoted to understanding color theory, so continuing the discussion in this book would indeed be a tangent. However, if you intend to work in web design and development, you will be served well by a solid understanding of the basics of color theory. Spend some time reading about it—an online search will provide a wealth of information. Additionally, spend some hands-on time with the color wheel. The Color Scheme Generator at http://colorschemedesigner.com/ allows you to start with a base color and produce monochromatic, complementary, triadic, tetradic, analogic, and accented analogic color schemes. Understanding Web Colors Specifying a background color other than white for a web page is easier than you probably realize. For example, to specify blue as the background color for a page, put style=”background-color:blue” inside the tag or in the style sheet rule for the body element. Of course, you can use many colors other than blue. In fact, there are 16 colors listed in the W3C stan- dards: aqua, black, blue, fuchsia, gray, green, lime, maroon, navy, olive, purple, red, silver, teal, white, and yellow. Obviously there are many more colors displayed on the Web than just those 16. In fact, there are 140 color names that you can use with assurance that all browsers will display these colors similarly. Here’s a partial list of the 140 descriptive color names: azure, bisque, cornflowerblue, dark- salmon, firebrick, honeydew, lemonchiffon, papayawhip, peachpuff, sad- dlebrown, thistle, tomato, wheat, and whitesmoke. But names are subjective—for instance, if you look at the color chart of 140 cross-browser color names, you will not be able to distinguish between fuchsia and magenta. You will then realize that the associated hexadecimal color values for those two terms, fuchsia and magenta, are exactly the same: #FF00FF. You’ll learn about hexadecimal color values in the next sec- tion, but for now, know that if you want to be standards-compliant and use more than the 16 color names the W3C standards dictate, you should use the hexadecimal color codes whenever possible. There are, in fact, 16 million colors made possible with hexadecimal color codes. However, most modern computer displays can display “only” 16,384. But 16,384 is still a lot more than 140, or 16. NOTE For a complete list of the 140 descriptive color names, as well as their hexadecimal codes and an example of the color as dis- played by your browser, visit http://www.w3schools.com/ HTML/html_colornames.asp. TIP It’s worth pointing out that color names are not case-sensitive. So, Black, black, and BLACK are all black, although most web designers stick with lower- case or mixed case (if they use color names at all, as most designers will use the hexadeci- mal notation for a more nuanced approach to color use). www.it-ebooks.info ptg 134 HOUR 9: Working with Colors You should be aware that not all computer monitors display colors in the same hues. What might appear as a beautiful light blue background color on your monitor might be more of a purple hue on another user’s monitor. Neutral, earth-tone colors (such as medium gray, tan, and ivory) can pro- duce even more unpredictable results on many computer monitors. These colors might even seem to change color on one monitor depending on lighting conditions in the room or the time of day. In addition to changing the background of your pages to a color other than white, you can change the color of text links, including various properties of links (such as the color for when a user hovers over a link versus when the user clicks a link—as you learned in the previous hours). You can also set the background color of container elements (such as paragraphs, divs, blockquotes, and table cells) and you can use colors to specify the borders around those elements. You’ll see some examples of colors and container elements later in this hour. There are plenty of very bad websites, some created by earnest people with no trace of irony whatsoever. However, “The World’s Worst Website” shown in Figure 9.1 was purposefully created to show some of the more egregious sins of web site design, especially with its use of colors. A screenshot does not do it justice—visit and experience the site for yourself at http://www.angelfire.com/super/badwebs/main.htm. FIGURE 9.1 A partial screenshot of “The World’s Worst Website.” www.it-ebooks.info ptg Using Hexadecimal Values for Colors 135 If you search for bad web site examples in your search engine, you will find many sites that collect examples of bad design and explain just why such a site should be in a Hall of Shame rather than a Hall of Fame. Many sites are considered “bad” because of their visual displays, and that dis- play begins with color selection. Therefore, understanding colors, as well as the nuances of their specification and use, is a crucial step to creating a good web site. Using Hexadecimal Values for Colors To remain standards-compliant, as well as to retain precise control over the colors in your web site, you can reference colors by their hexadecimal value. The hexadecimal value of a color is an indication of how much red, green, and blue light should be mixed into each color. It works a little bit like Play-Doh—just mix in the amounts of red, blue, and green you want to get the appropriate color. The hexadecimal color format is #rrggbb, in which rr, gg, and bb are two- digit hexadecimal values for the red (rr), green (gg), and blue (bb) compo- nents of the color. If you’re not familiar with hexadecimal numbers, don’t sweat it. Just remember that FF is the maximum and 00 is the minimum. Use one of the following codes for each component: . FF means full brightness. . CC means 80 percent brightness. . 99 means 60 percent brightness. . 66 means 40 percent brightness. . 33 means 20 percent brightness. . 00 means none of this color component. For example, bright red is #FF0000, dark green is #003300, bluish-purple is #660099, and medium-gray is #999999. To make a page with a red back- ground and dark green text, the HTML code would look like the following: Although only six examples of two-digit hexadecimal values are shown here, there are actually 225 combinations of two-digit hexadecimal val- www.it-ebooks.info ptg 136 HOUR 9: Working with Colors ues—0 through 9 and A through F, paired up. For example, F0 is a possible hex value (decimal value 240), 62 is a possible hex value (decimal value 98), and so on. As previously discussed, the rr, gg, and bb in the #rrggbb hexadecimal color code format stand for the red, green, and blue components of the color. Each of those components has a decimal value ranging from 0 (no color) to 255 (full color). So, white (or #FFFFFF) translates to a red value of 255, a green value of 255, and a blue value of 255. Similarly, black (#000000) translates to a red value of 0, a green value of 0, and a blue value of 0. True red is #FF0000 (all red, no green, and no blue), true green is #00FF00 (no red, all green, no blue), and true blue is #0000FF (no red, no green, and all blue). All other hexadecimal notations translate to some variation of the 255 possible val- ues for each of the three colors. The cross-browser compatible color name CornflowerBlue is associated with the hexadecimal notation #6495ED—a red value of 40, a green value of 149, and a blue value of 237 (almost all of the available blue values). When picking colors, either through a graphics program or by finding something online that you like, you might see the color notion in hexadeci- mal or decimal. If you type hexadecimal color converter in your search engine, you will find numerous options to help you convert color values into something you can use in your style sheets. Using CSS to Set Background, Text, and Border Colors When using CSS, there are three instances in which color values can be used: when specifying the background color, the text color, or the border color of elements. Previous hours contained examples of specifying colors without going in great detail about color notion or color theory. For exam- ple, in Hour 8, you learned about using colors for various link states. In Hour 7, one of the quiz questions asked how to fill table cells with colors. Figure 9.2 shows an example of color usage that could very easily go into a web design Hall of Shame. I can’t imagine ever using these combinations of colors and styles in a serious web site, but it serves here as an example of how color style could be applied to various elements. Listing 9.1 shows the XHTML and CSS styles used to produce Figure 9.2. www.it-ebooks.info ptg Using CSS to Set Background, Text, and Border Colors 137 Listing 9.1 Using Styles to Produce Background, Text, and Border Colors Background, Text, and Border Colors

                    Background, Text, and Border Colors

                    Grey paragraph, black border, red text with a orange span.

                    Black div, red border, white text.
                    Green Table Cell Red Table Cell
                    Blue Table Cell Yellow Table Cell

                    Blue blockquote, yellow border, white text.

                    www.it-ebooks.info ptg 138 HOUR 9: Working with Colors FIGURE 9.2 Background, text, and border col- ors can all be set using CSS. NOTE You can do quite a lot with bor- ders, specifying different widths, types, and colors for all four borders of an element: top, right, bottom, and left. See Appendix B, “XHTML 1.1 and CSS 2 Quick Reference” for more information. Looking at the styles used in Listing 9.1, you should be able to figure out almost everything except some of the border styles. In CSS, borders can’t be designated as a color without also having a width and type; in the first example shown in Listing 9.1, the border width is 1px and the border type is solid. In the second example shown in Listing 9.2, the border width is 2px and the border type is dashed. In the fourth example shown in Listing 9.2, the border width is 4px and the border type is dotted. When picking colors for your web site, remember that a little bit goes a long way—if you really like a bright and spectacular color, use it as an accent color and not throughout the primary design elements. For readabil- ity, remember that light backgrounds with dark text are much easier to read than dark backgrounds with light text. Finally, consider the not-insignificant portion of your audience that might be color blind. For accessibility, you might consider using the Colorblind Web Page Filter tool at http://colorfilter.wickline.org/ to see what your site will look like to a person with color blindness. www.it-ebooks.info ptg Q&A 139 Summary In this hour, you learned a few best practices for thinking about color use, and how to use the color wheel to help you find colors that will comple- ment your text. Additionally, you learned about hexadecimal notion for colors—that all colors are expressed in notations related to the amount of red, green, and blue in them—and how hexadecimal notation allows you to apply nuanced colors to your elements. More importantly, you learned about the three color-related style properties that can be used to apply color to container backgrounds, borders, and text using CSS. Table 9.1 summarizes these style properties. Table 9.1 Style Properties Covered in Hour 9 Attribute/Style Function style=”background-color:color” Sets the background color of an ele- ment (such as ,

                    ,

                    ,
                    , and other containers). style=”color:color” Sets the color of text within an ele- ment. style=”border:size type color “ Sets the color of the four borders around an element. Border colors cannot be used without also specify- ing the width and type of the border. Q&A Q Don’t web browsers let people choose their own background and text colors? A Yes, web browsers allow users to override the colors that you, as a web page author, specify. Some might see your white-on-blue page as green- on-white or their own favorite colors instead, but very few people actual- ly use this option. The colors specified in the tag will usually be seen. Q I’ve heard that there are 231 “browser-safe colors” that I can use on web pages and that I shouldn’t use any other colors. Is that true? A Here’s the real story: There are 231 colors that will appear less “fuzzy” to users who operate their computers in a 256-color (8-bit) video mode. Some web page authors try to stick to those colors. However, true-color www.it-ebooks.info ptg 140 HOUR 9: Working with Colors or high-color computer displays are all but standard these days, and they show all colors with equal clarity. So if your graphics program can provide color values to you in hexadecimal format, feel free to plug that value straight into your style sheet to display custom color schemes. Workshop The workshop contains quiz questions and activities to help you solidify your understanding of the material covered. Try to answer all questions before looking at the “Answers” section that follows. Quiz 1. How would you give a web page a black background and make all text bright green? Would you want to? 2. When selecting a color scheme for your web site, which of the fol- lowing types of color relationships would give you more color options: analogous, complementary, or triadic? 3. If you specify background-color #FFFFFF for the body element in your style sheet, then use background-color #FF0000 for the first
                    that you use on your page, will the background of that
                    be red or white? Answers 1. Put the following at the beginning of the web page or use a style rule for the body element: 2. Triadic. It refers to three colors evenly spaced around the color wheel. 3. The background of your
                    will be red, because the background- color specification of a container element will override the specifica- tion in the tag or body entry in the style sheet. www.it-ebooks.info ptg Exercises 141 Exercises . Select a base color that you like—perhaps a lovely blue or an earthy tone—and use the Color Scheme Generator at http://colorschemedesigner.com/ to come up with a set of colors that you can use in a web site. I recommend the tetrad or accented analogic scheme types. . Once you have a set of colors—or a few options for sets of colors— create a basic HTML page with a

                    element, a paragraph of text, and perhaps some list items. Use the color-related styles you’ve learned about in this hour to change the background color of the page, and the text of the various block-level elements, in order to see how these sets of colors might work together. See how they interact and determine which colors are best used for containers and which are best used for plain text, header text, and link text. www.it-ebooks.info ptg This page intentionally left blank www.it-ebooks.info ptg Although paying attention to color schemes and producing a visually appealing web site is important, you don’t have to be an artist by trade to put high-impact graphics on your web pages. More importantly, you don’t need to spend hundreds or thousands of dollars on software, either. This hour will help you get started with creating some of the images you can use in your web site. Although the sample figures in this chapter use a popular and free graphics program for Windows, Mac, and Linux users (GNU Image Manipulation Program, or GIMP), you can apply the knowl- edge learned in this hour to any major Windows or Macintosh graphics application—although the menus and options might be slightly different. In this hour, you learn only how to create the graphics themselves, including different types of graphic uses. In Hour 11, “Using Images in Your Web Site,” you’ll learn how to integrate your graphics using HTML and CSS. Choosing Graphics Software You can use almost any graphics program to create images for your web site, from the simple paint program that typically comes free with your computer’s operating system to an expensive professional program such as Adobe Photoshop. Similarly, if you have a digital camera or scanner attached to your computer, it probably came with some graphics software capable of creating web page graphics. There are also several free image editors available for download—or even online as a web application—that deal just with the manipulation of photographic elements. HOUR 10 Creating Images for Use on the Web WHAT YOU’LL LEARN IN THIS HOUR: . How to choose graphics software . How to prepare photo- graphs for use online . How to create banners and buttons . How to reduce the number of colors in an image . How to create transparent images . How to create tiled back- grounds . How to create animated web graphics NOTE Adobe Photoshop is without a doubt the cream of the crop when it comes to image-editing programs. However, it is expen- sive and quite complex if you don’t have experience working with computer graphics. For more information on Adobe’s products, visit the Adobe web site at http://www.adobe.com/. If you are in the market for one of their products, you can down- load a free evaluation version from their site. www.it-ebooks.info ptg 144 HOUR 10: Creating Images for Use on the Web If you already have software you think might be good for creating web graph- ics, try using it to do everything described in this hour. If it can’t do some of the tasks covered here, it probably won’t be a good tool for web graphics. In that case, download and install GIMP from http://www.gimp.org. This fully- functional graphics program is completely free: 1. Go to http://www.gimp.org/ and click the Downloads link. 2. You should see a link leading to a download for your operating sys- tem. You can also click the Show other downloads link, which will lead you to all the available options. Once you see the link to the software specifically made for your operating system, click that link to begin the download. 3. Once the download is complete, double-click the installer to install the program. The examples in this hour use GIMP to illustrate several key web graphics techniques you’ll need to know. Of course, there are so many ways to pro- duce images, and so many different types of software you can use, I can’t even begin to explain them all. However, all of the major software pro- grams for creating graphics will include detailed help functions, documen- tation, and online user tutorials. Use the power of your search engine to learn what I simply cannot explain in just one hour. If GIMP doesn’t suit you, consider downloading the evaluation version of Adobe Photoshop or Corel DRAW. For photo manipulation only, there are many free options, all with helpful features. Google’s Picasa, which is available free at http://picasa.google.com/, is one such option. Picnik (http://www.picnik.com/) is another. Both of these programs are suited for editing images rather than creating them from scratch, and Picasa is also oriented toward organizing your digital photograph collection. As such, these types of programs are not necessarily going to help you design a banner or button image for your site. However, these programs can help you work with some supplementary images and they are powerful enough that they are worth checking out. The Least You Need to Know About Graphics Two forces are always at odds when you post graphics and multimedia on the Internet. The users’ eyes and ears want all your content to be as detailed and accurate as possible and they also want that information dis- Using Another Site’s Material One of the best ways to save time creating the graphics and media files for web pages is, of course, to avoid creating them altogether. Grabbing a graphic from any web page is as simple as right-clicking it (or clicking and holding the button on a Macintosh mouse) and select- ing Save Image As or Save Picture As (depending on your browser). Extracting a back- ground image from a page is just as easy: Right-click it and select Save Background As. However, you should never use images without the explicit per- mission of the owner, either by asking them or by looking for a Creative Commons license. To take images without explicit permission is a copyright viola- tion (and is also distasteful). To learn more about copyrights, visit http://www.utsystem.edu/OGC/ IntellectualProperty/cprtindx.htm. You might also want to consider royalty-free clip art, which does- n’t require you to get copyright permission. A good source of clip art online is Microsoft’s Office Online Clip Art and Media web site, which is located at http://office.microsoft.com/ clipart/. Barry’s Clipart Server is another popular clip art destination, and it’s located at http://www.barrysclipart.com/. www.it-ebooks.info ptg Preparing Photographic Images 145 played immediately. Intricate, colorful graphics mean big file sizes, which increase the transfer time even over a fast connection. How do you maxi- mize the quality of your presentation while minimizing file size? To make these choices, you need to understand how color and resolution work together to create a subjective sense of quality. The resolution of an image is the number of individual dots, or pixels, that make up an image. Large, high-resolution images generally take longer to transfer and display than small, low-resolution images. Resolution is usu- ally specified as the width times the height of the image, expressed in pix- els; a 300×200 image, for example, is 300 pixels wide and 200 pixels high. You might be surprised to find that resolution isn’t the most significant fac- tor determining an image file’s storage size (and transfer time). This is because images used on web pages are always stored and transferred in compressed form. Image compression is the mathematical manipulation that images are put through to squeeze out repetitive patterns. The mathe- matics of image compression is complex, but the basic idea is that repeat- ing patterns or large areas of the same color can be squeezed out when the image is stored on a disk. This makes the image file much smaller and allows it to be transferred faster over the Internet. The web browser then restores the original appearance of the image when the image is displayed. In the rest of this hour, you’ll learn exactly how to create graphics with big visual impact and small file sizes. The techniques you’ll use to accomplish this depend on the contents and purpose of each image. There are as many uses for web graphics as there are web pages, but four types of graphics are by far the most common: . Photos of people, products, or places . Graphical banners and logos . Buttons or icons to indicate actions and provide links . Background textures for container elements Preparing Photographic Images To put photos on your web pages, you need to convert your print-based photos to digital images or create photos digitally by using a digital camera. You might need to use the custom software that comes with your scanner or camera to save pictures onto your hard drive, or you can just drag and NOTE There are several types of image resolution, including pixel, spatial, spectral, tempo- ral, and radiometric. You could spend hours just learning about each type; and if you were tak- ing a graphics design class, you might do just that. For now, however, all you need to remem- ber is that large images take longer to download and also use a lot of space in your dis- play. Display size and storage or transfer size are factors you should take into consideration when designing your web site. www.it-ebooks.info ptg TRY IT YOURSELF▼ Cropping in GIMP The GIMP toolbox offers quick access to the crop tool and its possible attrib- utes. Find an image file—either a digital image you have taken with your cam- era and stored on your hard drive, or an image you have found online. After opening the image in GIMP, perform the following steps to crop it in GIMP: 1. In the GIMP toolbox, click the crop tool (see Figure 10.1). Depending on the tool you select, there might be additional attributes you can select. For example, Figure 10.1 shows the attributes for the cropping tool (such as the aspect ratio, position, size, and so on). 146 HOUR 10: Creating Images for Use on the Web drop files from your camera to your hard drive. If you are using a scanner to create digital versions of your print photos, you can control just about any scanner directly from the graphics program of your choice—see the software documentation for details. After you transfer the digital image files to your computer, you can use your graphics program to crop, resize, color-correct, and compress to get them ready for use in your web site. Cropping an Image Since you want web page graphics to be as compact as possible, you’ll usu- ally need to crop your digital photos. When you crop a photo, you select the area you want to display and you crop away the rest. . TIP If you don’t have a scanner or digital camera, almost all film developers offer a service that transfers photos from 35mm film to a CD-ROM or DVD-ROM for a modest fee. You can then copy the files from the CD-ROM or DVD-ROM to your hard drive and then use your graphics pro- gram to open and modify the image files. FIGURE 10.1 Select the crop tool from the toolbox. www.it-ebooks.info ptg TRY IT YOURSELF ▼ Preparing Photographic Images 147 FIGURE 10.2 Select the area of the image that you wish to display. Cropping in GIMP 2. In the image you want to crop, draw a box around the selection by clicking the upper-left corner of the portion of the image you want to keep and holding the left mouse button while you drag down to the lower-right corner. See Figure 10.2. 3. Click one of the corners of the selection to apply the cropping. Your graphics program will likely have a different method than the one shown, but the concept is the same: select the area to keep and then crop out the rest. Even after your image has been cropped, it might be larger than it needs to be for a web page. Depending on the design of a specific web page, you might want to limit large images to no more than 800×600 pixels (if it is shown on a page by itself, such as an item catalog) or even 640×480 pixels or smaller. When shown alongside text, images tend to be in the 250 to 350 pixel range for width, so there’s just enough room for the text as well. In some cases, you might want to also provide a thumbnail version of the image that links to a larger version, in which case you’ll probably stick closer to 100 pixels in the larger dimension for the thumbnail. TIP Your graphics software will likely have an omnipresent size dis- play somewhere in the image window itself. In GIMP, the cur- rent image size can be seen in the top of the window. Other programs might show it in the lower-right or lower-left corner. You might also see the magnifi- cation ratio in the window, as well as the ability to change it (by zooming in or zooming out). www.it-ebooks.info ptg 148 HOUR 10: Creating Images for Use on the Web Resizing an Image The exact tool necessary to change an image’s size will depend on the pro- gram you are using. In GIMP, go to the Image menu and click Scale Image to open the Scale Image dialog box (see Figure 10.3). FIGURE 10.3 Use the Scale Image dialog box to change the size of an image. You’ll almost always want to resize using the existing aspect ratio, mean- ing that when you enter the width you’d like the image to be, the height will be calculated automatically (and vice versa) to keep the image from squishing out of shape. In GIMP, the aspect ratio is locked by default, as indicated by the chain link displayed next to the Width and Height options shown in Figure 10.3. Clicking once on the chain will unlock it, enabling you to specify pixel widths and heights of your own choosing—squished or not. In most, if not all, graphics programs, you can also resize the image based on percentages instead of providing specific pixel dimensions. For exam- ple, if my image started out as 1629 x 1487 and I didn’t want to do the math to determine the values necessary to show it as half that width, I could simply select Percent (in this instance from the drop-down next to the pixel display shown in Figure 10.3) and change the default setting (100) to 50. The image width would then become 815 pixels wide by 744 high — and no math was necessary on my part. NOTE As with many of the features in GIMP, the Scale Image dialog box appears in front of the win- dow containing the image being resized. This placement allows you to make changes in the dia- log box, apply them, and see the results immediately. www.it-ebooks.info ptg Preparing Photographic Images 149 Tweaking Image Colors If you are editing photographic images rather than creating your own graphics, you might need to use some color-correction tools to get the photo just right. Like many image editing programs, GIMP offers several options for adjusting an image’s brightness, contrast, and color balance, as well as a filter to reduce the dreaded red-eye. To remove red-eye using GIMP, go to Filters, click Enhance, and then click Red Eye Removal. Most of these options are pretty intuitive. If you want the image to be brighter, adjust the brightness. If you want more red in your image, adjust the color balance. In GIMP, the Colors menu gives you access to numerous tools. As with the Scale Image dialog box described in the previous section, each tool displays a dialog box in the foreground of your workspace. As you adjust the colors, the image reflects those changes. This preview func- tion is a feature included in most image editing software. Figure 10.4 shows the Adjust Hue/Lightness/Saturation tool, one of the many tools provided on the Colors menu. As shown in the figure, many color-related changes occur by using various sliders in dialog boxes to adjust the values you are working with. The Preview feature allows you to see what you are doing as you are doing it. The Reset Color button returns the image to its original state without any changes applied. FIGURE 10.4 The Adjust Hue/Lightness/ Saturation tool is one of many slid- er-based color modification tools available in GIMP. www.it-ebooks.info ptg 150 HOUR 10: Creating Images for Use on the Web Because of the numerous tools available to you, and the preview function available with each tool, a little playful experimentation is the best way to find out what each tool does. Controlling JPEG Compression Photographic images on the web work best when saved in the JPEG file format rather than GIF; JPG allows you to retain the number of colors in the file while still keeping the overall file size to a manageable level. When you’re finished adjusting the size and appearance of your photo, select File, Save As and choose JPEG as the file type. Your graphics program will likely provide you with another dialog box through which you can control various JPEG options, such as compression. Figure 10.5 shows the Save as JPEG dialog box you’ll see when you save a JPEG in GIMP. You can see here that you can control the compression ratio for saving JPEG files by adjusting the Quality slider between 1 (low quali- ty, small file size) and 100 (high quality, large file size). FIGURE 10.5 GIMP allows you reduce file size while still retaining image quality by saving in the JPEG format. You might want to experiment a bit to see how various JPEG compression levels affect the quality of your images, but 85% quality (or 15% compres- sion) is generally a good compromise between file size (and therefore download speed) and quality for most photographic images. www.it-ebooks.info ptg Creating Banners and Buttons 151 Creating Banners and Buttons Graphics that you create from scratch, such as banners and buttons, require you to make considerations uniquely different from photographs. The first decision you need to make when you produce a banner or button is how big it should be. Most people accessing the web now have a com- puter with a screen that is at least 1024×768 pixels in resolution, if not con- siderably larger. For example, my screen is currently set at 1440×900 pixels. You should generally plan your graphics so that they will always fit within smaller screens (1024×768), with room to spare for scrollbars and margins. The crucial size constraint is the horizontal width of your pages because scrolling a page horizontally is a huge hassle and a source of confusion for web users. Vertically scrolling a page is much more acceptable, so it’s okay if your pages are taller than the minimum screen sizes. Assuming that you target a minimum resolution of 800×600 pixels, full- sized banners and title graphics should be no more than 770 pixels wide by 430 pixels tall, which is the maximum viewable area of the page after you’ve accounted for scrollbars, toolbars, and other parts of the browser window. Within a page, normal photos and artwork should be from 100 to 300 pixels in each dimension, and smaller buttons and icons should be 20 to 100 pixels tall and wide. Obviously, if you design for the 1024×768 reso- lution, you have more screen “real estate” to work with, but the size guide- lines for banners, buttons, and other supplementary graphics are still in effect. To create a new image in GIMP, go to File and choose New. The Create a New Image dialog box displays (see Figure 10.6). If you aren’t sure how big the image needs to be, just accept the default size of a 640×480. Or you can choose one of the other pre-determined sizes in the Template drop- down, such as Web banner common 468×60 or Web banner huge 728×90. Those two settings are indeed considered “common” and “huge” for web site banners. Otherwise, enter the width and height of the new image. TIP For many years, designing for 800×600 screen resolution has been the norm. Still keep that low number in mind, as many people do not open applica- tions in full-screen mode. However, designing for a base- line 1,024×768 screen resolu- tion is not a bad idea. www.it-ebooks.info ptg 152 HOUR 10: Creating Images for Use on the Web For the image’s background color, you should usually choose white to match the background that most web browsers use for web pages (although as you learned in the previous hour, that color can be changed).When you know that you’ll be creating a page with a back- ground other than white, you can choose a different background color for your image. Or you might want to create an image with no background at all, in which case you’ll select Transparency as the background color. When an image’s background is transparent, the web page behind the image is allowed to show through those areas of the image. In GIMP, select the background color for your new image by opening the Advanced Options in the Create a New Image dialog box. When you enter the width and height of the image in pixels and click OK, you are faced with a blank canvas—an intimidating sight if you’re as art- phobic as most of us! However, there are so many image creation tutorials (not to mention entire books) available to lead you through the process, I am comfortable leaving you to your own creative devices. This hour is all about introducing you to the things you want to keep in mind when creat- ing graphics for use in your sites. This hour does not necessarily teach you exactly how to do it, because being comfortable with the tool you choose is the first step to mastering them. FIGURE 10.6 You need to decide on the size of an image before you start working on it. www.it-ebooks.info ptg Reducing the Number of Colors in an Image 153 Reducing the Number of Colors in an Image One of the most effective ways to reduce the size of, and therefore the download time for, an image is to reduce the number of colors used in the image. This can drastically reduce the visual quality of some photographic images, but it works great for most banners, buttons, and other icons. You’ll be glad to know that there is a special file format for images with a limited number of colors; it’s called the Graphics Interchange Format (GIF). When you save an image as a GIF, you might be prompted to flatten layers or reduce the number of colors by converting to an indexed image, as those are requirements for GIFs, as shown in Figure 10.7. The dialog box will simply ask you to confirm these changes that the save process will do for you—do not concern yourself with understanding these options at this time, but read your software’s help file regarding layers and indexed col- ors for a full understanding. Remember, the GIF image format is designed for images that contain areas of solid colors, such as web page titles and other illustrated graphics; the GIF format is not ideal for photographs. TIP Dithering is a technique used by image-editing programs to simulate a color that isn’t in the color palette with alternat- ing pixels of two similar colors. For example, a dithered pink color would consist of alternat- ing pixels of red and white pix- els, which would give the gener- al impression of pink. Dithering can make images look better in some cases, but it should usu- ally be avoided for web page graphics. Why? It substantially increases the information com- plexity of an image, and that usually results in much larger file sizes and slower down- loads. FIGURE 10.7 When saving an image as a GIF, you might be prompted to convert it to an indexed color palette. PNG (pronounced “ping”) is another useful file format that is supported in all major web browsers. While the GIF image format allows you to specify a single transparent color, which means that the background of the web page will show through those areas of an image, the PNG format takes things a step further by allowing you to specify varying degrees of trans- parency. www.it-ebooks.info ptg 154 HOUR 10: Creating Images for Use on the Web Working with Transparent Images You might have seen web sites that use background colors or images in their container elements, but also have images present in the foreground that allow the background to show through parts of the foreground graph- ics. In these cases, the images in the foreground have portions which are transparent, so that the images themselves—which are always on a rectan- gular canvas—do not show the areas of the canvas in which the design does not occur. You’ll often want to use these types of partially transparent images to make graphics look good over any background color or back- ground image you might have in place. To make part of an image transparent, the image must be saved in the GIF or PNG file format. As mentioned previously in this lesson, most graphics programs that support the GIF format allow you to specify one color to be transparent, whereas PNG images allow for a range of transparency. Largely because of this transparency range, the PNG format is superior to GIF. All the latest web browsers already support PNG images. For more information on the PNG image format, visit http://www.libpng.org/pub/png/pngintro.html. The process of creating a transparent image depends on the type of image you are creating (GIF or PNG) and the graphics software you are using to create it. For instructions, look in your graphics program’s help files or type transparent images with [your program here] into your search engine. Creating Tiled Backgrounds Any GIF or JPEG image can be used as a background tile within a contain- er element. However, before you go off and create a tiled background, especially a highly patterned tiled background, ask yourself what that tiled background adds to the overall look and feel of your web site, and—more importantly—ask yourself if the text of the site can be read easily when placed over that pattern? Think about the web sites you frequent every day and consider the fact that few use tiled, patterned backgrounds on their entire pages. If you restrict your browsing to web sites for companies, products, sports teams, or other sites in which information (primarily text) is privileged, the num- ber of sites with tiled, patterned backgrounds will decrease even further. While the web affords everyone the right of individuality in design, if you www.it-ebooks.info ptg Creating Tiled Backgrounds 155 are creating a site for your business, you might want to avoid a highly pat- terned background with contrasting colored text. If you do use a tiled, patterned background image for your entire site, remember that tiled images look best when you can’t tell they’re tiled images. In other words, you know you have a good image when the top edge of a background tile matches seamlessly with the bottom edge, and the left edge matches with the right. Figures 10.8 and 10.9 show background tiles in use, both with seamless background, but with varying degrees of effectiveness. FIGURE 10.8 This is an example of a seamless background image whereby you can tell the background is tiled because you can see six identical shapes. FIGURE 10.9 This is also an example of a seam- less background image, only you can’t tell that it is tiled. www.it-ebooks.info ptg 156 HOUR 10: Creating Images for Use on the Web In Hour 11, you’ll learn how to place background images within your con- tainer elements. Despite my warnings in this section, there are actually times when background images can be powerful weapons in your design arsenal—just not when used as entire page backgrounds. Creating Animated Web Graphics The GIF image format allows you to create animated images that can be used to add some motion that will spice up any web page. Animated GIF images also transfer much faster than most of the video or multimedia files that are often used for similar effect. With GIMP, you can create animated GIFs by creating multiple layers within an image and then modifying the Animated GIF options when saving the file. Additionally, if you have a series of images you want to animate, you can use the free, web-based GIF animation service at Gickr (http://www.gickr.com/). The first step in creating a GIF animation is to create a series of images to be displayed one after the other—or a series of layers, depending on your particular software program. Each of these images is called a frame. By the way, this use of the word frame has nothing whatsoever to do with the frames you’ll learn about in Hour 13, “Working with Frames.” Instead, think of the frames like how movies or cartoons are put together—the images that you see on the screen are made up of many individual frames with slight differences in their appearance. Once you have your frames in mind, the process of tying them together is relatively simple—it’s the plan- ning stage that’s the most difficult. Take some time to sketch out the frames in storyboard fashion, especially if you plan to have more than just a few frames. After you know how your frames are going to fit together, use the Gickr service mentioned earlier in this section, or read the docu- mentation for your graphics software to learn its particular process for pulling it all together. TIP If you really want to use a back- ground tile but you just cannot seem to get the pattern you want, you can check out some of the hundreds of sites on the Internet offering public-domain background images that are free or inexpensive yet profes- sionally designed. www.it-ebooks.info ptg Summary 157 Summary In this hour, you learned the basics of preparing graphics for use on web pages. If nothing else, you learned that this is a very complex topic, and you learned just enough in this hour to whet your appetite. The examples in this hour used the popular (and free!) GIMP software package, but feel free to use the graphics software that best suits your needs. You learned how to crop, resize, and tweak image colors, and you learned about the different file formats. There are many considerations you must keep in mind when including graphics in your site, including graphic size and resolution and how to use transparency, animated GIFs, and tiled backgrounds. Q&A Q Instead of learning all this stuff myself, shouldn’t I just hire a graphics artist to design my pages? A This is a difficult question to answer, and it’s not because I have a con- flict of interest here—I work for a web development and design agency, so it’s in my best interest to recommend agencies. But an agency isn’t always the best solution. Hiring a graphic designer takes time and money. Additionally, there are many graphics artists who do not produce work suitable for the web—they are specifically print-based artists, and the print world is quite different than the online world. Also, hiring an individual who deems himself a graphics designer to create a web site might not play to the strengths of that particular graphics designer. In other words, he might be good at designing the graphical elements of a web site, but he might not be good as a content architect or at working with HTML and CSS. If your site is simply a personal site, a profession- al design might not be where you want to spend your money. But if your site is intended to promote a business, a product, a school, or anything else whereby your image is integral to your success, it’s worth your while (and money) to consult with web design professional. Q I’ve produced graphics for printing on paper. Are web page graphics any different? A Yes. In fact, many of the rules for print graphics are reversed on the Web. Web page graphics have to be low-resolution, while print graphics should be as high-resolution as possible. White washes out black on computer screens, while black bleeds into white on paper. Also, some- one might stop a web page from loading when only half the graphics have been downloaded. Try to avoid falling into old habits if you’ve done a lot of print graphics design. www.it-ebooks.info ptg 158 HOUR 10: Creating Images for Use on the Web Q I have a Windows AVI video clip. Can I turn it into a GIF animation? A Yes. Simply open the AVI file with software such as Animation Shop to convert it to a GIF animation. The software will give you the option to reduce the number of frames; it’s usually a good idea to sample every third frame or so to keep the file size down to reasonable proportions. You can also embed AVI files directly into web pages, as discussed in Hour 12, “Using Multimedia in Your Web Site.” Workshop The workshop contains quiz questions and activities to help you solidify your understanding of the material covered. Try to answer all questions before looking at the “Answers” section that follows. Quiz 1. You have a scanned picture of a horse that you need to put on a web page. How big should you make it? In what file format should you save it? 2. Your company logo is a black letter Z with a red circle behind it. What size should you draw or scan it? What file format should you save it for use on your web page? 3. Your business partner comes to you with a richly detailed back- ground graphic of dark forest foliage and wants you to use it as the background on your corporate site—with bold white text. What do you do? Answers 1. Depending on how important the image is to your page, you should make it as small as 100×40 pixels or as large as 300×120 pixels. The JPEG format, with about 85% compression, would be best. Of course, you could also provide a thumbnail link to a larger image that is viewed by itself. You’ll learn how to use images as links in the next hour. 2. About 100×100 pixels is generally good for a square logo, but a sim- ple graphic like that will compress very well. You could make it up to 300×300 pixels or more (and have the space in your template to position it appropriately—but that’s a pretty big square). Save it as an indexed GIF file since it contains very few colors. www.it-ebooks.info ptg Exercises 159 3. You tell him no and you refuse to allow him to have any input on design decisions in the future. Exercises . If you have an archive of company (or personal) photo prints, look through it to find a few that might enhance your web site. Scan them (or send them out to be scanned), so that you’ll have a library of digi- tal photos, ready to use on your pages. If you have digital files of photos taken on a digital camera, you can obviously skip the scan- ning step and jump straight into prepping the images for your web pages. . Before you start designing graphics for an important business site, try spicing up your own personal home page. This will give you a chance to learn GIMP (or give you a chance to use your graphics software) so that you’ll know what you’re doing when you tackle the task at work. www.it-ebooks.info ptg This page intentionally left blank www.it-ebooks.info ptg In Hour 10, “Creating Images for Use on the Web,” you learned how to find and create digital images for use in your web site. This hour shows you how easy it is to place those images in your web site. In this hour you’ll learn the HTML for placing and describing images in your site, how to align images, and how to use images as links or “maps” to other content. HOUR 11 Using Images in Your Web Site WHAT YOU’LL LEARN IN THIS HOUR: . How to place an image on a web page . How to describe images with text . How to specify image height and width . How to align images . How to turn images into links . How to use background images . How to use image maps Prepare Images for Use in Your Web Site You should get two or three images ready now so that you can try putting them on your own pages as you follow along with this hour. If you have some image files already saved in the GIF, PNG, or JPEG format (the filenames will end in .gif,.png, or .jpg), use those. It’s also fine to use any graphics you created while reading the preced- ing lesson. Search engines (such as Google) can become a gold mine of images by lead- ing you to sites related to your own theme. Search engines can also help you discover the oodles of sites specifi- cally dedicated to providing free and cheap access to reusable media collec- tions. Also, don’t forget Microsoft’s massive clip art library at the Office TRY IT YOURSELF ▼ Online Clip Art and Media web site, located at http://office.microsoft.com/ clipart/. Other valuable sources include Google Images (http://images.google.com/) and Flickr (http://www.flickr.com)— look for images using Creative Commons licenses that allow for free use with attribution. www.it-ebooks.info ptg 162 HOUR 11: Using Images in Your Web Site Placing Images on a Web Page To put an image on a web page, first move the image file into the same fold- er as the HTML file or in a directory named Images for easy organization. Insert the following HTML tag at the point in the text where you want the image to appear. Use the name of your image file instead of myimage.gif: ”My If your image file were in the images directory below the document root, you would use: ”My Both the src and the alt attributes of the tag are required in XHTML web pages. The src attribute identifies the image file and the alt attribute allows you to specify descriptive text about the image, the latter of which is intended to serve as an alternative to the image in the event that a user is unable to view the image. You’ll read more on the alt attrib- ute later, in the section “Describing Images with Text.” As an example of how to use the tag, Listing 11.1 inserts an image at the top of the page, before a paragraph of text. Whenever a web browser displays the HTML file in Listing 11.1, it automatically retrieves and dis- plays the image file as shown in Figure 11.1. Listing 11.1 Using the Tag to Place Images on a Web Page A Spectacular Yosemite View

                    A Spectacular Yosemite View

                    ”Half

                    Half Dome is a granite dome in Yosemite National Park, located in northeastern Mariposa County, California, at the eastern end of Yosemite Valley. The granite crest rises more than 4,737 ft (1,444 m) above the valley floor.

                    This particular view is of Half Dome as seen from Washburn Point.

                    NOTE It doesn’t matter to the web server, web browser, or end user just where you put your images, as long as you know where they are and as long as you use the correct paths in your HTML code. NOTE The tag also supports a title attribute that is used to describe an image. Unlike the alt attribute, the title attrib- ute is truly intended to provide an image description with the assumption that the image is visible. The alt attribute serves a more important pur- pose, and is put into play pri- marily when an image cannot be displayed, such as when a blind user is “viewing” a page using supplementary screen reading software. The alt attrib- ute is required but it’s a good idea to provide both alt and title attributes if you want to ensure that your images are all well-described. www.it-ebooks.info ptg Describing Images with Text 163 If you guessed that img stands for image, you’re right. And src stands for source, which is a reference to the location of the image file. As discussed earlier in the book, an image is always stored in a file separate from the text, even though it appears to be part of the same page when viewed in a browser. Just as with the tag used for hyperlinks, you can specify any com- plete Internet address in the src attribute of the tag. Alternatively, if an image is located in the same folder as the HTML file, you can specify just the filename. You can also use relative addresses, such as /images/birdy.jpg or ../smiley.gif. Describing Images with Text Each tag in Listing 11.1 includes a short text message, such as alt=”Half Dome”. The alt stands for alternate text, which is the message that appears in place of the image itself if it does not load. An image might not load if its address is incorrect, if the user has turned off automatic image downloading in her web browser preferences, or if the Internet connection is very slow and the data has yet to transfer. Figure 11.2 shows an example of alt text used in place of an image. FIGURE 11.1 When a web browser displays the HTML code shown in Listing 11.1, it renders the hd.jpg image. NOTE Theoretically, you can include an image from any web site within your own pages. In those cases, the image is retrieved from the other page’s web serv- er whenever your page is dis- played. You could do this, but you shouldn’t! Not only is it bad manners, because you are using the other person’s band- width for your own personal gain, it also can make your pages display more slowly. You also have no way of controlling when the image might be changed or deleted. If you are granted permission to republish an image from anoth- er web page, always transfer a copy of that image to your com- puter and use a local file refer- ence, such as instead of . This advice is not applicable, howev- er, when you host your images—such as photo- graphs—at a service specifical- ly meant as an image reposito- ry, such as Flickr (http://www.flickr.com/). Services like Flickr provide you with a URL for each image, and each URL includes Flickr’s domain in the address. www.it-ebooks.info ptg 164 HOUR 11: Using Images in Your Web Site Even when graphics have fully loaded and are visible in the web browser, the alt message typically appears in a little box (known as a tool tip) when- ever the mouse pointer passes over an image. The alt message also helps any user who is visually impaired (or is using a voice-based interface to read the web page). You must include a suitable alt attribute in every tag on your web pages, keeping in mind the variety of situations in which people might see that message. A very brief description of the image is usually best, but web page authors sometimes put short advertising messages or subtle humor in their alt messages; too much humor and not enough information is frowned upon, however. For small or unimportant images, it’s tempting to omit the alt message altogether, but it is a required attribute of the tag. This doesn’t mean your page won’t display properly, but it does mean you’ll be in violation of the latest XHTML standards. I recommend assign- ing an empty text message to alt if you absolutely don’t need it (alt=””), which is sometimes the case with small or decorative images. The title attribute is not required by the tag, but it functions simi- larly to the alt attribute; in fact, the title attribute supersedes the alt attribute for tool tips if both attributes are present. Knowing this, the best approach for describing images via text is to use both the alt attribute and the title attribute to provide relevant notation or helpful hints about the image that you think might be useful when viewed as a tool tip or via screen reader software. FIGURE 11.2 Users will see alt messages when images do not appear. www.it-ebooks.info ptg Aligning Images 165 Specifying Image Height and Width Because text moves over the Internet much faster than graphics, most web browsers display the text on a page before they display images. This gives users something to read while they’re waiting to see the pictures, which makes the whole page seem to load faster. You can make sure that everything on your page appears as quickly as possible and in the right places by explicitly stating each image’s height and width. That way, a web browser can immediately and accurately make room for each image as it lays out the page and while it waits for the images to finish transferring. For each image you want to include in your site, you can use your graph- ics program to determine its exact height and width in pixels. You might also be able to find these image properties by using system tools. For example, in Windows, you can see an image’s height and width by right- clicking on the image, selecting Properties, and then selecting Details. Once you know the height and width of an image, you can include its dimen- sions in the tag, like this: ”Fancy Aligning Images Just as you can align text on a page, you can align images on the page using special attributes. Not only can you align images horizontally, you also can align them vertically with respect to text and other images that surround them. Horizontal Image Alignment As discussed in Hour 5, “Working with Text Blocks and Lists,” you can use
                    ,
                    , and
                    to align an element to the center, to the right mar- gin, or to the left margin. These style settings affect both text and images and can be used within the

                    tag as well. Like text, images are normally lined up with the left margin unless a style=”text-align:center” or style=”text-align:right” setting indicates that they should be centered or right-justified. In other words, left is the default value of the text-align style property. TIP The height and width specified for an image don’t have to match the image’s actual height and width. A web browser will try to squish or stretch the image to display whatever size you specify. However, this is generally a bad idea because browsers aren’t particularly good at resizing images. If you want an image to display small- er, you’re definitely better off resizing it in an image editor. www.it-ebooks.info ptg 166 HOUR 11: Using Images in Your Web Site You can also wrap text around images by using the float style property directly within the tag. In Listing 11.2, aligns the first image to the left and wraps text around the right side of it, as you might expect. Similarly, aligns the second image to the right and wraps text around the left side of it. Figure 11.3 shows how these images align on a web page. There is no concept of floating an image to the center because there would be no way to determine how to wrap text on each side of it. Listing 11.2 Using text-align Styles to Align Images on a Web Page More Spectacular Yosemite Views

                    More Spectacular Yosemite Views

                    ”ElEl Capitan is a 3,000-foot (910 m) vertical rock formation in Yosemite National Park, located on the north side of Yosemite Valley, near its western end. The granite monolith is one of the world’s favorite challenges for rock climbers. The formation was named “El Capitan” by the Mariposa Battalion when it explored the valley in 1851.

                    ”TunnelTunnel View is a viewpoint on State Route 41 located directly east of the Wawona Tunnel as one enters Yosemite Valley from the south. The view looks east into Yosemite Valley including the southwest face of El Capitan, Half Dome, and Bridalveil Falls. This is, to many, the first views of the popular attractions in Yosemite.

                    NOTE The float style property is actually more powerful than described here and, in fact, applies to more than just images. You can use the float style property creatively to arrive at some interesting page layouts, as you’ll learn later in the book. www.it-ebooks.info ptg Aligning Images 167 Vertical Image Alignment Sometimes, you might want to insert a small image in the middle of a line of text; or you might like to put a single line of text next to an image as a caption. In either case, it would be handy to have some control over how the text and images line up vertically. Should the bottom of the image line up with the bottom of the letters, or should the text and images all be arranged so that their middles line up? You can choose between these and several other options: . To line up the top of an image with the top of the tallest image or let- ter on the same line, use . . To line up the bottom of an image with the bottom of the text, use . . To line up the middle of an image with the overall vertical center of everything on the line, use . . To line up the bottom of an image with the baseline of the text, use . All four of these options are used in Listing 11.3 and displayed in Figure 11.4. Four thumbnail images are now listed vertically down the page, along with descriptive text next to each image. Various settings for the vertical- align style property are used to align each image and its relevant text. FIGURE 11.3 Showing the image alignment from Listing 11.2. NOTE Notice the addition of padding in the style attribute for both tags used in Listing 11.2. This padding provides some “breathing room” between the image and the text—6 pixels on all four sides of the image. You will learn more about padding in Hour 13. NOTE The vertical-align style prop- erty also supports values of top and bottom, which can be used to align images with the overall top or bottom of a line of ele- ments regardless of any text on the line. www.it-ebooks.info ptg 168 HOUR 11: Using Images in Your Web Site Listing 11.3 Using vertical-align Styles to Align Text with Images Small But Mighty Spectacular Yosemite Views

                    Small But Mighty Yosemite Views

                    ”ElEl Capitan is a 3,000-foot (910 m) vertical rock formation in Yosemite National Park.

                    ”TunnelTunnel View looks east into Yosemite Valley.

                    ”UpperUpper Yosemite Falls are 1,430 ft and are among the twenty highest waterfalls in the world.

                    ”HangingHanging Rock, off Glacier Point, used to be a popular spot for people to, well, hang from. Crazy people.

                    TIP If you don’t include any align attribute in an tag, the bottom of the image will line up with the baseline of any text next to it. That means you never actually have to type style=”vertical-align:base- line” because it is assumed by default. However, if you specify a margin for an image and intend for the alignment to be a bit more exacting with the text, you might want to explicitly set the vertical-align attribute to text-bottom. Take a look at the last image shown in Figure 11.4 to see an example of the text appearing slightly below the image due to the image margin—this is a result of the baseline setting for vertical- align. FIGURE 11.4 Showing the vertical image align- ment options used in Listing 11.3. www.it-ebooks.info ptg Turning Images into Links 169 Turning Images into Links You probably noticed in Figure 11.1 that the image on the page is quite large, which fine in this particular example but isn’t ideal when you’re try- ing to present multiple images. It makes more sense in this case to create smaller image thumbnails that link to larger versions of each image. Then you can arrange the thumbnails on the page so that visitors can easily see all the content, even if they see only a smaller version of the actual (larger) image. Thumbnails are one of the many ways you can use image links to spice up your pages. To turn any image into a clickable link to another page or image, you can use the
                    tag that you used previously to make text links . Listing 11.4 contains the code for a modification of Listing 11.2—which already used thumbnails—to provide links to larger versions of the images. To ensure that the user knows to click the thumbnails, the image and some helper text is enclosed in a
                    , as shown in Figure 11.5. Experiment with Image Alignment Try adding some images to your web pages now and experiment with dif- ferent values of text-align, vertical-align, and float. To get you started, here’s a quick review of how to add a hypothetical fish image (fish.jpg) to any web page. 1. Copy the fish.jpg image file to the same directory as the HTML file (or leave the image in its current location and make sure you remem- ber where it is located). 2. With a text editor, choose where you want the image to appear in the text and add ”Brightto that location. 3. If you want the image to be centered, put
                    before the tag and
                    after it. To wrap text around the image, add style=”float:right” or style=”float:left” to the tag. And, finally, use the vertical-align style property directly within the tag to control the vertical alignment of the image with respect to other images and text next to it. 4. If you have time for a little more experimentation, try combining multiple images of various sizes using various vertical alignment settings. TRY IT YOURSELF ▼ www.it-ebooks.info ptg 170 HOUR 11: Using Images in Your Web Site Listing 11.4 Using Tumbnails for Effective Image Links More Spectacular Yosemite Views

                    More Spectacular Yosemite Views

                    ”El
                    click image to enlarge
                    El Capitan is a 3,000-foot (910 m) vertical rock formation in Yosemite National Park, located on the north side of Yosemite Valley, near its western end. The granite monolith is one of the world’s favorite challenges for rock climbers. The formation was named “El Capitan” by the Mariposa Battalion when it explored the valley in 1851.

                    ”Tunnel
                    click image to enlarge
                    Tunnel View is a viewpoint on State Route 41 located directly east of the Wawona Tunnel as one enters Yosemite Valley from the south. The view looks east into Yosemite Valley including the southwest face of El Capitan, Half Dome, and Bridalveil Falls. This is, to many, the first views of the popular attractions in Yosemite.

                    www.it-ebooks.info ptg Turning Images into Links 171 The code in Listing 11.4 uses additional styles that will be explained in more detail in Hours 14 and 15, but you should be able to figure out the basics: . The tags link these particular images to larger versions, which in this case are stored on an external server (at Flickr). . The
                    tags, and their styles, are used to align those sets of graph- ics and caption text (and also include some padding). Unless instructed otherwise, web browsers display a colored rectangle around the edge of each image link. Like text links, the rectangle usually appears blue for links that haven’t been visited recently or purple for links that have been visited recently—unless you specify different colored links in your style sheet. Because you seldom, if ever, want this unsightly line around your linked images, you should usually include style=”border:none” in any tag within a link. In this instance, the border:none style is made part of the style sheet entry for the img element because we use the same styles twice. When you click one of the thumbnail images on the sample page shown, the link is opened in the browser, as shown in Figure 11.6. FIGURE 11.5 Using thumbnails as links improves the layout of a page that uses large images. www.it-ebooks.info ptg 172 HOUR 11: Using Images in Your Web Site Using Background Images As you learned in the previous hour, you can use background images to act as a sort of “wallpaper” in a container element, so that the text or other images appear on top of this underlying design. The basic style properties that work together to create a background are: . background-color: specifies the background color of the element. While not image-related, it is part of the set of background-related properties. . background-image: specifies the image to use as the background of the element using the following syntax: url(‘imagename.gif’). . background-repeat: specifies how the image should repeat, both hori- zontally and vertically. By default (without specifying anything), background images will repeat both horizontally and vertically. Other options are: repeat (same as default), repeat-x (horizontal), repeat-y (vertical), and no-repeat (only one appearance of the graphic). . background-position: specifies where the image should be initially placed relative to its container. Options include: top-left, top-center, top-right, center-left, center-center, center-right, bottom-left, bot- tom-center, bottom-right, and specific pixel and percentage placements. When specifying a background image, you can put all of these specifica- tions together into one property, like so: body { background: #ffffff url(‘imagename.gif’) no-repeat top right; } FIGURE 11.6 Clicking a linked thumbnail image opens the target of the link. www.it-ebooks.info ptg Using Imagemaps 173 In the previous style sheet entry, the body element of the web page will be white and include a graphic named imagename.gif on the top right. Another use for the background property is the creation of custom bullets for your unordered lists. To use images as bullets, first define the style for the
                      tag as follows: ul { list-style-type: none; padding-left: 0; margin-left: 0; } Next, change the declaration for the
                    • tag to: li { background: url(mybullet.gif) left center no-repeat } Make sure that mybullet.gif (or whatever you name your graphic) is on the web server and accessible; in that case, all unordered list items will show your custom image rather than the standard filled disc bullet. We will return to the specific use of background properties in later lessons when using CSS for overall page layouts. Using Imagemaps Sometimes you might want to use an image as navigation, but beyond the simple button-based or link-based navigation that you often see in web sites. For example, perhaps you have a web site with medical information and you want to show an image of the human body that links to pages that provide information about various body parts. Or you have a web site that provides a world map users can click to access information about countries. You can divide an image into regions that link to different docu- ments, depending on where users click within that image. This is called an imagemap, and any image can be made into an imagemap. Why Imagemaps Aren’t Always Necessary The first thing you should know about imagemaps is that you probably won’t need to use them except in very special cases. It’s almost always eas- ier and more efficient to use several ordinary images that are placed direct- ly next to one another and provide a separate link for each image. For example, see Figure 11.7. This is a web page that shows 12 different corporate logos; this example is a common type of web page in the busi- ness world, one in which you give a little free advertisement to your part- www.it-ebooks.info ptg 174 HOUR 11: Using Images in Your Web Site ners. You could present these logos as one large image and create an imagemap that provides links to each of the 12 companies. Users could click each logo in the image to visit each company’s site. Or you could display the images on the page as in this example, and use 12 separate images—one for each company—with each image including a link to that particular company. FIGURE 11.7 Web page with 12 different logos; this could be presented as a sin- gle imagemap or divided into 12 separate pieces. Mapping Regions Within an Image To create any type of imagemap, you need to figure out the numerical pixel coordinates of each region within the image that you want to turn into a click- able link. These clickable links are also known as areas. Your graphics program might provide you with an easy way to find these coordinates. Or you might want to use a standalone imagemapping tool such as Mapedit FIGURE 11.8 An image that wouldn’t take well to being sliced up—better make it an imagemap. An imagemap is the best choice for an image that has numer- ous parts, is oddly arranged, or the design of the image itself might be too compli- cated to divide into separate images. Figure 11.8 shows an image that is best suit- ed as an imagemap. www.it-ebooks.info ptg Using Imagemaps 175 (http://www.boutell.com/mapedit/) or the online imagemap maker at http://www.image-maps.com/. In addition to helping you map the coordinates, these tools also provide the HTML code necessary to make the maps work. Using an image mapping tool is often as simple as using your mouse to draw a rectangle (or a custom shape) around the area you wish to be a link. Figure 11.9 shows the result of one of these rectangular selections as well as the inter- face for adding the URL and the title or alternate text for this link. Several pieces of information are necessary to creating the HTML for your imagemap: coordinates, target URL, title of link, and alternative text for the link. FIGURE 11.9 Using an imagemapping tool to create linked areas of a single graphic. Create Your Own Imagemap You’re more likely to remember how to make imagemaps if you get an image of your own and turn it into an imagemap as you continue with this hour: . For starters, it’s easiest to choose a fairly large image that is visually divided into roughly rectangular regions. . If you don’t have a suitable image handy, use your favorite graphics program to make one. Perhaps use a single photograph showing sev- eral people and use each person as an area of the imagemap. . Try a few different imagemapping tools to determine which you like best. Start with standalone software such as MapEdit (http://www.boutell.com/mapedit/) and move to the online imagemap maker at http://www.image-maps.com/. There are others; use the search engine of your choice to find variations on the “imagemap software” theme. TRY IT YOURSELF ▼ www.it-ebooks.info ptg 176 HOUR 11: Using Images in Your Web Site Creating the HTML for an Imagemap If you use an imagemap generator, you will already have the HTML neces- sary for creating the imagemap. However, it is a good idea to understand the parts of the code so that you can check it for accuracy. The following HTML code is required to start any imagemap: Keep in mind that you can use whatever name you want for the name of the tag, although it helps if you make it as descriptive as possible. Next, you’ll need an tag for each region of the image. Following is an example of a single tag that is used in the mapping-a-map imagemap example: ”Whitman This tag has five attributes, which you will use with every area you describe in an imagemap: . shape indicates whether the region is a rectangle (shape=”rect”), a cir- cle (shape=”circle”), or an irregular polygon (shape=”poly”). . coords gives the exact pixel coordinates for the region. For rectangles, give the x,y coordinates of the upper-left corner followed by the x,y coordinates of the lower-right corner. For circles, give the x,y center point followed by the radius in pixels. For polygons, list the x,y coor- dinates of all the corners in a connect-the-dots order. . href specifies the page to which the region links. You can use any address or filename that you would use in an ordinary link tag. . alt allows you to provide a piece of text that is associated with the shape. Most browsers (Firefox excluded) display this text in a small box when a user hovers his mouse over the shape. This text adds a subtle but important visual cue to users who might not otherwise realize that they are looking at an imagemap. Firefox correctly uses the title attrib- ute in addition to the alt attribute to provide a visual cue, which is why, as noted previously in this hour, you should use both attributes. Each distinct clickable region in an imagemap must be described as a sin- gle area, which means a typical imagemap consists of a list of areas. After coding the tags, you are done defining the imagemap, so wrap things up with a closing tag. www.it-ebooks.info ptg Using Imagemaps 177 The last step in creating an imagemap is wiring it to the actual map image. The map image is placed on the page using an ordinary tag. However, there is an extra usemap attribute that is coded like this: ”Native When specifying the value of the usemap attribute, use the name you put in the id of the tag (and don’t forget the # symbol). Also include the style attribute to specify the height and width of the image and to turn off the border around the imagemap, which you might or might not elect to keep in imagemaps of your own. Listing 11.5 shows the complete code for a sample web page containing the map graphic, its imagemap and a few mapped areas. Listing 11.5 Defining the Regions of an Imagemap with and Tags Testing an Imagemap

                      Testing an Imagemap

                      Click on a logo to go to the county’s web site.
                      ”Native

                      ”Whitman ”Santa ”Mifflin NOTE If you’re a stickler for details, you might have noticed—check out the first few lines of code— that this web page is coded as an XHTML 1.0 document, as opposed to the XHTML 1.1 used with most of the other examples in the book. This is done because some browsers (Internet Explorer, for one) are lagging in their support of a sin- gle XHTML 1.1 change in how imagemaps are used. This change is specific to the usemap attribute, which in XHTML 1.1 doesn’t require the # symbol in front of the map name. In fact, the # symbol isn’t allowed at all in XHTML 1.1. The # symbol is, however, allowed in XHTML 1.0, so to satisfy current web browsers and still provide you with a valid web page, this particular exam- ple uses XHTML 1.0. www.it-ebooks.info ptg 178 HOUR 11: Using Images in Your Web Site Figure 11.10 shows the imagemap in action. Notice in the bottom of your browser window that your browser (in this example, Firefox) displays the link address for whatever area the mouse is hovering over. Additionally, when you hover the mouse over an area, the alt or title text for that area—in this example, Whitman County—is displayed on the imagemap. FIGURE 11.10 The imagemap defined in Listing 11.5 as it displays on the web page. NOTE There is a method of producing mapped images that relies solely on CSS and not the HTML tag. You will learn more about this in Hour 16, “Using CSS to Do More With Lists.” www.it-ebooks.info ptg Summary 179 Summary This hour has shown you how to use the tag to place images on your web pages. You learned how to include a short text message that appears in place of the image as it loads and also appears whenever users move the mouse pointer over the image. You also learned how to control the horizontal and vertical alignment of each image and how to wrap text around the left or right of an image. You also learned how to use images as links—either by using the
                      tag around the images or by creating imagemaps. You also learned a little bit about how to use images in the background of container elements. Table 11.1 summarizes the attributes of the tag covered in this hour, along with relevant style properties. Table 11.1 HTML Tags and Attributes Covered in Hour 11 Tag/Attribute Function Places an image file within the page. A client-side imagemap referenced by . Includes one or more tags. Defines a clickable link within a client- side imagemap. Attributes src=”address” The address or filename of the image. alt=”altdescription” An alternative description of the image that is displayed in place of the image, primarily for users who can’t view the image itself. title=”title” A text message that is displayed as an image title, typically in a small pop- up box (tool tip) over the image. width=”width” The width of the image (in pixels). height=”height” The height of the image (in pixels). style=”border:attributes” Gets rid of the border around the image if the image is serving as a link. style=”vertical-align:alignment” Aligns the image vertically to text-top, top, text-bottom, bottom, middle,or baseline. www.it-ebooks.info ptg 180 HOUR 11: Using Images in Your Web Site Table 11.1 HTML Tags and Attributes Covered in Hour 11 Tag/Attribute Function style=”float:float” Floats the image to one side so text can wrap around it. Possible values are left, right, and none (default). usemap=”name” The name of an imagemap specifica- tion for client-side image mapping. Used with and . shape=”value” Within the tag, specifies the shape of the clickable area. Valid options for this attribute are rect, poly, and circle. coords=”values” Within the tag, specifies the coordinates of the clickable region within an image. Its meaning and set- ting vary according to the type of area. href=”linkurl” Within the tag, specifies the URL that should be loaded when the area is clicked. Q&A Q How long can I make a message that I put after alt= in an tag? A Theoretically, as long as you want. For practicality, you should keep the message short enough that it fits in a smaller space than the image itself. For big images, 10 words might be fine; in some cases, I’ve even seen web page authors include a small paragraph of text. For small images, a single word is best. Q I used the tag just as you advised, but when I view the page, all I see is a little box with an × or some shapes in it. What’s wrong? A The broken image icon you’re seeing can mean one of two things: Either the web browser couldn’t find the image file or the image isn’t saved in a format the browser recognizes. To solve these problems, first check to make sure that the image is where it is supposed to be. If it is, then open the image in your graphics editor and save it again as a GIF, JPG, or PNG format. www.it-ebooks.info ptg Workshop 181 Q What happens if I overlap areas on an imagemap? A You are allowed to overlap areas on an imagemap. Just keep in mind that when determining which link to follow, one area will have prece- dence over the other area. Precedence is assigned according to which areas are listed first in the imagemap. For example, the first area in the map has precedence over the second area, which means that a click in the overlapping portion of the areas will link to the first area. If you have an area within an imagemap that doesn’t link to anything (known as a “dead” area), you can use this overlap trick to deliberately prevent this area from linking to anything. To do this, just place the dead area before other areas so that the dead area overlaps them, and then set its href attribute to “”. Workshop The workshop contains quiz questions and activities to help you solidify your understanding of the material covered. Try to answer all questions before looking at the “Answers” section that follows. Quiz 1. How would you insert an elephant.jpg image file at the very top of a web page? 2. How would you make the word Elephant display whenever the actual elephant.jpg image couldn’t be displayed by a web browser? 3. You want to create an imagemap of a 200×200-pixel image named quarters.gif. When viewers click the upper-left quarter of the image, you want them to get a page named topleft.html. When they click the upper-right quarter, you want them to get topright.html. Clicking the lower-left quarter should bring up bot- tomleft.html, and the lower-right panel should lead to bottom- right.html. What HTML would you use to implement this as an imagemap? Answers 1. Copy the image file into the same directory folder as the HTML text file. Immediately after the tag in the HTML text file, type

                      ””

                      . 2. Use the following HTML: ”elephant” www.it-ebooks.info ptg 182 HOUR 11: Using Images in Your Web Site 3. Create the following imagemap: ”top ”top ”bottom ”bottom ”quarters” Exercises . Practicing any of the image placement methods in this lesson will go a long way toward helping you determine the role that images can, and will, play in the web sites you design. Using a few sample images, practice using the float style to place images and text in rela- tion to one another. Remember the possible values for float are left, right, and none (default). . Image alignment is also an important aspect of good visual web design. Using a few sample images, practice using the vertical-align style to place images and text in relation to one another. Remember the possible values for image-align are text-top, top, text-bottom, bot- tom, middle, and baseline. www.it-ebooks.info ptg The term multimedia encompasses everything we see and hear on a web page: audio, video, and animation, as well as static images and text. In pre- vious hours, you learned how to use images and text, so in this hour, you’ll learn about including the other types of multimedia in your web sites. You won’t learn how to create any particular audio, video, or animation, but you will learn how to include such files in your site, through either linking or embedding the content. Before even thinking about including multimedia in your site, remember that not every user has devices that will play your media type, nor do all users have broadband Internet connections which allow these large files to transfer quickly. Always warn your visitors that the links they click will take them to multimedia files, and offer them the choice to view or listen to the content—don’t force the files upon them. HOUR 12 Using Multimedia in Your Web Site WHAT YOU’LL LEARN IN THIS HOUR: . How to link to multimedia files . How to embed multimedia files . Additional tips for using multimedia Create or Find some Multimedia to Use in Your Web Site Before you learn how to place multimedia on your web pages, you need to have some multimedia content to start with. Creating multimedia of any kind can be a challenging and complicated task. If you’re planning to create your own content from scratch, you’ll need far more than this book to become the next crackerjack multimedia developer. After you have some content, however, this hour will show you how to place your new creations into your web pages. For those of us who are artistically challenged, several alternative ways to obtain useful multimedia assets are available. Aside from the obvious (such as hiring an artist), here are a few suggestions: . Much of the material on the Internet is free. Of course, it’s still a good idea to double-check with the author or current owner of the TRY IT YOURSELF ▼ www.it-ebooks.info ptg 184 HOUR 12: Using Multimedia in Your Web Site Linking to Multimedia Files The simplest and most reliable option for incorporating a video or audio file into your web site is to simply link it in with
                      , exactly as you would link to another HTML file. For example, the following line could be used to offer a MOV video of a hockey game: View the hockey video clip. When the user clicks the words View the hockey video clip., the hockey.mov QuickTime video file is transferred to her computer from your web server. Whichever helper application or plug-in she has installed automatically starts as soon as the file has finished downloading. If no compatible helper or plug-in can be found, the web browser will offer her a chance to down- load the appropriate plug-in or save the video on her hard drive for later viewing. TRY IT YOURSELF▼ Create or Find some Multimedia to Use in Your Web Site content; you don’t want to be sued for copyright infringement. In addition, various offices of the U.S. government generate content which, by law, belongs to all Americans. (For example, any NASA footage found online is free for your use.) . Many search engines (google.com, yahoo.com, lycos.com, and so on) have specific search capabilities for finding multimedia files. As long as you are careful about copyright issues, this can be an easy way to find multimedia related to a specific topic. A simple search for sam- ple Flash animations, sample QuickTime movie, or sample audio files will produce more results than you can handle. . If you are creatively inclined, determine the medium you like most— for some of you it might be video production, others may enjoy audio production, and still others might want to dabble in animation. Once you have determined a starting point, look into the various types of software which will enable you to create such artistic mas- terpieces. Many companies provide multimedia software, such as Adobe (http://www.adobe.com/) and Apple (http://www.apple.com/) to name but two. NOTE Regardless of the specific media types shown in this hour, the procedures shown for incor- porating multimedia into your web pages will be similar no matter which media format you choose. www.it-ebooks.info ptg Linking to Multimedia Files 185 Listing 12.1 contains the code for a web page that uses a simple image link to play a video in Windows Media file format. In addition to the image link, a link is also placed within the text to provide context for the user. Listing 12.1 Using the to Link an Image to a Windows Media Video Fun in the Pond

                      Fun in the Pond

                      ”Pond Michael’s backyard pond is not only a fun hobby but also an ongoing home improvement project that is both creative and relaxing. He has numerous fish in the pond, all Koi from various places as far as Japan, Israel, and Australia. Although they don’t bark, purr, or fetch anything other than food, these fish are his pets, and good ones at that. You can click here or on the animated graphic on the left to see a movie clip of some fish in the pond.

                      This code simply uses the projector.gif animated GIF image as a link to the pond.wmv video clip. Figure 12.1 shows the pond sample page with the projector image in view. When the image is clicked, the Windows Media Player is invoked and begins to play the movie. NOTE In case you’re unfamiliar with helper applications (helper apps for short), they are the external programs that a web browser calls on to display any type of file it can’t handle on its own. Generally, the helper application associated with a file type is called on whenever a web browser can’t display that type of file on its own. Plug-ins are a special sort of helper application installed directly into a web browser and they allow you to view multime- dia content directly within the browser window. www.it-ebooks.info ptg 186 HOUR 12: Using Multimedia in Your Web Site To view the video, you need only to click the animated projector (or the text link in the paragraph). This action results in the browser either playing the video with the help of a plug-in (if one is found that can play the clip) or deferring to a suitable helper application. If you change the link from pond.wmv (Windows Media) to pond.mov (QuickTime), your browser handles the link differently. Instead of launch- ing another program, the QuickTime plug-in allows you to view the movie clip directly in the browser window (see Figure 12.2). FIGURE 12.1 The projector.gif animated GIF image is used as an image link to a Windows Media file that launch- es an external helper application. FIGURE 12.2 When you follow the image link, the pond.mov QuickTime movie is played using the QuickTime brows- er plug-in. www.it-ebooks.info ptg Embedding Multimedia Files 187 As you might have guessed, this approach of using a simple link to play multimedia files offers the best backward compatibility because the brows- er bears all the responsibility of figuring out how to play a multimedia clip. The downside to this is that you don’t have much control over how a clip is played, and you definitely can’t play a clip directly in the context of a page. Embedding Multimedia Files XHTML contains a standard tag that is the preferred way to embed multimedia of any kind in a web page. This tag is used instead of the old tag that you might still see in some HTML source code. Embedding a multimedia file into a page produces a set of software con- trols that allow the file to be played directly—no secondary window is nec- essary, and there’s no need to navigate away from the page you are on. Following is code to embed the pond video, which you saw earlier, using the tag by itself: This code isn’t too terribly complicated when you consider that it literally embeds a video directly into your web page (see Figure 11.3). The messiest part of the code is the classid attribute of the tag, which is set to a long alphanumeric code. This code is the “global ID” for Windows Media Player, which means that you’re telling the tag to embed Windows Media Player on the page to play the video clip. You can just copy and paste this code into your own web pages. NOTE If your browser has no support for QuickTime, you can down- load the QuickTime player free from Apple at http://www.apple.com/quick- time/. Even if you do have QuickTime installed, some browsers might still play QuickTime movies differently based on whether a plug-in is installed. For example, on my Windows computer, Internet Explorer and Firefox both play QuickTime movies directly in the browser window via a plug- in, whereas Opera launches QuickTime as a helper applica- tion. NOTE It’s important to note that Windows Media Player is a sophisticated enough media player that it automatically streams multimedia files, which means that it begins playing them after loading only the first few seconds of content. The idea is that the rest of the con- tent is loaded in the back- ground while you’re watching or listening to earlier portions. The result is that visitors don’t have to wait through long download times when viewing or listening to your multimedia clips. www.it-ebooks.info ptg 188 HOUR 12: Using Multimedia in Your Web Site The width and height attributes of the tag determine the size of the embedded Windows Media Player window. Some browsers will automati- cally size the embedded player to fit the content if you leave these attrib- utes off, whereas others won’t show anything at all. Play it safe by setting them to a size that suits the multimedia content being played. There are four tags within the tag that are responsible for additional details about how the clip is to be played. Each tag has two attributes, name and value, which are responsible for associating data (value) with a particular setting (name). In this example, the URL for the media clip is set to pond.wmv. The third parameter, uiMode, determines which buttons and user interface options are made available by Windows Media Player—full indicates that all user interface features are enabled, such as the control buttons and volume slider. Finally, the autoStart parameter is set to false so that the video clip does not automatically start playing when the page is opened in a browser. The type parameter is perhaps the trickiest. It identifies the type of media being displayed, which in this case is a Windows Media Video (WMV) file. This media type must be specified as one of the standard Internet MIME types. FIGURE 12.3 The tag allows you to embed a video clip on a web page while specifying which media play- er is to play it. www.it-ebooks.info ptg Embedding Multimedia Files 189 A MIME type is an identifier for uniquely identifying different types of media objects on the Internet. MIME stands for Multipurpose Internet Mail Extensions, and this name comes from the fact that MIME types were orig- inally used to identify email attachments. These MIME types should be used in the type attribute of the tag to identify what kind of multi- media object is being referenced in the data attribute. Following are the MIME types for several popular sound and video for- mats you might want to use in your web pages: . WAV Audio—audio/x-wav . AU Audio—audio/basic . MP3 Audio—audio/mpeg . MIDI Audio—audio/midi . WMA Audio—audio/x-ms-wma . RealAudio—audio/x-pn-realaudio-plugin . AVI—video/x-msvideo . WMV—video/x-ms-wmv . MPEG Video—video/mpeg . QuickTime—video/quicktime Listing 12.2 shows the relevant code for the pond web page, where you can see the tag as it appears in context. Listing 12.2 Using an Tag to Directly Embed a WMV Video Clip Fun in the Pond

                      Fun in the Pond

                      www.it-ebooks.info ptg 190 HOUR 12: Using Multimedia in Your Web Site Listing 12.2 Using an Tag to Directly Embed a WMV Video Clip

                      Michael’s backyard pond is not only a fun hobby but also an ongoing home improvement project that is both creative and relaxing.

                      He has numerous fish in the pond, all Koi from various places as far as Japan, Israel, and Australia. Although they don’t bark, purr, or fetch anything other than food, these fish are his pets, and good ones at that.

                      You might notice that there’s some extra code that didn’t appear in the ear- lier tag example. Unfortunately, as discussed earlier in the hour, not all web browsers are entirely consistent in their support of the tag. For this reason, it is necessary to include an tag within the tag to account for browser inconsistencies. This isn’t an ideal solu- tion, but it’s all we have while browser vendors continue to lag behind prevailing standards. If you pay close attention, you’ll notice that the tag contains all the same information as the tag. The tag is a bit more complex than what is revealed here. However, you don’t need to know how to use the more advanced facets of the tag just to play multimedia content. In other words, it isn’t important for you to become a multimedia guru in order to share some multimedia clips on your web pages. Additional Tips for Using Multimedia Before you add video, audio, or animations to your web site, first ask yourself if you really should. When you use these types of multimedia, be sure to do so for a reason. Gratuitous sound and video, just like gratuitous images, can detract from your overall message. Then again, if your mes- sage is “Look at the videos I have made” or “Listen to my music and download some songs,” then multimedia absolutely must play a role in your web site. NOTE Because the tag is not supported in XHTML, it will prevent your pages from validat- ing. Unfortunately, there really is no workaround for this prob- lem—we’ll just have to wait for browsers to fully support the tag by itself or move to the element of HTML 5. NOTE Video files aren’t the only media files you can include within your web site using the and tags. Adding any multimedia file will follow the same process. To determine exactly which classid and codebase attributes to use, as well as additional parame- ters (in the tags), use your search engine to look up something like object embed mediatype where medi- atype is Real Audio, QuickTime, Flash, or whatever you want. www.it-ebooks.info ptg Additional Tips for Using Multimedia 191 Here are a few additional tips to keep in mind: . Don’t include multimedia in a page and set it to automatically play when the page loads. Always give users the option to start (and stop) your sound or video. . When possible, give users a choice of multimedia players. Don’t limit yourself to multimedia content playable by only one type of player on only one operating system. . Multimedia files are larger than the typical graphics and text files, which means you need to have the space on your web server to store them, as well as the bandwidth allotment to transfer them to whomever requests them via your web site. . If your site is entirely audio or video and offers very little by way of text or graphics, understand that a certain segment of your audience won’t see or hear what you want to present because of the limita- tions of their system or bandwidth. Provide these users with addi- tional options to get your information. . Leverage free online video hosting services, such as YouTube (http://www.youtube.com/). Not only does YouTube provide storage for your video clips, it will provide you with the code necessary to embed the video in your own web page. For example, Figure 12.4 shows the YouTube page for the cutest puppy in the world. If you copy and paste the text from the “Embed” area shown in the figure, you would get the following: You could then insert the code into your web page. www.it-ebooks.info ptg 192 HOUR 12: Using Multimedia in Your Web Site Summary In this hour, you’ve learned how to embed video and sound into a web page. You learned how to use a simple link to a multimedia file, which is the most broadly supported but least flexible option for playing media content. You then learned how to use the tag to embed a media player directly in a web page. Not only that, you learned that for maxi- mum browser compatibility, it helps to assist the tag with the tag. The and tags can be used to include a vast array of media types, including WAV, MP3, RealAudio, and MIDI files— not to mention AVI, WMV, and QuickTime videos, to name just a few. Table 12.1 summarizes the tags discussed in this hour. FIGURE 12.4 YouTube provides storage of your video files as well as links and code for use in your own pages. www.it-ebooks.info ptg Summary 193 Table 12.1 HTML Tags and Attributes Covered in Hour 12 Tag/Attribute Function Inserts images, videos, Java applets, ActiveX controls, or other objects into a doc- ument. … Runtime settings for an object, such as the width and height of the area it occupies on a page. Attributes name=”name” A named parameter property. value=”value” The value associated with a named parame- ter property. Embeds a multimedia file to be read or dis- played by a plug-in application; this tag is technically deprecated but still useful due to browsers not fully supporting the tag yet. Attributes width=”width” The width of the embedded object in pixels. height=”height” The height of the embedded object in pixels. type=”mimetype” The MIME type of the multimedia content. src=”mediaurl” The URL of the file to embed. controls=”controls” The configuration of the user input controls for the media player; use all to enable all controls. loop=”loop” Play the media clip once or loop it repeatedly; set to true or false. autostart=”autostart” Play the media clip upon opening the page; set to true or false. pluginspage=”pluginurl” The URL of the plug-in required to play the media clip. www.it-ebooks.info ptg 194 HOUR 12: Using Multimedia in Your Web Site Q&A Q I hear a lot about streaming video and audio. What does that mean? A In the past, video and audio files took minutes and sometimes hours to retrieve through most modems, which severely limited the inclusion of video and audio on web pages. The goal that everyone is moving toward is streaming video or audio, which plays while the data is being received. In other words, you don’t have to completely download the clip before you can start to watch it or listen to it. Streaming playback is now widely supported through most media play- ers, in both standalone versions and plug-ins. When you embed a media object using the tag, the underlying media player auto- matically streams the media clip if streaming is supported in the player. Q How do I choose an audiovisual file format among QuickTime, Windows AVI/WAV, RealVideo/RealAudio, and MPEG? Is there any sig- nificant difference among them? A QuickTime is the most popular video format among Macintosh users, though QuickTime players are available for Windows as well. Similarly, AVI/WMV and WAV/WMA are the video and audio formats for Windows users, but you can get players for the Macintosh that support these for- mats. MPEG is another popular audio and video standard. MPEG-3 (MP3 is already extremely popular as the high-fidelity audio standard of choice). One other audio format that is based on MPEG is Apple’s AAC format, which might be more familiar to you as the native iTunes music format. If most of your audience uses Windows, use AVI/WMV for video and WAV/WMA or MP3 for audio. If your audience includes a significant number of Macintosh users, use QuickTime or RealVideo/RealAudio, or at least offer some alternative. MP3 is also a viable option for Mac audio. If cross-platform compatibility is essential, consider going specifi- cally with MP3 for audio or RealVideo/RealAudio—although only those who download special software from http://www.real.com/player/ will be able to see RealVideo/RealAudio clips. www.it-ebooks.info ptg Workshop 195 Workshop The workshop contains quiz questions and activities to help you solidify your understanding of the material covered. Try to answer all questions before looking at the “Answers” section that follows. Quiz 1. What’s the simplest method to provide access to a video on your web site for the widest possible audience? 2. What HTML would you use to embed a video file named myvideo.avi into a web page so that the users of all major web browsers will be able to see it? The video requires an area on the page that is 320[ts]305 pixels in size. 3. How would you code a tag within an tag so that a media clip is played repeatedly? Answers 1. Just link to it: my video 2. Because the video clip is in a Microsoft format (AVI), you should embed a Windows Media player object using the following HTML code: 3. www.it-ebooks.info ptg 196 HOUR 12: Using Multimedia in Your Web Site Exercises . Try your hand at creating your own video clip and embedding it in a web page, or find some freely available clips from the web and prac- tice placement within your text. . The techniques and tags covered in this hour for embedding media also work with Flash files. To find out how you can use Flash to put interactive animations in your web pages, check out the Flash home page at http://www.adobe.com/products/flash/. www.it-ebooks.info ptg You might have visited web sites in which the browser window seemingly allowed you to move between several different pages. The truth is that the browser really was allowing you to view several pages at once by separat- ing the browser window into regions that contain separate web pages; each region is known as a frame. Of course, from the user’s perspective, everything comes together to form a single window of web content, but there are separate pages at work. What Are Frames? A frame is a rectangular region within the browser window that displays a web page alongside other pages in other frames. At first glance, Figure 13.1 might look like an ordinary web page, but it is actually two separate HTML pages, both displayed in the same web browser window. Each page is displayed in its own frame, arranged horizontally and separated by the horizontal bar. HOUR 13 Working with Frames WHAT YOU’LL LEARN IN THIS HOUR: . How to build a frameset . How to link between frames and windows . How to use inline frames FIGURE 13.1 Frames allow more than one web page to be displayed at once. www.it-ebooks.info ptg 198 HOUR 13: Working with Frames If frames are used, typically they are used to create a framed site that takes advantage of a static set of navigational links; you can see these links in the top frame of Figure 13.1. When one of the links in this example is clicked, the top frame will not change; a new page will be loaded and displayed in the bottom frame (see Figure 13.2). FIGURE 13.2 Clicking Products brings up a new bottom page but leaves the top frame the same. You should be aware that frames have long been a vexed issue in web design. The advantages have never really outweighed the disadvantages, yet due to differences in browser support for HTML and CSS standards, frames were seen as a way to achieve certain goals despite their shortcom- ings. As a web developer, I do not recommend the use of frames for the following reasons: . Frames go against the fundamental concept of the Web, which is the hypertextual connection between individual instances of web content that can be accessed via a single web address (URL). . Printing parts of a framed site are very difficult; unless you have clicked on the specific frame you wish to print, and select “Print this Frame” from a context menu (if one is available), all that will print is the frameset itself, which will have no content in it. . If a frame lacks proper coding, or if it has proper coding but the code is used for nefarious purposes, a user could get stuck inside a framed site unable to view external content outside of the frame. www.it-ebooks.info ptg Building a Frameset 199 . Frames have been used historically in lieu of standard, professional, accessible methods of web development and design. There is no rea- son to choose the lesser option when the better option of CSS layout is available. . For these (and other) reasons, frames have been removed from the HTML 5 standard. The antiquated , , and tags will simply not be available in the future. Despite these shortcomings, you will learn in this hour how to create a very simple framed site. It is quite likely that you will still encounter framed sites, and you might need to know how to re-create the “look and feel” of the site but without using frames. In that case, it is important to understand how frames are constructed so you can successfully decon- struct them. Additionally, you will learn about a type of frame—the <iframe>—that does serve an important purpose and will still be present in HTML 5. Later in this book, you will learn how to use XHTML and CSS to produce the same functionality only without using the frames. For now, follow along the construction of this simple framed site so that you can learn the process should you ever have to undo one and re-create it a different way. Building a Frameset This section shows you how to create the simple framed site shown in Figures 13.1 and 13.2. The contents of each frame were created as ordinary HTML pages. The pages are top.html (for the navigation), home.html, products.html, services.html, and contact.html. These pages don’t contain any tags you haven’t already seen in other hours. A special page known as a frameset document was used to put the pages together; in this case, that document is index.html. Creating a Frameset Document A frameset document is an HTML page that instructs the web browser to split its window into multiple frames and specifies which web page should be displayed in each frame. A frameset document actually has no content. It only tells the browser which other pages to load and how to arrange them in the browser www.it-ebooks.info ptg 200 HOUR 13: Working with Frames window. Listing 13.1 shows the frameset document for the sample framed site shown in Figure 13.1 and Figure 13.2. Listing 13.1 Frameset Document for the Site Shown in Figure 13.1 <?xml version=”1.0” encoding=”UTF-8”?> <!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” xml:lang=”en”> <head> <title>Sample Framed Site</title> </head> <frameset rows=”50,*”> <frame src=”top.html” name=”top” /> <frame src=”home.html” name=”main” /> <noframes> <body> <h1>Sample Framed Site</h1> Your browser does not support frames. Sorry! </body> Listing 13.1 uses a tag instead of a tag. No tags that would normally be contained in a tag can be within the tag. The tag in this example includes a rows attribute, meaning that the frames should be arranged on top of each other like the horizontal rows of a table. If you want your frames to be side by side, use a cols attribute (instead of a rows attribute). You must specify the sizes of the rows or cols, either as precise pixel values or as percentages of the total size of the browser window. You can also use an asterisk (*) to indicate that a frame should fill whatever space is avail- able in the window. If more than one frame has an * value, the remaining space will be divided equally between them. In Listing 13.1, splits the window vertically into two frames. The top frame will be exactly 50 pixels tall and the bottom frame will take up all the remaining space in the window. The top frame contains the document top.html (see Listing 13.2) and the bottom frame contains home.html (see Listing 13.3). NOTE It’s important to notice that the DTD used in this sample page is not the familiar XHTML 1.1 DTD that you’ve been using throughout the book. This is because frames are not sup- ported in the standard XHTML 1.1 DTD. Therefore, to validate a page with frames, you must instead use the XHTML 1.0 Frameset DTD, which is a spe- cial DTD designed just for pages that use frames. www.it-ebooks.info ptg Building a Frameset 201 Listing 13.2 The top.html Navigation Bar for the Sample Framed Site Sample Framed Site Listing 13.3 The home.html Single Content Frame Within the Sample Framed Site Sample Framed Site

                      Sample Framed Site: Home

                      This is an example of the “home” page.

                      In this example, the top navigation frame has a fixed height of 50 pixels. But because you can’t predict the size of the window in which users will TIP After the framesets in Listing 13.1, there is a complete web page between the and tags. Notice that this doesn’t appear at all in Figure 13.1 or Figure 13.2. All web browsers that support frames will ignore anything between the and tags. All major browsers these days support frames, so the issue of frames compatibility is much less significant now than in years past. Even so, it’s easy enough to include the tag and cover the few users who might still use ancient browsers—if you use frames at all, that is. NOTE The pages in Listing 13.2 and Listing 13.3 use the XHTML 1.0 Transitional DTD. XHTML 1.1 DTD is newer and much stricter, but frames require you to stick with XHTML 1.0 for validation purposes, so it made sense to also use XHTML 1.0 for the pages that appear within the frames. www.it-ebooks.info ptg 202 HOUR 13: Working with Frames view your web page, it is often convenient to use percentages rather than exact pixel values to dictate the size of the rows and columns. For example, to make a left frame 20% of the width of the browser window with a right frame taking up the remaining 80%, you would type the following : <frameset cols=”20%,80%”> Whenever you specify any frame size in pixels, it’s a good idea to include at least one frame in the same frameset with a variable (*) width so that the document can grow to fill a window of any size. Adding Individual Frames Within the <frameset> and </frameset> tags, you should have a <frame /> tag indicating which HTML document to display in each frame. Note that if you have fewer <frame /> tags than the number of frames defined in the <frameset> tag, any remaining frames will be left blank. Include an src attribute in each <frame> tag with the address of the web page to load in that frame. You can put the address of an image file, instead of a web page, if you just want a frame with a single image in it. Linking Between Frames and Windows The real power of frames begins to emerge when you give a frame a unique name with the name attribute in the <frame /> tag. You can then make any link on the page change the contents of that frame by using the target attribute in an <a> tag. For example, Listing 13.1 includes the follow- ing tag: <frame src=”home.html” name=”main” /> This code displays the home.html page in that frame when the page loads and names the frame “main”. In the code for the top frame, which is shown in Listing 13.2, you will see the following link: <a style=”color:#FFFFFF;” href=”services.html” target=”main”>SERVICES</a> When the user clicks this link, services.html is displayed in the frame named main (the lower frame). If the target=”main” attribute had been left out, the services.html page would be displayed in the current (top) frame instead. NOTE Technically speaking, the name tag is outdated and has been replaced by the id tag. However, current web browsers still rely on name instead of id when it comes to identifying frames as targets and the use of name is still valid XHTML. So, for now, you need to stick with the name attribute when identify- ing frames. Of course, it would- n’t hurt to use both attributes. www.it-ebooks.info ptg Linking Between Frames and Windows 203 To save space, I haven’t provided a listing of the services.html page; it’s just a regular web page with no special frame-related features. You can see what it looks like within the frameset in Figure 13.2. There are HTML attributes that you can use with your frame code to get rid of the frame dividers, make more space in small frames by reducing the size of the margins, and force frames not to have scrollbars. Listing 13.4 shows a modified version of the code in Listing 13.1. The two changes made to the code are the addition of the following attributes to the <frame> tags: scrolling=”no” and frameborder=”0”. Listing 13.4 Frameset Document for the Site Shown in Figure 13.3 <?xml version=”1.0” encoding=”UTF-8”?> <!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” xml:lang=”en”> <head> <title>Sample Framed Site</title> </head> <frameset rows=”50,*”> <frame src=”top.html” name=”top” scrolling=”no” frameborder=”0” /> <frame src=”home.html” name=”main” scrolling=”no” frameborder=”0” /> <noframes> <body> <h1>Sample Framed Site</h1> Your browser does not support frames. Sorry! </body> FIGURE 13.3 This is the page whose code is shown in Listing 13.4 after attrib- utes were added to the tags. www.it-ebooks.info ptg 204 HOUR 13: Working with Frames Using Inline Frames Inline frames do not have the same usability issues that regular frames do, but inline frames are used for different reasons. Instead of being a pure lay- out trick, the The only XHTML code you haven’t yet encountered in Listing 13.5 is the Creates an inline frame; accepts all the same attributes as does and can be styled with CSS. Q&A Q Can I display other users’ web pages in one frame and my own pages in another frame at the same time? What if those other sites use frames, too? A You can load any document from anywhere on the Internet (or an intranet) into a frame. If the document is a frameset, its frames are sized to fit within the existing frame into which you load it. For example, you could put a list of your favorite links in one frame and use a separate frame to display the pages that those links refer to. This makes it easy to provide links to other sites without risking that someone will get lost and never come back to your own site. You should also be aware that framing somebody else’s pages so that they appear to be part of your own site might get you in legal trouble, www.it-ebooks.info ptg 208 HOUR 13: Working with Frames so be sure to get explicit written permission from anyone whose pages you plan to put within one of your frames (just as you would if you were putting images or text from their site on your own pages). Q Do I need to put a in all my frames? If I do, which title will be displayed at the top of the window? A The title of the frameset document is the only one that will be dis- played. <head> and <title> tags are not required in framed documents, but it’s a good idea to give all your pages titles just in case a user opens one by itself outside any frame. Workshop The workshop contains quiz questions and activities to help you solidify your understanding of the material covered. Try to answer all questions before looking at the “Answers” section that follows. Quiz 1. Write the HTML code to list the names Mickey, Minnie, and Donald in a frame taking up the left 25% of the browser window. Make it so that clicking each name brings up a corresponding web page in the right 75% of the browser window. 2. What <iframe> code would produce a borderless <iframe> with a white background that encompasses 98% of the width of the page and is 250 pixels high? Answers 1. You need five separate HTML documents. The first document is the frameset: <html> <head> <title>Our Friends www.it-ebooks.info ptg Exercises 209 Next, you need the index.html document for the left frame: Our Friends Index

                      Pick a friend:

                      Mickey
                      Minnie
                      Donald

                      Finally, you need the three HTML pages named mickey.html, minnie.html, and donald.html. They contain the information about each friend. 2. Use the following code: Exercises . Consider the reasons you might want to use a framed layout, and then sketch this layout on a piece of paper. Save this sketch for the upcoming lessons when you will learn to design layouts using XHTML and CSS, as these technologies offer you standards-compliant and user-friendly ways to achieve similar displays and functionality. . Think of some ways you can use an