JETZT ONLINE BESTELLEN
Add to Cart
Web Design in a Nutshell
A Desktop Quick Reference

Third Edition März 2006
ISBN 978-0-596-00987-8
826 Seiten
EUR32.00

Weitere Informationen zu diesem Buch

Inhaltsverzeichnis | Rezensionen |


Inhaltsverzeichnis

	
Chapter 1: Web Standards
Inhaltsvorschau
A great sea change has taken place in web development in the last six or seven years (and since the last edition of this book). Standards compliance is the name of the game in web design these days. After years of browser competition, HTML hacking, and other practices born out of the lack of guiding principles, we are all finally recognizing the benefits of abiding by the rules. That means using clean and logical HTML or XHTML for marking up content, Cascading Style Sheets for all matters of presentation, and a single Document Object Model for scripting.
As of this writing, we are still in a period of transition. New approaches need to be learned; old habits need to be shaken. Eventually, standards -based design will be second nature. The good news is that the developers of the tools we use to view and create web pages are making strides toward full standards support. With everyone on the same page, web production has the potential to be more efficient, less costly, and forward compatible.
This chapter introduces the current web standards and the way they impact web design.
The World Wide Web Consortium (W3C) creates and oversees the development of web technologies, including XML, HTML, and their numerous applications. They also keep their eye on higher-level issues such as making content accessible to the greatest number of devices and users, as well as laying a common foundation for future development, thus making web content "forward compatible."
The W3C is not an official standards body, but rather a joint effort by experts in web-related fields to bring order to the development of web technologies. The W3C releases its final word on how various tasks (such as HTML markup) should be handled in documents called "Recommendations." Most of their recommendations become the de facto standards for web development. There are other standards bodies that also affect the Web and the Internet at large, including those described next.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
What Are Standards?
Inhaltsvorschau
The World Wide Web Consortium (W3C) creates and oversees the development of web technologies, including XML, HTML, and their numerous applications. They also keep their eye on higher-level issues such as making content accessible to the greatest number of devices and users, as well as laying a common foundation for future development, thus making web content "forward compatible."
The W3C is not an official standards body, but rather a joint effort by experts in web-related fields to bring order to the development of web technologies. The W3C releases its final word on how various tasks (such as HTML markup) should be handled in documents called "Recommendations." Most of their recommendations become the de facto standards for web development. There are other standards bodies that also affect the Web and the Internet at large, including those described next.
ISO (International Organization for Standardization)
The ISO is a true standards organization that manages more than 10,000 standards, including everything from information systems and character sets to the dimensions of 220-size film and the grain size of coated adhesives. Their seal of approval helps keep commerce and information technologies compatible world wide.
IETF (Internet Engineering Task Force)
The IETF is an international community of network designers, operators, vendors, and researchers concerned with the evolution of the Internet as a whole. It publishes Request for Comments (RFCs) that define how things are done over the Internet, including FTP, TCP/IP, HTTP, and email.
Ecma International
Previously known as ECMA (European Computer Manufacturers Association) , this is a European association for standardizing information and communication systems. Ecma International manages information technology standards, including ECMAScript, the standardized version of JavaScript.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Current Web Standards
Inhaltsvorschau
Okay, so standards are great, but what standards are we talking about? This section looks at the current standards for the structural, presentational, and behavioral aspects of web design.
Web design and development is commonly discussed in terms of "layers" (and sometimes, even as a "layer cake," which is more enticing), borrowing a layer model from one commonly used for describing network protocols. The marked up document forms the structural layer, which is the foundation on which other layers may be applied. Next comes the presentation layer, specified with Cascading Style Sheets, that provides instructions on how the document should look on the screen, sound when it is read aloud, or be formatted when it is printed. On top of these layers, there may also be a behavioral layer , the scripting and programming that adds interactivity and dynamic effects to a site. This edition of Web Design in a Nutshell is organized according to this new mental model of web design.
The following is a summary of web technology Recommendations (what the W3C calls its final published standards) as of this writing. You can check in with further developments of these technologies at the W3C site ( www.w3.org ).
After years of browser developers getting jiggy with tag creation, the web community is returning to HTML's original intent as a markup language: to describe the structure of the document, not to provide instructions for how it should look. The structural markup of the document forms the foundation on which the presentational and behavioral layers may be applied.
These are the current standard languages for structural markup:
XHTML 1.0 (Extensible Hypertext Markup Language) and XHTML 1.1
XHTML 1.0 is simply HTML 4.01 rewritten according to the stricter syntax rules of XML. XHTML 1.1 finally does away with deprecated and legacy elements and attributes and has been modularized to make future expansions easier. XHTML 2.0 is currently in development. The last version of HTML was HTML 4.01, which is still universally supported by today's browsers, but is not forward compatible. Part II looks at these languages in detail. Links to the full XHTML 1.0, XHTML 1.1, and HTML 4.01 specifications can be found on this page:
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Standards-Driven Design
Inhaltsvorschau
Now that standards-compliant browsers are used by the vast majority of web visitors (see Chapter 2 for statistics), it is definitely time for designers and developers to start creating standards-compliant content. The following sections present some quick tips for making the transition to standards-based design.
For web designers and developers, the biggest mind shift towards making standards-compliant sites is keeping presentation separate from structure.
It was difficult to recognize HTML as a structural language when it was full of elements and attributes (like bgcolor, align, and of course, font) that define how elements look on the page. The W3C has deprecated those elements in the HTML 4.01 Recommendation and removed them entirely from XHTML 1.1. What remains is a markup language suited for the original purpose of logically describing the meaning of content elements (semantic markup) and establishing the basic hierarchical outline (or structure) of the document. The way the document is visually (or aurally, in the case of speech browsers) presented should be handled entirely by style sheets.
Following are some guidelines that will get you on the right track for designing with web standards.
Don't choose an element based on how it looks in the browser.
Now that you can make any element look the way you want with a style sheet rule, there is no reason to use an h3 because it looks less clunky than an h1, or a blockquote just because you want an indent. Take the time to consider the meaning or function of each element in your document and mark it up accurately.
Don't leave elements undefined.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
For Further Reading
Inhaltsvorschau
If this introduction to standards has left you hungry for more detail, you can find plenty of in-depth discussions on the bookshelves and the Web.
Additional books regarding accessibility, HTML, XHTML, CSS (including invaluable books by CSS guru, Eric Meyer) are listed at the ends of the appropriate chapters of this book. For more information on standards, consider these two volumes.
Designing with Web Standards, by Jeffrey Zeldman (New Riders)
This is the place to start if you need guidance and practical advice regarding making the switch to standards. Not only is it extremely thorough and informative, it's actually really fun to read.
Web Standards Solutions: The Markup and Style Handbook (Pioneering Series), by Dan Cederholm (Friends of Ed)
This book offers practical advice on how to create web content with standards, including multiple solutions to common issues.
With so many professionals in the online community learning to design with standards, it's no surprise there are plenty of tips, tutorials, and resources available.
The Web Standards Project (www.webstandards.org))
The Web Standards Project is an organization founded in 1998 to push the industry toward standardization. This site provides numerous compelling articles and helpful resources.
A List Apart (www.alistapart.com)
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Chapter 2: Designing for a Variety of Browsers
Inhaltsvorschau
Most web authors agree that the biggest challenge (and headache) in web design is dealing with a multitude of browsers and their varying support of web standards. Does a page that is designed to be functional on all browsers necessarily need to be boring? Is it possible to please everyone? And if not, where do you draw the line? How many past browser versions do you need to cater to with your designs?
The situation is better than it was a few years ago, but the struggle is not over. For instance, you can now be confident that at least 99% of users have browsers that support nearly all of HTML 4. Unfortunately, there are still inconsistencies in the way Cascading Style Sheets are implemented. And of course, older browser versions that pre-date the current standards take a long time to fade away entirely.
This chapter provides background information, statistics, and current wisdom from professional web designers that may help you deal with browser differences. It focuses on the traditional graphical computer-based browsers that developers generally keep in mind. Web browsing clients for mobile devices are discussed in Chapter 3, and assistive browsing devices for the disabled are addressed in Chapter 5.
The story of the browser provides useful context for the way web sites are currently designed and developed. This brief and simplified timeline highlights a few of the significant events in the development of the major browsers that have led to the current web design environment.
If you are interested in the history of browsers and the Web, take a look at the thorough timeline and the old browser emulators at Deja Vu ( www.dejavu.org ).
1991 to 1993: The World Wide Web is born.
Tim Berners-Lee started his hypertext-based information management at the CERN physics research labs. Text-only pages could be viewed using a simple line-mode browser.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Browser History
Inhaltsvorschau
The story of the browser provides useful context for the way web sites are currently designed and developed. This brief and simplified timeline highlights a few of the significant events in the development of the major browsers that have led to the current web design environment.
If you are interested in the history of browsers and the Web, take a look at the thorough timeline and the old browser emulators at Deja Vu ( www.dejavu.org ).
1991 to 1993: The World Wide Web is born.
Tim Berners-Lee started his hypertext-based information management at the CERN physics research labs. Text-only pages could be viewed using a simple line-mode browser.
1993: NCSA Mosaic is released.
The Mosaic browser was created by Marc Andreessen, a student at the National Center for Supercomputing Applications (NCSA) . Although it was not the first browser to allow graphics to be placed on the page, it was certainly the most popular due to its cross-platform availability. The ability to add images to documents was one of the keys to the Web's rapid rise in popularity. Mosaic also supported sound, video, bookmarks, and forms. All web pages at this time were displayed in black text on a gray background .
1994: Netscape 0.9 is released.
Marc Andreessen formed Mosaic Communications Corp. (which later became Netscape Communications) and released the Netscape 0.9 browser. The early browsers were not free (except to students and teachers). To offer a superior experience over such freely available browsers as Mosaic and thereby attract customers, Netscape created its own HTML tags without regard for the traditional standards process. For example, Netscape 1.1 included tags for changing the background color of a web page and formatting text with tables.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Browser Roll-Call
Inhaltsvorschau
It is critical that professional web developers be familiar with the most popular browsers in current use and not just the ones on their own desktops. This section provides basic information about the browsers that web developers care about most, whether because of total share of web usage (Internet Explorer 6 for Windows) or because its technology and standards support is important to the development community (Opera). The browsers listed here make up more than 99% of total usage as of this writing.
There are scores of less common browsers, some with loyal followings, as well as older browser versions that are still in use. Unfortunately, it is not possible to list them all in this chapter. Evolt.org, a site for the web development community, keeps a complete archive of browsers old and new at browsers.evolt.org .
Table 2-1 lists the browsers and their release dates, platforms, rendering engines, and level of standards support, while the following sections describe each browser in more detail.
Table 2-1: Various web browsers
Browser
Release date
Platform
Rendering engine
Standards support
Microsoft Internet Explorer 6
2001
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Gathering Usage Statistics
Inhaltsvorschau
Web developers pay attention to the breakdown of browser usage, for the Web at large and more relevantly for their specific sites, because it directly affects the way they create their pages. There are several methods for tracking browser usage: free general statistics listings, log analysis tools that you run on your own server, and professional statistics services.
If you are interested in a general breakdown of overall browser usage, there are a number of web sites that provide listings for free. They also offer usage statistics on other useful criteria such as screen resolution and various web technologies.
The Counter ( www.thecounter.com/stats ) bases its global statistics on millions of visitors using thousands of web sites registered with their service. This is an easy (and free) way to get a good general overview of browser usage.
Another useful resource for browser information, as well as for tutorials on a number of web topics, is the W3 Schools site ( www.w3schools.com/browsers ). Their statistics seem skewed toward the development and technically savvy community, as evidenced by the fact that the Firefox browser makes up nearly 20% of all usage, compared with only 8% at the more general Counter.com as of this writing (September 2005).
The most meaningful statistics are those culled from your own site's usage. There are software tools designed just for this purpose, all of which work basically the same way.
When a browser accesses files from a server, it leaves a record of that transaction on the server, including a little data about itself: specifically, its version and the platform it is running on. This information is known as the user agent string , and it is used by analysis software to generate statistics about the browser usage for a site. A typical user agent string might look like this:
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Learning from Browser Statistics
Inhaltsvorschau
However you gather your statistics, they can tell you some important things about your audience and how they may experience the Web. Consider Table 2-2, which provides a set of browser statistics typical of the end of 2005. These statistics may not necessarily be meaningful as you read this book, but if you are completely unfamiliar with the typical browser breakdowns, these will give you a ballpark idea.
Table 2-2: Browser statistics for December 2005 from The Counter.com
Browser
Usage
Microsoft Internet Explorer 6
83%
Microsoft Internet Explorer 5
3%
Mozilla/Firefox
8%
Safari
2%
Unknown
1%
Opera x.x
1%
Netscape 7
1%
Netscape compatible
< 1%
Microsoft Internet Explorer 4.x
< 1%
Netscape 4.x
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Dealing with Browser Differences
Inhaltsvorschau
How do professional web designers and developers cope with the multitude of browsers and their varying capabilities?
In the past, it required some tough decisions or a lot of extra work. It was common to create multiple versions of a site to ensure similar functionality. Some designers played it safe and avoided any web technology more advanced than basic HTML. On the other end of the spectrum were designers who chose to design cutting edge sites exclusively for the latest version of one specific browser. We can thank the Browser Wars of the late '90s for that chaos.
Web standards—or more important, the fact that the major browser developers have finally started to support them—have simplified the way designers cope with the multitude of browsers in use. Gone are the days of choosing sides or building several versions of the same site. Today, it is possible to create sites that are accessible to 100% of browsers and that look good in the vast majority of them. The trick is following the standards yourself in the way you write, style, and program your content.
Note that I said "possible" in the last paragraph, and not "easy," to create sites for all browsers. As of this writing, the web environment, although inching towards standards compliance, is not there yet. There are still inconsistencies, even in the current browser versions, that require some fancy coding to deliver a consistent cross-browser experience. While we are in this period of transition, there are still some old-school techniques that are common practice or even necessary despite going against W3C recommendations.
Bugs aside, sticking with standards is still the primary tool to ensuring your site is usable for all users on all browsers. Following are some specific strategies for addressing varying browser capabilities.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Know Your Audience
Inhaltsvorschau
Although by following standards-driven development techniques, you ensure that your site is usable for all visitors, you may decide to embrace or steer clear of certain technologies based on knowledge of your audience. Before designing a new site, be sure to spend time up front researching the likely platforms, browsers , technical savviness, and connection speeds of the users you are targeting. If you are redesigning an existing site, spend time with the server logs to analyze past site usage.
There are no browser-support guidelines that can anticipate every design situation; however, the following scenarios should start you thinking:
  • If your site is aimed at a consumer audience—for instance, a site that sells educational toys to a primarily parent audience—don't ignore your site's performance and presentation in the AOL browsers or older browser versions over dial-up connections.
  • If you are designing for a controlled environment, such as a corporate intranet or, even better, a web-based kiosk, you've got it made! Knowing exactly what browser and platform your viewers are using means you can take full advantage of the bells and whistles (and even proprietary features) appropriate to that browser. If you are designing a standalone kiosk, you may even have the luxury of loading the fonts you want to use. Just be sure your design won't crash the browser, because there won't be anyone there to restart it for you immediately.
  • If your site is about the technology being used, such as SVG graphics or Flash animations, you have every right to expect users to use the appropriate browser or plug-in to catch up with your content. But it might still be nice to at least provide some screenshots or other alternative content to let the others know what they're missing.
  • If you are designing a government site, you are required by law under Section 508 to make your pages accessible to all browsing devices. For more information, see Chapter 5.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Test!
Inhaltsvorschau
The final word in the dilemma of designing for a variety of browsers is test! Always test your site on as many browsers, browser versions, and platform configurations as you can get your hands on.
Professional web design firms run their sites through a vigorous quality assurance phase before going "live." They generally keep a bank of computers of varying platforms and processing powers that run as many versions of browsers (including Lynx) as possible.
Another option is to subscribe to a screen capture service such as Browser Cam. For a monthly fee, you can enter the URL of a page you want to check, and Browser Cam creates screen captures of the page in all the operating systems and browsers you select. This makes it easy to see which browsers are having problems without needing to run copies of all of them yourself. Read more at browsercam.com .
If you have extremely limited resources, make the site available on a private test site and take a look at it on your friends' computers. You might view it under corporate conditions (a fast Windows machine with a 6.0 browser and a T1 connection), and then visit a friend at home to see the same site on AOL with a 56K modem. (If nothing else, this is a good excuse to get away from your computer and visit your friends.)
Although your pages will certainly look different in different environments, the idea is to make sure that nothing is outright broken and your content is communicated clearly.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Chapter 3: Designing for a Variety of Displays
Inhaltsvorschau
A simple fact of web publishing is that your page is at the mercy of the software and hardware configuration of each individual user. A page that looks great on your machine may look radically different when viewed on another user's setup. This is partly due to the browser's functionality (as discussed in Chapter 2) and the individual user's preferences (font size, colors, etc.), but the display device itself also plays a large part in the user's experience.
This chapter looks at the ways in which design decisions are influenced by a wide range of displays and viewing conditions. The variation in display is a function of the monitor's size (or, more accurately, its resolution), color capabilities, and user's personal preferences. However, it is important to keep in mind that the diversity does not end there. Some users may be watching your web page on TV. Still others may be viewing it in the palm of their hand on a PDA (personal digital assistant) or cell phone. Sight-impaired users may be listening to your page, not viewing it.
How do you create a page that works in a cinema-display computer monitor and a postage-stamp sized cell phone? Once again, web standards are the answer. The W3C guides the development of web technologies in a way that ensures that the Web is accessible to all manner of devices. As designers and developers, our job is to author documents in a way that they make sense in any environment. That means logical, well-structured markup, uncluttered by presentation instructions that may not be appropriate for a particular medium. In fact, Cascading Style Sheets include a function that allows you to create different style sheets targeted to particular media such as print, screen, and handheld.
As most web viewing does take place on computer monitors, this chapter starts with a look at how monitor resolution impacts web page design.
Browser windows can be resized to any dimension, limited only by the maximum size of the monitor. Designing for an unknown amount of browser real estate is a challenge unique to web design and one that is particularly troublesome for designers who are accustomed to the printed page.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Designing for Unknown Monitor Resolutions
Inhaltsvorschau
Browser windows can be resized to any dimension, limited only by the maximum size of the monitor. Designing for an unknown amount of browser real estate is a challenge unique to web design and one that is particularly troublesome for designers who are accustomed to the printed page.
Many web designers want to know which monitor resolution to design for. As with most web design issues, there is no "right" way to design for the Web, and your decisions should always be guided by your knowledge of your target audience and the purpose of your site. Still, it is helpful to understand the environment and to know how others are maneuvering within it.
This section looks at the range of monitor resolutions and presents the current wisdom on making appropriate design decisions.
The first step in determining the likely size of your web page is to look at the maximum amount of space provided by the computer monitor. Computer monitors come in a variety of standard sizes, typically measured in inches, ranging from 12" laptop displays all the way up to 30" cinema displays.
A more meaningful measurement, however, is monitor resolution: the total number of pixels available on the screen. The higher the resolution, the more detail can be rendered on the screen. Resolution is related to but not necessarily determined by monitor size. Depending on the video card driving it, a single monitor can display a number of different resolutions. For instance, a 17" monitor can display 800 × 600 pixels, 1024 X 768 pixels, or even higher. The following is a list of some standard monitor resolutions supported by Windows and Macintosh platforms. This is not a complete listing, merely the most commonly occurring configurations.
  • 640 × 480
  • 800 × 600
  • 1024 × 768
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Fixed Versus Liquid Web Pages
Inhaltsvorschau
Closely related to the issue of varying monitor resolutions is the question of whether web pages should be designed to be liquid (resizing and adapting to various window sizes, also called "fluid" design) or fixed at a particular size (giving the designer more control of the page's dimensions). There are very strong opinions on both sides, and there are good reasons for and against each approach, naturally.
You may find that you choose a fixed structure for some sites and allow others to be liquid, or you may have strong convictions that one or the other approach is the only way to go. Either way, it is useful to be familiar with the whole picture and the current opinions of professional web designers (see "The Layout Debate" sidebar). This section attempts to present a balanced overview of the possibilities and the pitfalls.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Designing "Above the Fold"
Inhaltsvorschau
Newspaper editors have always designed the front page with the most important elements "above the fold," that is, visible when the paper is folded and sitting in the rack.
Likewise, the first screenful of a web site's homepage is the most important real estate of the whole site, regardless of whether the page is fixed or flexible. It is here that the user makes the decision to continue exploring the site or to hit the Back button and move along. Web designers have adopted the term "above the fold" to apply to the contents that fit in that important first screen.
As discussed throughout this chapter, a "screenful" can be quite different depending on the resolution of the monitor. To play it absolutely safe, consider the space available for the lowest common denominator 800 × 600 monitor—approximately 780 × 400 pixels. That's not much room.
Some elements you should consider placing above the fold include:
  • The name of the site.
  • Your primary marketing message.
  • Some indication of what the site is about. For instance, if it is a shopping site, you might place the credit card logos or shopping cart in the top corner to instantly communicate that "shopping happens here."
  • Navigation to other parts of the site. If the entire navigation device (such as a list of links down the left edge of the page) doesn't fit, at least get it started in the first screen; hopefully users will scroll to see the remainder. If it is out of sight completely, it is that much more likely to be missed.
  • Any other information that is crucial for visitors to the site, such as a toll-free number or special promotion.
  • Banner advertising. Advertisers may require that their ads appear at the top of the page.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Mobile Devices
Inhaltsvorschau
The increased popularity and usefulness of the Web combined with the growing reliance on handheld communications devices (such as palm-top computers, PDAs, and cellular telephones) has resulted in web browsers squeezing into the coziest of spaces. Advancing technology and lower production costs have made high-resolution color displays and embedded web browsers standard issue on nearly all new phones and PDAs. This comes as a big improvement over the black-and-white, text-only displays of only a few years ago, and it is creating a call for mobile -appropriate web content.
Because each manufacturer creates its own displays, there are no clear standard screen resolutions for mobile devices the way there are for computer monitors. But to get you in the ballpark, take a look at some current specifications. On the low end are standard mobile phones with screen dimensions of 128 × 128 pixels. Fuller-featured phones typically have resolutions of 176 × 208, 176 × 220, 208 × 208, or as large as 240 × 320. Handheld devices, such as the ubiquitous BlackBerry, sport screen sizes of 240 × 160 or 240 × 240.
The browsers embedded in mobile phones and PDAs (also known as microbrowsers ) are designed to accommodate the lower memory capacity, low bandwidth abilities, and limited display area of handheld devices. Some are WAP browsers with limited HTML support (see the sidebar, "WAP and WML"), and some are full-featured browsers that support the current web standards and allow access to all the same web content that is available from a PC browser. (Some of the best-known mobile browsers and their web addresses are listed at the end of this section.)

Section 3.4.2.1: Support for standards

The significant development in mobile browsing technology is the abandonment of WAP (Wireless Application Protocol) and its authoring language WML (Wireless Markup Language) in favor of the same web authoring standards set forth by the W3C for web content. The Open Mobile Alliance (
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Chapter 4: A Beginner's Guide to the Server
Inhaltsvorschau
Even if you focus primarily on what's commonly referred to as frontend web development—HTML documents and web graphics—the server and the way it is configured may impact the way you work. In most cases, there is no way to avoid making firsthand contact with the server, even if it's just to upload files.
For this reason, all web designers should have a basic level of familiarity with servers and what they do. At the very least, this will enable you to communicate more clearly with your server administrator. If you have permission for greater access to the server, it could mean taking care of certain tasks yourself without needing to wait for assistance.
This chapter provides an introduction to server terminology and functions, pathnames, and file (MIME) types. It also discusses uploading files and setting permissions, which designers often need to do.
A server is any computer running software that enables it to answer requests for documents and other data. The programs that request and display documents (such as a browser) are called clients . The terms server-side and client-side, in regard to such specific functions refer to which machine is doing the processing. Client-side functions happen on the user's machine; server-side functions occur on the remote machine.
Web servers answer requests from browsers (the client program), retrieve the specified file (or execute a script), and return the document or script results. Web browsers and servers communicate via the Hypertext Transfer Protocol (HTTP).
Any computer can be a server as long as it is running server software. Today, there are many server packages available, but the overwhelming leaders are Apache and Microsoft Internet Information Server (IIS) .
Apache
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Servers 101
Inhaltsvorschau
A server is any computer running software that enables it to answer requests for documents and other data. The programs that request and display documents (such as a browser) are called clients . The terms server-side and client-side, in regard to such specific functions refer to which machine is doing the processing. Client-side functions happen on the user's machine; server-side functions occur on the remote machine.
Web servers answer requests from browsers (the client program), retrieve the specified file (or execute a script), and return the document or script results. Web browsers and servers communicate via the Hypertext Transfer Protocol (HTTP).
Any computer can be a server as long as it is running server software. Today, there are many server packages available, but the overwhelming leaders are Apache and Microsoft Internet Information Server (IIS) .
Apache
The majority of servers today (approximately 70%) run Apache. Powerful and full-featured, it has always been available for free. It runs primarily on the Unix platform but is also available on other platforms, including Windows NT/2000 and Mac OS X.
The core installation of Apache has limited functionality, but it can be expanded and customized easily by adding modules. Apache calls on each module to perform a dedicated task, such as user authentication or database queries. You can pick up a copy of the Apache server and its documentation from the Apache home page at www.apache.org
Internet Information Server (IIS)
This is Microsoft's server package, which is also available without charge. IIS runs on the Windows NT platform. IIS has developed into a powerful and stable server option that is somewhat easier to set up and maintain than its Unix competitor. It has many advanced server features, including ASP (Active Server Pages) for server-side scripting. As of this writing, approximately 20% of sites run on IIS servers. For more information, see the Windows Server System pages at
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Unix Directory Structures
Inhaltsvorschau
Because the Web was spawned from the Unix environment, it follows many of the same conventions. Directory structure and pathname syntax are prime examples. It is important for all web designers to have an understanding of how directory structures are indicated on the Unix platform, because pathnames are used in hyperlinks and pointers to images and other resources.
Directories ("places" to store files) are organized into a hierarchical structure that fans out like an upside-down tree. The topmost directory is known as the root and is written as a forward slash (/). The root can contain several directories , each of which can contain subdirectories; each of these can contain more subdirectories, and so on. A subdirectory is said to be the child of the directory that holds it (its parent). Figure 4-1 shows a system with five directories under the root. The directory users contains two subdirectories, jen and richard. Within jen are two more subdirectories, work and pers, and within pers is the file art.html.
A pathname is the notation used to point to a particular file or directory; it tells you the path of directories you must travel to get to where you want to go. There are two types of pathnames: absolute and relative.
An absolute pathname always starts from the root directory , which is indicated by a slash (/). So, for example, the pathname for the pers directory is /users/jen/pers, as shown in Figure 4-2. The first slash indicates that you are starting at the root and is necessary for indicating that a pathname is absolute.
Figure 4-1: Example of a directory hierarchy
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
File Naming Conventions
Inhaltsvorschau
For your files to traverse the network successfully, you must name them in accordance with established file naming conventions :
  • Avoid character spaces in filenames. Although this is perfectly acceptable for local files on a Macintosh or Windows machine, character spaces are not recognized by other systems. It is common to use an underscore or hyphen character to visually separate words within filenames, such as andre_bio.html or andre-bio.html. Hyphens are sometimes preferred because they tend to better enable search engines to index the individual words in a filename.
  • Avoid special characters such as ?, %, #, /, and : in filenames. It is best to limit filenames to letters, numbers, underscores (in place of character spaces), hyphens, and periods.
  • Use proper suffixes. HTML documents should use the suffix .html (.htm also works on most servers ). GIF graphic files take the suffix .gif, and JPEGs should be named .jpg or .jpeg. If your files do not have the correct suffix, the server might not send the proper HTTP Content-Type header, and thus the browser may not recognize the files as web-based files. Suffixes for a large number of common file types are listed later in this chapter.
  • Consistently using all lowercase letters in filenames, while certainly not necessary, may make them easier to remember. In addition, filenames are case-sensitive on some servers, so keeping them all lowercase avoids potential hassles.
  • Keep filenames as short as possible. They add to the size of the file (and they can be a nuisance to remember).
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Uploading Documents (FTP)
Inhaltsvorschau
The most common transaction that a web designer will have with a web server is the uploading of HTML documents, graphics, and other media files. Files are transferred between computers over a network via a method called FTP (File Transfer Protocol) .
If you are working in a Telnet session on Unix, you can run the FTP program and transfer files with a hefty collection of command-line arguments (not covered in this book).
Fortunately, if you work on a Mac or PC, there are a number of FTP programs with graphical interfaces that spare you the experience of transferring files using the Unix command line. In fact, FTP functions are now built right into full-featured web authoring tools, such as GoLive, Dreamweaver, and FrontPage, among others. On the Mac, dedicated programs that allow drag-and-drop file transfer, such as Fetch and Interarchy (previously Anarchie) are quite popular. On the PC, there are numerous simple FTP programs, such as CuteFTP, WS_FTP, AceFTP, and Transmit. These (and many others) are available for download at www.shareware.com ; search for "ftp."
Regardless of the tool you use, the basic principles and processes are the same. Before you begin, you must have an account with permission to upload files to the server. Check with the server administrator to be sure you have a login name and a password.
You don't necessarily need an account to upload and download files if the server is set up as an "anonymous" FTP site. However, due to obvious security implications, be sure that your personal directories are not configured to be accessible to all anonymous users.
  1. Launch the FTP program of your choice and open a connection with your server. You'll need to enter the exact name of the server, your account name, and password.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
File (MIME) Types
Inhaltsvorschau
Servers add a header to each document, which tells the browser the type of file it is sending. The browser determines how to handle the file based on that information—for example, whether to display the contents in the window, or to launch the appropriate plug-in or helper application.
The system for communicating media types closely resembles MIME (Multipurpose Internet Mail Extension) , which was originally developed for sending attachments in email . The server needs to be configured to recognize each MIME type to successfully communicate the media type to the browser.
If you want to deliver media beyond the standard HTML files and graphics (such as a Shockwave Flash movie or an audio file), you should contact your server administrator to be sure the server is configured to support that MIME type. Most common formats are built into current versions of server software, but if the format isn't there already, the administrator can easily set it up if you provide the necessary information.
The exact syntax for configuring MIME types varies among server software; however, they all require the same basic information: type, subtype, and extension. Types are the most broad categories for files. They include text, image, audio, video, application, and so on. Within each category are a number of subtypes. For instance, the file type image includes the subtypes gif, jpeg, and the like. The extension refers to the file's suffix, which the server uses to determine the file type and subtype. Not all extensions are standardized.
Table 4-1 lists the MIME type and subtype for common media types. The ASCII/binary information is provided to aid in making upload decisions.
Of course, new technologies and file types are emerging every day, so keep in mind that it is the web designer's responsibility to make sure that for any new media type, the appropriate information is communicated to the server administrator. For a complete listing of registered MIME types, see the IANA (Internet Assigned Numbers Authority) site at
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Chapter 5: Accessibility
Inhaltsvorschau
by Derek Featherstone
At its core, web accessibility is about building web sites, applications, and pages so that there are as few barriers to use as possible for anyone, regardless of ability and the device used to access the information. Web accessibility goes beyond creating a more usable Web for persons with disabilities, too. Many of the techniques and principles designers apply to make web content more accessible to people with disabilities also improve accessibility for those using slower connections who might have the images off as well as increase interoperability with handhelds.
For sites to be accessible, we have to let go the notion that we know how people use our web sites. We have to understand the nature of the medium in which we work. And, we have to be willing to embrace "universal design" and to use web development techniques and code that support accessibility.
There are four broad categories of disabilities that have an impact on how a person interacts with a web site: vision impairment, mobility impairment , auditory impairment, and cognitive impairments.
Vision impairment
People that are blind or have low vision use a variety of assistive technology to get content from the screen, including screen readers, Braille displays, screen magnifiers, and even some combination of these.
Mobility impairment
Mobility challenges range from having no use of the hands at all to difficulties with fine motor control. Various hardware solutions include modified mice and keyboards, single-button "switches," foot pedals, head wands, and joysticks, while software solutions range from full voice recognition to face tracking to simple keyboard macros.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Types of Disabilities
Inhaltsvorschau
There are four broad categories of disabilities that have an impact on how a person interacts with a web site: vision impairment, mobility impairment , auditory impairment, and cognitive impairments.
Vision impairment
People that are blind or have low vision use a variety of assistive technology to get content from the screen, including screen readers, Braille displays, screen magnifiers, and even some combination of these.
Mobility impairment
Mobility challenges range from having no use of the hands at all to difficulties with fine motor control. Various hardware solutions include modified mice and keyboards, single-button "switches," foot pedals, head wands, and joysticks, while software solutions range from full voice recognition to face tracking to simple keyboard macros.
Auditory impairment
Auditory impairments may seem to have little to no impact on how people use the Web, as most content is text and images. A person who has never been able to hear, however, may process language completely differently than a hearing person or someone with hearing loss that occurred later. There are requirements for captioning for multimedia and audio files to make this type of media accessible to everyone.
Cognitive impairment
Cognitive impairments, which involve memory, reading comprehension, mathematical processing, visual comprehension, problem solving, and attention, are the least understood of the various accessibility issues. Although there isn't a large body of literature and research available, the common advice is to focus on simplicity and clarity to help address some of these issues. Thinking this way also helps make your web pages, sites, and applications more readily understood by everyone.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Overview of Assistive Technology
Inhaltsvorschau
Assistive technology is any tool that helps a person with a disability accomplish everyday tasks more easily. A specially designed "rocker" knife that makes it easier to cut food with the use of one hand is considered assistive technology . In computer terms, assistive technology helps people accomplish two fundamental tasks: input and output. These tools are not web specific; web usage is just one component of their overall utility.
Don't overlook your own computer's capabilities. Windows XP and Mac OS X both include a lot of support for accessibility by default, and Sun Microsystems' Solaris 10 includes full accessibility support with voice capabilities, screen magnification, and onscreen keyboard functions.
Assistive technology for input works to provide the same type of functionality that a keyboard and mouse provide. This means that for the most part, you as a web designer or developer simply need to ensure that what you create is operable by both keyboard and mouse. If you can do that, generally the assistive technology will take care of the rest (although some input considerations are discussed later in the chapter).
Some example technologies are:
Alternative keyboards
Alternative keyboards may provide a more functional key layout, be color-coded for cognitive disabilities, include larger keys, have a keyboard overlay or guide that aids in selection of the proper key, or be designed for one-handed use.
Virtual keyboards
A virtual keyboard is one that is displayed on the screen to help people who may have difficulty typing but are able to use a mouse or some other pointing device effectively. Windows XP comes with a basic onscreen keyboard.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Who Is Responsible for Accessibility?
Inhaltsvorschau
Generally speaking, there are four "groups" of people responsible for accessibility. These include:
Web designers
That's right, us: the people who design, program, and build web sites. Using the W3C's Web Content Accessibility Guidelines (WCAG ) we can make informed decisions as to how to make sites accessible.
Browser, screen reader, and other user agent manufacturers
This group is responsible for ensuring the accessibility of their tools for using the Web. The User Agent Accessibility Guidelines (UAAG) help browser manufacturers build their tools so that they can leverage the good content that developers produce.
Software vendors
Playing a critical role in accessibility, this group creates the tools that developers, designers, and authors use to create web content. This group looks at the Authoring Tool Accessibility Guidelines (ATAG) when they are building their software.
Users
People with disabilities are not without some responsibility. It is quite reasonable that we expect people using assistive technology to know how to use it properly and efficiently.
So if we as developers, designers, and authors are partly responsible, how do we go about living up to those responsibilities to make our web sites accessible? First, we start with an understanding of what we're trying to achieve, and then we apply that to the way we build our sites. Fortunately, we are guided by the W3C's Web Content Accessibility Guidelines 1.0 (WCAG 1.0).
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Web Content Accessibility Guidelines
Inhaltsvorschau
The Web Content Accessibility Guidelines were created by the Web Accessibility Initiative (WAI) at the W3C. The guidelines were formally made Recommendations in 1999, and a lot has changed since then. Some of the techniques that are advocated in the WCAG 1.0 Techniques resource are outdated and may no longer apply in the same way as when the guidelines were released.
These guidelines have several related checkpoints organized according to three different priority levels from Priority 1 (most critical for web accessibility) to Priority 3 (important but having less impact on overall accessibility). At www.w3.org/TR/1999/WAI-WEBCONTENT-19990505, each of the checkpoints are listed following their related guidelines along with their priority level. For a view of the checkpoints organized according to their priority level, go to www.w3.org/TR/WCAG10/full-checklist.html.
Guideline 1: Provide equivalent alternatives to auditory and visual content.
Following this rule ensures that visually or aurally impaired people have access to the content that they are unable to perceive. "Equivalent alternatives" refers to ensuring that images have appropriate alt text that represents the image, that audio content has captions provided, and that video includes audio description. Remember, when deciding what an equivalent alternative is, you must consider both the content and function of the original.
Guideline 2: Don't rely on color alone.
When you rely on color alone to present information on a web page, you limit the usefulness of that information. Rather than using color alone to show which fields of a form are required, mark the labels in red and bold, or with an asterisk beside them to ensure that people who can't see the red color have some other means of getting the same information. Further, provide sufficient contrast between the foreground color and the background color to ensure that text (even as part of a graphic, Flash movie, or other multimedia component) is readable.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Web Content Accessibility Guidelines 2.0 (WCAG 2.0)
Inhaltsvorschau
At the time of this writing, the W3C's Working Draft of Web Content Accessibility Guidelines 2.0 was entering its final stages of approval.
WCAG 2.0 revolves around four basic principles for web accessibility:
  • Content must be perceivable.
  • User interface components in the content must be operable.
  • Content and controls must be understandable.
  • Content must be robust enough to work with current and future technologies.
This is not a radical departure from WCAG 1.0, and the same general principles apply. In many ways, it is a reorganization to make the full gamut of accessibility guidelines more understandable. Further, WCAG 2.0 attempts to provide better guidance to web content authors by eliminating some of the ambiguity in WCAG 1.0. For a comparison of WCAG 1.0 and WCAG 2.0, see www.w3.org/WAI/GL/2005/06/30-mapping.html.
Keep in mind, however, that the WCAG 2.0 Working Draft is subject to revision based on review and public comment.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Standards Variations and Section 508
Inhaltsvorschau
Various other countries have their own versions of web accessibility standards, most of which are derived from WCAG 1.0. Canada, Australia, the U.K., and Europe, for example, have accessibility standards that generally agree with the most important points (Priority 1 and Priority 2) of WCAG 1.0. One of the most well-known standards that is a deviation from this is Section 508 in the U.S., which uses Priority 1 checkpoints, as well as a few other selectively chosen checkpoints.
Many view Section 508 as a more literal and strict interpretation of the Priority 1 and 2 checkpoints. Fundamentally, though, Section 508 principles are generally consistent with Priority 1 of WCAG 1.0, though the wording may be slightly different.
The following list is excerpted from subsection 1194.22 of Section 508 standards for Web-based intranet and Internet information and applications (www.section508.gov/index.cfm?FuseAction=Content&ID=12#Web). You'll notice that the items (a) through (k) consistently map to the Priority 1 checkpoints of WCAG 1.0, whereas the subsequent items do not.
  • (a) A text equivalent for every nontext element shall be provided (e.g., via alt, longdesc, or in element content).
  • (b) Equivalent alternatives for any multimedia presentation shall be synchronized with the presentation.
  • (c) Web pages shall be designed so that all information conveyed with color is also available without color, for example, from context or markup.
  • (d) Documents shall be organized so they are readable without requiring an associated style sheet.
  • (e) Redundant text links shall be provided for each active region of a server-side image map.
  • (f) Client-side image maps shall be provided instead of server-side image maps except where the regions cannot be defined with an available geometric shape.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Web Accessibility Techniques
Inhaltsvorschau
Official guidelines and checkpoints are vital, but they don't give us much in the way of best practice advice or implementation techniques. To help you, the W3C provides reference documents with overviews of HTML, CSS, and core techniques at www.w3.org/WAI/intro/wcag.php.
Here are some good starting points that will help you make your web sites more accessible.
Start with meaning.
In other words, use HTML elements for the purposes for which they were designed: to provide a semantic description of a document's content. As discussed in the guidelines earlier in this chapter, make use of headings (h1 through h6), lists, quotes, and blockquotes to provide structure to your pages. Use table markup appropriately as shown in Chapter 13. Screen readers and other software infer meaning and provide functionality based on this markup.
Provide alternatives.
Ensure that you provide some type of alternative--alt text, longdesc, transcripts for audio files, and captions for video—for users with various disabilities. Formerly cost prohibitive, captioning and transcripting can now be outsourced at a very reasonable cost and provide significant benefit to users that require alternative media types.
Use Zoom layouts.
Typically used by low-vision users, a Zoom layout is an alternative view of the same content. Users of screen magnification software have a limited view of what is on the screen, making multiple columns difficult to follow. A single-column format can be very useful. For more information on Zoom layouts, Joe Clark's web site (
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Testing for Accessibility
Inhaltsvorschau
One of the best ways to ensure successful implementation of these guidelines is through testing. How else will you know when you've hit the mark in terms of providing accessible content? There are four primary methods of testing for accessibility: by developers, by expert review, with real users, and with automated tools.
You can find accessibility testing tools online and on the desktop for everything from smaller scale testing to enterprise level tools that allow you to track progress over time, automate reporting, and allow for manual review in conjunction with automated tests.
These items should be in every web developer's toolkit. In addition to their use for informal accessibility testing, they are often useful for general web development as well.
Web Developer Toolbar for Firefox/Mozilla (addons.mozilla.org/extensions/moreinfo.php?id=60)
An extension for Firefox and Mozilla, the Web Developer Toolbar provides a host of tools that are useful for low-level accessibility testing. It allows you to easily disable CSS and JavaScript, as well as replace images with their alt text. Quick access to these tools helps assess your work against the guidelines presented in this chapter.
Accessibility Toolbar for Internet Explorer (www.nils.org.au/ais/web/resources/toolbar/)
Similar to the Web Developer Toolbar, the Accessibility Toolbar is designed to work in Internet Explorer for Windows. It provides quick access to many of the same types of tools found in the Web Developer Toolbar, as well as one-click launching of several online services that allow you to roughly analyze readability of passages of text, color contrast analysis, various other vision-related disabilities, and online automated testing tools.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Chapter 6: Internationalization
Inhaltsvorschau
If the Web is to reach a truly worldwide audience, it needs to be able to support the display of all the languages of the world, with all their unique alphabets and symbols, directionality, and specialized punctuation. The W3C's efforts for internationalization (often referred to as "i18n"—an i, then 18 letters, then an n) ensure that the formats and protocols defined by the W3C are usable worldwide in all languages and writing systems.
You often hear the terms internationalization (or globalization ) and localization used together. The W3C defines localization as the process of adapting a technology or content to meet the language, cultural, and other requirements of a particular culture, region, or language. Internationalization refers to the design and development of web content and technologies that enables easy localization for target audiences. Localization entails more than simple language translation. It also takes into account details including, but not limited to:
  • Date and time formats
  • Currency
  • Keyboard usage
  • Cultural interpretations of symbols, icons, and colors
  • Content that may be subject to misinterpretation or viewed as insensitive
  • Varying legal requirements
Creating multilingual web sites and localized versions of site content is well beyond the scope of this Nutshell book. This chapter addresses two primary issues related to internationalization. First is the handling of alternative character sets that take into account all the writing systems of the world, including character encoding and character references. Second is the features built into HTML 4.01 and CSS 2.1 for specifying languages and their unique presentation requirements.
The first challenge in internationalization is dealing with the staggering number of unique character shapes (called
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Character Sets and Encoding
Inhaltsvorschau
The first challenge in internationalization is dealing with the staggering number of unique character shapes (called glyphs ) that occur in the writing systems of the world. This includes not only alphabets, but also all ideographs (characters that indicate a whole word or concept) for such languages as Chinese, Japanese, and Korean. There are also invisible characters that indicate particular functionality within a word or a line of text, such as characters that indicate that adjacent characters should be joined.
To understand character encoding as it relates to HTML, XHTML, and XML, you must be familiar with some basic terms and concepts.
Character set
A character set is any collection or repertoire of characters that are used together for a particular function. Many character sets have been standardized, such as the familiar ASCII character set that includes 128 characters mostly from the Roman alphabet used in modern English.
Coded character set
When a specific number is assigned to each character in a set, it becomes a coded character set. Each position (or numbered unit) in a coded character set is called a code point (or code position ). In Unicode, (discussed in more detail later) the code point of the greater-than symbol (>) is 3E in hexadecimal or 62 in decimal. Unicode code points are typically denoted as U+hhhh, where hhhh is a sequence of at least four and sometimes six hexadecimal digits.
Character encoding
Character encoding
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Character References
Inhaltsvorschau
HTML and XHTML documents use the standard ASCII character set (these are the characters you see printed on the keys of your keyboard). To represent characters that fall outside the ASCII range, you must refer to the character by using a character reference. This is known as escaping the character.
In HTML and XML documents, some ASCII characters that you intend to be rendered in the browser as part of the text content must be escaped in order not to be interpreted as code by the user agent. For example, the less-than symbol (<) must be escaped in order not to be mistaken as the beginning of an element start tag. Other characters that must be escaped are the greater-than symbol (>), ampersand (&), single quote ('), and double quotation marks ("). In XML documents, all ampersands must be escaped or they won't validate.
There are two types of character references: Numeric Character References (NCR) and character entities.
A Numeric Character Reference (NCR) refers to the character by its Unicode code point (introduced earlier in this chapter). NCRs are always preceded by &# and end with a ; (semicolon). The numeric value may be provided in decimal or hexadecimal. Hexadecimal values are indicated by an x before the value.
For example, the copyright symbol (©), which occupies the 169th position in Unicode (U+00A9), may be represented by its hexadecimal NCR &#xA9; or its decimal equivalent, &#169;. Decimal values are more common in practice. Note that the zeros at the beginning of the code point may be omitted in the numeric character reference.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Language Features
Inhaltsvorschau
Coordinating character sets is only the first part of the challenge. Even languages that share a character set may have different rules for hyphenation, spacing, quotation marks, punctuation, and so on. In addition to character shapes (glyphs ), issues such as directionality (whether the text reads left to right or right to left) and cursive joining behavior have to be taken into account. This section introduces the features included in HTML 4.01 and XHTML 1.0 and higher that address the needs of a multilingual Web.
Authors are strongly urged to specify the language for all HTML and XHTML documents. To specify a language for XHTML documents, use the xml:lang attribute in the html root element. HTML documents use the lang attribute for the same purpose . To ensure backward compatibility, the convention is simply to use both attributes, as shown in this example, which specifies the language of the document as French.

    <html xml:lang="fr" lang="fr" xmlns="http://www.w3.org/1999/xhtml" >

Users can set language preferences in their browsers. This language preference information is passed to the server when the user makes a request for a document. The server may use it to return a document in the preferred language if there is a document available that matches the language description.
The language attributes may be used in a particular element to override the language declaration for the document. In this example, a long quotation is provided in Norwegian.

    <blockquote xml:lang="no" lang="no">...</blockquote>

The value of the lang and xml:lang attributes is a language tag as defined in "Tags for the Identification of Languages" (RFC 3066 ). Language tags consist of a primary subtag that identifies the language according to a two-or three-letter language code (according to the ISO 639 standard ), for example,
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Style Sheets Language Features
Inhaltsvorschau
The first version of Cascading Style Sheets (CSS) did not include any mechanisms for dealing with anything but standard western, left-to-right languages.
CSS Level 2 introduced a few controls that specifically address multilingualism.
Directionality
The direction and unicode-bidi properties in CSS 2 allow authors to specify text direction, similar to the dir and bdo elements in HTML.
Quotation marks
The quotes property is used to specify quotation marks appropriate to the current language of the text. Generated quotation marks are discussed in Chapter 23.
CSS Level 3 addresses advanced foreign language attributes such as detailed specification of international numbering schemes, vertical text, and language-based text justification. International numbering schemes are published in the CSS 3 Lists Module ( www.w3.org/TR/css3-lists/ ). Text effects that accommodate internationalization efforts are published in the CSS 3 Text Effects Module ( www.w3.org/TR/css3-text/ ).
CSS 3 also includes a module for dealing with Ruby text . Ruby text is a run of text that appears alongside another run of text (the base). It serves as an annotation or pronunciation guide, as in the case of phonetic Japanese characters that run above the pictorial kanji symbols to aid readers who do not understand the symbols. More information can be found at www.w3.org/TR/css3-ruby/ .
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
For Further Reading
Inhaltsvorschau
If you are interested in learning more, the W3C Internationalization Activity Home Page ( www.w3.org/International/ ) makes a great jumping-off point for further exploration.
Another good resource is Babel, an Alis Technologies/Internet Society joint project to internationalize the Internet. It is available at alis.isoc.org/index.en.html .
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Chapter 7: Introduction to XML
Inhaltsvorschau
If you are thinking about skipping this chapter, please reconsider. While you may never need to be an XML expert, the basic concepts covered here will illuminate why things are done the way they are in the world of web document authoring. Furthermore, if you "get" XML, you'll understand the reasoning that influences all contemporary web design and related W3C Recommendations, from XHTML to CSS 2 and beyond.
XML (Extensible Markup Language) is a W3C standard for text document markup. It is not a language in itself (like HTML), but rather a set of rules for creating other markup languages. In other words, it is a meta-markup language. Languages written according to XML syntax are called XML applications (a confusing use of the word "application" to be sure, but such is the legacy jargon that SGML has left us). If this sounds a bit abstract, think of it this way: XML provides the tools for making up custom sets and subsets of tags.
Although XML began as an effort to improve information structure and handling on the Web, it has quickly taken the entire computing world by storm. In fact, today there is more XML used outside the Web than on it. XML is used for document sharing and data storage in fields as diverse as finance, retail, physics, travel, insurance, and academia, just to name a few. There are also XML files working behind the scenes in an increasing number of software applications, such as Microsoft Office, Macromedia Flash, and Apple iTunes. This is just a testament to the flexibility and robust nature of XML.
XML is having some of its intended impact on the Web as well. It is the cornerstone of the W3C's vision for the future of information exchange over networks.
XML is a complex topic, well beyond the scope of this web design book. This chapter provides an introduction to XML, focusing on the aspects of XML that are useful to web designers and developers, such as how it works, the basic syntax, terminology, and web-based XML applications.
The best way to get a feel for XML is to look at a quick example.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
XML Basics
Inhaltsvorschau
Here is a very simple XML document that is marked up with tags I made up to describe the liner notes for my famous end-of-the-year music compilations. (I could call it JenML).

<?xml version="1.0"?>

<compilation >

<title>Oh Baby! Jen's Favorites</title>

<year>2005</year>

<image source="ohbabycover.jpg"/>

<tracklist>

  <track number="1">

     <artist>The Wrens</artist>

     <song>

        <song_title>Hopeless</song_title> from

        <album_title>The Meadowlands</album_title>,

        <label>Absolutely Kosher Records</label>,

        <release_date>2003</release_date>

     </song>

     <comments>I love The Wrens, both musically and personally.</comments>

  </track>

<!--more tracks added here -->

</tracklist>

</compilation>

Certain things about this example should look familiar to anyone who has seen an HTML document. First, it is a plain-text document. As such, it can be created or edited in any text editor. It also uses tags in brackets to indicate the start and end of content elements in the document. Consider this element from the example:

<artist>The Wrens</artist>

The element includes the content (in this case, the character data "The Wrens") and its markup (the start tag <artist> and end tag </artist>). In XML, tags are case-sensitive, so <ARTIST>, <Artist>, and <artist>would be parsed as three different elements. Elements may contain character data, other elements, or both. Some elements are empty, which means they have no content. <meta/> is an example of an empty element in XHTML. Elements may be clarified or enhanced with attributes that provide extra information about that element. In the example, the image element uses the source attribute to provide the location of the image file.
The most significant thing to note here is that the tags describe the information they contain in a meaningful way. In XML, element names are intended to be simple, descriptive, and easily readable by human beings as well as machines. Notice also that the tags do not provide any indication of how the document should look when it is displayed. Their purpose is to provide a
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
How It Works
Inhaltsvorschau
XML has four basic components :
  • A document marked up in an XML language
  • An optional Document Type Definition or XML Schema that defines the elements and the rules for their use in that language
  • Style sheets for presentation instructions
  • Parsers that interpret the XML document
Take a closer look at each.
XML documents may be used for a wide variety of content. A document might be text based (such as a magazine article), or it might contain only numerical data to be transferred from one database or application to another. An XML document might also contain an abstract structure, such as a particular vector graphic shape (as in SVG) or a mathematical equation (as in MathML).
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
XML Document Syntax
Inhaltsvorschau
Now let's look at some of the particulars of XML syntax using this simple XML document:

<?xml version="1.0" encoding="US-ASCII" standalone="no"?>

<!DOCTYPE accounts SYSTEM "simple.dtd">

<accounts>

<customer>

    <name>

        <firstname>Bobby</firstname>

        <lastname>Five</lastname>

    </name>

    <accountNumber>4456</accountNumber>

    <balance>111.32</balance>

</customer>

<!-- more customers will be added soon -->

<?php  print date ('Fj,Y') ?>

</accounts>

Because XHTML is an XML application, all of the following syntax conventions apply to web documents written in XHTML.
The first line of the example is the XML declaration.

<?xml version="1.0" encoding="US-ASCII" standalone="no"?>

The XML declaration contains special information for the XML parser. First, the version attribute tells the parser that it is an XML document that conforms to Version 1.0 of the XML standard (which, incidentally, is the only available option).
In addition, the encoding attribute specifies which character encoding the document uses. By default, XML use the UTF-8 encoding of the Unicode character set (the most complete character set including glyphs from most of the world's languages). Alternate encodings may also be specified, such as ISO-8859-1 (Latin-1), which is a set containing characters from most Western European languages. Character encodings are discussed in more detail in Chapter 6.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Well-Formed XML
Inhaltsvorschau
Browsers often recover from sloppily written or illegal HTML. This is not the case with XML documents. Because XML languages vary, the rules for coding the document need to be followed to the letter to ensure proper interpretation by the XML client. In fact, the XML specification strictly prohibits XML parsers from trying to read or render documents with syntax errors. When a document follows the XML markup syntax rules, it is said to be well-formed . Documents that have incorrect syntax are referred to as malformed .
The primary rules for a well-formed XML document are:
  • There may be no whitespace (character spaces or line returns) before the XML declaration, if there is one.
  • An element must have both an opening and closing tag, unless it is an empty element.
  • If an element is empty, it must contain a closing slash before the end of the tag (for example, <br/>).
  • All opening and closing tags must nest correctly and not overlap.
  • There may not be whitespace between the opening < and the element name in a tag.
  • All element attribute values must be in straight quotation marks (either single or double quotes).
  • An element may not have two attributes with the same name.
  • Comments and processing instructions may not appear inside tags.
  • No unescaped < or & signs may occur in the character data of an element or attribute.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Document Type Definition (DTD)
Inhaltsvorschau
A Document Type Definition (DTD) is a file associated with SGML and XML documents that defines how markup tags should be interpreted by the application reading the document. The DTD uses SGML syntax to explain precisely which elements and attributes may appear in a document and the context in which they may be used. DTDs were briefly introduced earlier in this chapter. In this section, we'll take a closer look.
A DTD is a text document that contains a set of rules, formally known as element declarations , attlist (attribute) declarations, and entity declarations. DTDs are most often stored in a separate file (with the .dtd suffix) and shared by multiple documents; however, DTD information can be included inside the XML document as well. Both methods are demonstrated later in this section.
XML documents specify which DTD they use via a document type declaration (also called a DOCTYPE declaration
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
XML Namespaces
Inhaltsvorschau
An XML document may use tags that come from different XML applications or vocabularies. For example, you might have an XHTML document that also contains some math expressions written using MathML. But in this case, the parser needs to differentiate between an a element coming from XHTML (an anchor) and an a element that might come from MathML (an absolute value).
The W3C anticipated such conflicts and responded by creating the namespace convention (see the Recommendation at www.w3.org/TR/REC-xml-names ). A namespace provides a name for a particular XML vocabulary, the group of element and attribute names used in an XML application. This allows several XML vocabularies to be used in a single XML document.
When you reference elements and attributes in your document, the browser looks them up in the namespace to find out how they should be used. Namespaces have names that look just like URLs (they are not links to actual documents, however) to ensure uniqueness and provide information about the organization that maintains the namespace.
Namespaces are declared in an XML document using the xmlns attribute. You can establish the namespace for a whole document or an individual element. Typically, the value of the xmlns attribute is a reference to the URL-like namespace. This example establishes the default namespace for the document to be transitional XHTML:

<html xmlns="http://www.w3.org/1999/xhtml">

If you need to include math markup, you can apply the xmlns attribute within the specific tag, so the browser knows to look up the element in the MathML DTD (not XHTML):

<a xmlns="http://www.w3.org/1998/Math/MathML">46/100</a>

If you plan to refer to a namespace repeatedly within a document, you can declare the namespace and give it a label just once at the beginning of the document. Then refer to it in each tag by placing the label before the tag name, separated by a colon (:). For example:

<html xmlns="http://www.w3.org/1999/xhtml"

      xmlns:math="http://www.w3.org/1998/Math/MathML">

Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
XML on the Web
Inhaltsvorschau
As mentioned earlier, XML turned out to have uses that reach far beyond web documents , but it is still the W3C's primary tool for optimizing information exchange over the Web. XML is put to use on the Web in several ways.
The most common is XHTML, a reformulation of HTML according to the stricter syntax rules of XML. XHTML is formally introduced in the next section and is discussed in detail in the Chapters 8 through 15.
XHTML 1.1 can be combined in documents with other XML vocabularies such as MathML and SVG (Scalable Vector Graphics; discussed next). Namespaces help the parser keep track of which elements belong to which application (note that this requires a browser that supports namespaces ).
XML documents may also be displayed directly in web browsers that support XML. The "Browser Support" section provides more information on how browsers deal with XML.
Finally, one of the most widespread uses of an XML-based format for web content is in the form of RSS feeds that allow summaries of web content (or the content itself) to be shared on other sites or read with a special reader. RSS is discussed in detail in the following section.
The W3C keeps a directory of Recommended DTDs to use in web documents at www.w3.org/QA/2002/04/valid-dtd-list.html .
All of the current browser versions produced by Microsoft, Mozilla, and Opera support XML in some form. Table 7-2 lists each of the browsers and the XML features they support.
Table 7-2: Browser support for XML
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Web-Related XML Applications
Inhaltsvorschau
XML is already being put to powerful uses on the Web. Some languages, like XHTML and RSS, are expanding the possibilities of web-based content and changing the way we use the Web itself. Others have found small niche uses (such as SMIL and MathML) or have yet to live up to their promised potential (such as SVG). This section introduces these XML languages and others that are relevant to the Web.
Figure 7-1: An unstyled XML document displayed in Firefox 1.0
Figure 7-2: An XML document with a CSS style sheet displayed in Firefox 1.0
In the context of XML, XHTML is a language for describing the content of hypertext documents intended to be viewed or read in some sort of browsing client. It uses a DTD that declares such elements as paragraphs, headings, lists, and hyperlinks. It uses the namespace http://www.w3.org/1999/xhtml .
In the context of web design, XHTML is the updated version of HTML and is the current W3C recommendation for authoring web pages. It has all the same elements and attributes as the HTML 4.01 Recommendation, but where HTML was written according to the broader rules of SGML, XHTML has been rewritten according to XML syntax. That means that XHTML documents need to be well-formed, requiring more stringent markup practices. XHTML is by far the dominant use of XML on the Web.
XHTML is discussed in great detail in Chapters 8 through 15.
RSS is an XML language and file format for syndicating web content. The elements in the RSS vocabulary provide metadata about content (such as its headline, author, description, and originating site) that allows content to be shared as data, known as an
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Where to Learn More
Inhaltsvorschau
If you are interested in learning more about XML, you will want to check out Learning XML by Erik T. Ray and XML in a Nutshell by Elliotte Rusty Harold and W. Scott Means, both published by O'Reilly.
The growth and development of XML is well documented online in resources such as the following:
World Wide Web Consortium( www.w3.org )
The World Wide Web Consortium's official web site is the best place to go for the latest news on new XML standards and proposals.
XML.com ( www.xml.com )
XML.com, part of the O'Reilly Network, is a clearinghouse of great articles and information on XML.
The XML Cover Pages ( www.oasis-open.org/cover/xml.html )
The Cover Pages hosted by Oasis provide a comprehensive reference on all XML-related topics.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Chapter 8: HTML and XHTML Overview
Inhaltsvorschau
HTML (Hypertext Markup Language) is the markup language used to turn text documents into web pages. HTML allows authors to identify elements that give the document structure, such as headings, paragraphs, lists, and so on. Other elements act as mechanisms for adding hypertext links, interactive forms, and media such as audio and video to web pages.
HTML has undergone quite a journey since its creation by Tim Berners-Lee in 1991 as a simple way to indicate the meaning and structure of hypertext documents. It didn't take long for competing browser developers to add on to the initial minimal set of HTML elements or for the first crop of web designers to co-opt HTML as a visual design tool.
XHTML is a reformulation of HTML in XML. In other words, it uses the same vocabulary (the same elements and attributes) as HTML, but the syntactical rules are pulled from XML, which is stricter than HTML. XHTML is discussed in detail later in this chapter.
Before we delve into HTML and XHTML syntax, let's take a moment to look at the important role (X)HTML plays as well as the recent groundswell of respect it has earned in the new standards-driven web design environment.
The marked up HTML document is said to be the structural layer of a web page. It is the foundation upon which the presentation layer (instructions for how the elements should be delivered or displayed) and the behavioral layer (scripting and interactivity) are applied.
Did you happen to read the preceding XML chapter? It may seem off the topic of HTML, but there are some critical XML-based concepts there that guide the way HTML is perceived and handled in contemporary web design. One guiding concept is that the fundamental purpose of HTML as a markup language is to provide a
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
The Role of HTML
Inhaltsvorschau
The marked up HTML document is said to be the structural layer of a web page. It is the foundation upon which the presentation layer (instructions for how the elements should be delivered or displayed) and the behavioral layer (scripting and interactivity) are applied.
Did you happen to read the preceding XML chapter? It may seem off the topic of HTML, but there are some critical XML-based concepts there that guide the way HTML is perceived and handled in contemporary web design. One guiding concept is that the fundamental purpose of HTML as a markup language is to provide a semantic description (the meaning) of the content and establish a document structure. It is not concerned with presentation, such as how the document will look in a browser. Presentation is the job of Cascading Style Sheets, which is covered in Part III.
That presentational instructions should be kept separate from the semantic and structural markup is nothing new. It has been the intent of HTML from its beginning as an application of SGML (Standardized General Markup Language) as noted in the upcoming sidebar. What is new is that the web community is recognizing that there are measurable advantages (in terms of time and money) to using HTML for what it was designed to do, and nothing more.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Markup Basics
Inhaltsvorschau
An HTML or XHTML document is an ASCII (plain text), or more often, Unicode (e.g., UTF-8) document that has been marked up with tags that indicate elements and other necessary declarations (such as the markup language it is written in). An element is a structural component (such as a paragraph) or a desired behavior (such as a line break). This section introduces the key components and behaviors of HTML documents, including elements, attributes, how elements may be nested, and information in a document that is ignored by browsers.
Elements are denoted in the text source by the insertion of special bracketed HTML tags. Most elements follow this syntax.

<element-name>content</element-name>

The element name appears in the start tag (also called the opening tag) and again in the end (or closing ) tag, preceded by a slash (/). The end tag works something like an "off" switch for the element. Nothing within the brackets is displayed by the browser or other user agent. It is important to note that the element includes both the content and its markup (the start and end tags ).
In XHTML, all element and attribute names must be lowercase. HTML is not case sensitive.
Consider this example of HTML markup that identifies the content at the beginning of this section as a second-level heading element and a paragraph element:

<h2>Elements</h2>

<p>Elements are denoted in the text source by the insertion of special bracketed HTML

tags. Most elements follow this syntax.</p>

In HTML 4.01 and earlier, the end tag for some elements is optional, and the browser determines when the tag ends by context. This practice is most common with the p (paragraph) element. Most browsers automatically end a paragraph when they encounter a new start tag. In XHTML, end tags are always required.
Some elements do not have content because they are used to provide a simple directive. These elements are said to be
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Introduction to XHTML
Inhaltsvorschau
With the finalization of the XML Recommendation in hand (see Chapter 7), the W3C had a streamlined and web-friendly standard for defining markup languages. It should come as no surprise that one of the top priorities was reformulating HTML (an SGML application) into an XML application. XHTML is the result.
XHTML 1.0 contains the same list of elements and attributes as HTML 4.01. It even has the same three associated DTDs: Strict, Transitional, and Frames. The difference is that, as for all XML applications, correct syntax is suddenly critical. So while browsers are forgiving of a certain amount of looseness in HTML, XHTML documents are required to be well-formed. The syntax requirement differences between HTML and XHTML are listed in the upcoming "Well-Formed XHTML" section. The W3C recognizes the benefit of having a stricter professional standard and a more relaxed standard that is accessible to anyone who wants to publish on the Web, so both HTML and XHTML standards are currently maintained and supported by current browsers.
XHTML is not just one, but a family of document types. Between January 2000 and June 2001, the W3C turned out four XHTML Recommendations: XHTML 1.0, XHTML Basic, the Modularization of XHTML, and XHTML 1.1. They are currently reviewing XHTML 2.0 and XHTML-Print, both based on modular XHTML. This section takes a brief look at each one. You can find detailed and up-to-date information on the W3C site at w3c.org/MarkUp. (For example, on May 27, 2005, the seventh working draft of XHTML 2.0 was published.)

Section 8.3.1.1: XHTML 1.0

The XHTML 1.0 Recommendation (released in January 2000) is just a reformulation of the HTML 4.01 specification according to the rules of XML. Like HTML 4.01, XHTML 1.0 comes in three varieties—Strict, Transitional, and Frames—each defined by a separate Document Type Definition (DTD). These are discussed in the next section.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Which Standard Is Right for You?
Inhaltsvorschau
With so many co-existing Recommendations, it may be difficult to choose which one is best for your purposes. The following is a quick summary that will put all of these options into perspective.
XHTML 1.0 Transitional
Use this standard if your authoring style makes use of any of the deprecated elements (such as font) or attributes (such as bgcolor or align) and you have the discipline (or authoring tools) it takes to make sure the document is well-formed. This is the most popular choice for professional web developers because it is forward compatible, yet still allows some of the legacy techniques required to control presentation in current browsers.
XHTML 1.0 Strict
Use XHTML Strict if you are committed to using style sheets for all presentation and layout because all of those deprecated tags have been removed from this Recommendation. Documents must be well-formed as well, of course.
HTML 4.01
Use Transitional, Strict, or Frames if you aren't concerned with site longevity, if you are not using updated authoring tools, or if you can't bring yourself to close an li element.
XHTML 1.0 Frames or HTML 4.01 Frames
Use if you are creating a framed site. All deprecated attributes are still in there.
XHTML 1.1
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Well-Formed XHTML
Inhaltsvorschau
Web browsers are forgiving of sloppy HTML, but XHTML (being an XML application) requires that you play by the rigid rules of XML markup syntax. What makes XHTML documents different from HTML documents is that you need to be absolutely sure that your document follows the syntax rules of XML correctly (in other words, that it is well-formed ). The sections below summarize the requirements of well-formed XHTML as well as some tips for backward compatibility with older browsers.
In XML, all elements and attribute names are case-sensitive, which means that <img>, <Img>, and <IMG> are parsed as different elements. In the reformulation of HTML into XHTML, all elements were interpreted to be lowercase. When writing XHTML documents (and their associated style sheets), be sure that all tags and attribute names are written in lowercase. Attribute values are not required to be case-sensitive.
If you want to convert the upper- and mixed-case tags in an existing HTML file to well-formed, all-lowercase tags, try the HTML Tidy utility (tidy.sourceforge.net/) or Barebones Software BBEdit (Macintosh only, www.bbedit.com), which can automate the process.
XHTML requires that all attribute values be contained in quotation marks . Double or single quotation marks are acceptable, as long as they are used consistently throughout the document. So where previously it was okay to omit the quotes around single words and numeric values, now you need to be careful that every attribute value is quoted.
In HTML, it is okay to omit the end tag for certain block elements (such as p and li). The beginning of a new block element is enough to trigger the browser to parse the previous one as closed. Not so in XHTML. To be well-formed, every container element must have its end tag, or it registers as an error and renders the document noncompliant.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Web Authoring Tools
Inhaltsvorschau
HTML documents are simple text files, which means you can use any minimal text editor to write them. Fortunately, there are a number of tools that make the process of generating HTML documents more quick and efficient. They fall into two main categories: HTML editors and WYSIWYG (What-You-See-Is-What-You-Get) web authoring tools .
HTML editors are text editing tools designed especially for writing HTML. They require that you know how to compose HTML by hand; however, they save time by providing shortcuts for such repetitive tasks as setting up documents, compiling tables, or simply applying styles to text.
There are scores of simple HTML editors available, and many of them are free. Just enter "HTML Editor" in the search field of Shareware.com (www.shareware.com) and wade through the results. For purposes of brevity, I'm going to cut to the chase.
Windows users should check out Macromedia HomeSite. For more information and to download a demo copy, see www.macromedia.com/software/homesite/.
If you're working on a Macintosh, check out BBEdit, a commercial HTML editor from Bare Bones Software, Inc. For more information and to download a demo version, see www.bbedit.com.
WYSIWYG HTML editors have graphical interfaces that make writing HTML more like using a word processor or page layout program. So for instance, if you want to add an image, just drag it from the desktop onto the page; the authoring tool creates all the HTML coding needed to accomplish the effect on the screen. In addition to simple style and format shortcuts, many of these tools automate more complex tasks, such as creating Cascading Style Sheets, adding JavaScript, and adding PHP functionality.
WYSIWYG tools offer several benefits:
  • They offer considerable time savings over writing code by hand.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Good Authoring Practices
Inhaltsvorschau
This section offers some guidelines for writing "good" HTML documents—markup that will be supported by a wide variety of browsers, handled easily by browsers expecting correct syntax, and extensible to emerging technologies built on the current HTML specification.
Choose elements that accurately and meaningfully describe the content
Making sure that your document is semantically sound improves accessibility under the wide range of web browsing environments. If something is a list, mark it up as a list. If you don't want bullets, it's not a problem. You can use a style sheet to change the presentation of the list to be anything you want, be it bullet-less or a graphical horizontal navigation bar (see Chapter 24 for this technique).
Avoid choosing elements based on the way that they render in the browser.
For example, don't use a blockquote just to achieve indented text and don't use a series of brs or <p>&nbsp;</p> for extra whitespace. Again, you can use a style sheet for such presentational effects.
Avoid using deprecated elements and attributes.
This is actually a round-about way of saying "use style sheets instead of presentational HTML," because most elements and attributes have been deprecated in favor of style sheet controls.
Write compliant, valid documents.
Even if you are using HTML 4.01, it is a good idea to follow the XHTML Recommendations for a compliant, valid document. Although once it was fine to omit closing tags and quotation marks, browsers in the future may not be so forgiving.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Chapter 9: Document Structure
Inhaltsvorschau
Before marking up your actual content, it is necessary to establish the proper global structure of the (X)HTML document itself. An (X)HTML document is composed of three parts: a declaration of the HTML or XHTML version used, a header containing information about the document, and the body containing the document's content. This chapter takes a look at each of these components and, in doing so, introduces these elements used for establishing the global structure of the document:
html
Root element of an (X)HTML document
head
Header
body
The body of the document
title
Document title
meta
Meta data (information about the document)
If you use a professional web authoring tool to create web pages, chances are you're accustomed to the minimal document structural markup inserted for you when you select "New File." This chapter will give you the tools necessary to peek under the hood and decide if the automatically generated declarations accurately represent the mode in which you intend to author.
This markup sample shows the structure of a minimal XHTML document as specified in the XHTML 1.0 Recommendation. It provides important context to upcoming discussions of global document structure.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Minimal Document Structure
Inhaltsvorschau
This markup sample shows the structure of a minimal XHTML document as specified in the XHTML 1.0 Recommendation. It provides important context to upcoming discussions of global document structure.

    <?xml version="1.0" encoding="UTF-8"?>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">



    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">



      <head>

        <title>Document Title</title>

      </head>



      <body>

        <p>Content of document...</p>

      </body>



    </html>

This example begins with an XML declaration that identifies the version of XML and the character encoding of the document. XML declarations are encouraged for XHTML documents; however, they are not required when the character encoding is the UTF-8 default as in the above example. Because XML declarations are problematic for current browsers as of this writing, even those that are standards-compliant, they are generally omitted.
Now, take a closer look at the four major components of XHTML (and HTML) documents.
Document type declaration

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

The document type (DOCTYPE) declaration tells the browser which DTD to use to parse the document. This example specifies XHTML Strict. If this example were an HTML document, it would use one of the HTML DTDs. The upcoming See Document Type Declaration." section provides more information on the DTD options and uses for this information.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Document Type Declaration
Inhaltsvorschau
To be valid, an (X)HTML document must begin with a document type declaration that identifies which version of HTML or XHTML is used in the document. This is done using a DOCTYPE declaration that names the document type definition (DTD) for the document. A DTD is a text document that lists all the elements, attributes, and rules of use for a particular markup language. See Chapter 7 for more information on DTDs.
The inclusion of a document type declaration has always been a requirement of valid HTML documents. With no DOCTYPE declaration, there is no set of rules to validate against. In the years of fast and loose HTML authoring, the DOCTYPE declaration was commonly omitted. However, now that standards compliance is a priority in the web development community, and because there are so many DTDs to choose from, authors are strongly urged to include the DTD declaration and validate their documents. The DOCTYPE declaration (or its omission) also triggers different browser behaviors, as discussed in the upcoming "DOCTYPE Switching" section.
HTML 4.01 and XHTML 1.0 offer three DTD versions:
  • Strict
  • Transitional
  • Frameset
XHTML 1.1 has only one DTD. The DTD documents live on the W3C server at a stable URL.
The <!DOCTYPE> (document type) declaration contains two methods for pointing to DTD information: one is a publicly recognized document identifier; the other is a specific URL in case the browsing device does not recognize the public identifier. Descriptions and specific markup for each HTML and XHTML version are listed here.
HTML 4.01 Strict
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
The Root Element
Inhaltsvorschau
XML and SGML documents have one and exactly one root element. It is the element that encloses all following elements. XHTML and HTML define html as the root element.

html

    <html>...</html>

Attributes
Internationalization attributes: lang, xml:lang, dir
id="text" (XHTML only)
xmlns="http://www.w3.org/1999/xhtml" (Required; XHTML only)
version="-//W3C//DTD HTML 4.01//EN" (Deprecated in HTML 4.01)

All elements in the document are contained within the root element (they are said to be descendants of the root element). As the root element, html may have no ancestors (in other words, it may not be contained within any other element).
This example shows the root element from a minimal XHTML document:

    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en" >

Because this example is an XHTML document, the html element is also used to identify the XML namespace and language for the document, as discussed next. HTML documents do not use namespaces.

Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
The Document Header
Inhaltsvorschau
The header provides a place to include important information about the document to users, browsers, and search engines. It is also a common place to stow scripts and embedded style sheets. This section looks at the head element and the elements it contains.

head

    <head>...</head>

Attributes
Internationalization attributes: lang, xml:lang, dir
id="text" (XHTML only)
profile=" URLS "

Every head element must include a title element that provides a description of the document. The head element may also include any of the following elements in any order: script, style, meta, link, object, isindex, and base. The head element merely acts as a container of these elements and does not have any content of its own.
It is recommended that HTML documents (and XHTML documents without an XML declaration) also include a meta element that specifies the content type and character encoding for the document, although this element is not required. The meta element is discussed in the upcoming "Providing Meta Data section.

The most important (and only required) element within the header is the document title, which provides a description of the page's contents.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
The Document Body
Inhaltsvorschau
The body of the document comes after the document header. Although the body element markup is optional in previous versions of HTML, in XHTML it is required. The content of the body element is what gets displayed in the browser window (or read by a speech browser).
body

    <body>...</body>

Attributes
Core attributes: id, class, style, title
Internationalization: lang, xml:lang, dir
Intrinsic Events: onload, onunload, onclick, ondblclick, onmousedown, onmouseup, onmouseover, onmousemove, onmouseout, onkeypress, onkeydown, onkeyup
Deprecated Attributes
alink="# rrggbb " or " color name "
background=" URL "
bgcolor=" #rrggbb " or " color name "
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Chapter 10: Text Elements
Inhaltsvorschau
This chapter gets to the real meat and potatoes of document markup: elements used to structure text content. It's no surprise that nearly half of all the elements in the (X)HTML Recommendation are introduced in this chapter. The elements and discussions are organized as follows:
Block elements
Generic elements
h#
Heading
div
Block division
p
Paragraph
span
Span of inline content
pre
Preformatted text
Lists
address
Contact information
ul
Unordered list
blockquote
Lengthy quotation
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Choosing Text Elements
Inhaltsvorschau
This chapter, jam-packed as it is with text elements, is a good opportunity for a reminder about the importance of well-structured and meaningful (semantic ) markup.
In the early years of web design, it was common to choose elements based on their default formatting in the browser. Don't like the size of the h1? Hey, use an h4 instead. Don't like bullets on your list? Make something list-like using br elements. Need indents? Blockquote it! Those days are over and gone.
Now we have Cascading Style Sheets (CSS) to visually format any element any way we like, at last liberating us from the browsers' default rendering styles. That means you must choose elements that accurately describe your content. If you don't like how it looks, change it with a style sheet. If you don't see an HTML element that fits, use a generic div or span element to add appropriate structure and meaning.
Additional tips on good markup are listed in Chapter 8.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
The Building Blocks of Content
Inhaltsvorschau
Text elements fall into two broad categories: inline and block. Inline elements occur in the flow of text and do not cause line breaks by default (they are covered later in this chapter). Block-level elements, on the other hand, have a default presentation that starts a new line and tends to stack up like blocks in the normal flow of the document. Block elements make up the main components of document structure.
Compared to inline elements, there are relatively few block elements. This section looks at heading levels, paragraphs, blockquotes, preformatted text, and addresses. Lists and list items are also block elements, and they are discussed later in this chapter, as is the generic div element used for defining custom block elements. The other block-level elements are tables and forms, which are treated in their own respective chapters.
Headings are used to introduce ideas or sections of text. (X)HTML defines six levels of headings, from h1 to h6, in order from most to least important.
h1 through h6

    <hn>...</hn>

Attributes
Core (id, class, style, title), Internationalization, Events
Deprecated attributes
align="center|left|right"
This example defines the element as a first-level heading.

    <h1>Camp Sunny-Side Up</h1>

HTML syntax requires that headings appear in order (for example, an h2 should not precede an h1) for proper document structure. Doing so not only improves accessibility, but aids in search engine optimization (information in higher heading levels is given more weight). Using heading levels consistently throughout a site—using
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Inline Elements
Inhaltsvorschau
Most text elements are inline elements (spans of characters within the flow of text). Inline elements by default do not add line breaks or extra space.
This section introduces the semantic text elements that describe the enclosed text's meaning, context, or usage. These elements leave the specific rendering of the element to style sheets, either the author's or the browser's default rendering. There are other inline elements in the XHTML specification that are concerned with presentation (for example, the b element for bold text). They are briefly discussed at the end this chapter.
HTML 4.01 and XHTML 1.0 and 1.1 define a collection of phrase elements (also called logical elements) for adding structure and meaning to inline text. Because phrase elements share syntax and attributes, they are aggregated into one element listing here.

abbr, acronym, cite, code, dfn, em, kbd, samp, strong, var

    <abbr>...</abbr>, <acronym>...</acronym>, etc.

Attributes
Core (id, class, style, title), Internationalization, Events
Phrase elements may contain other inline elements. The meaning and use of each element is listed here. When elements have a standardized presentation in browsers (for example, em elements universally display in an italic font), it is also noted. Authors are reminded, however, to choose elements based on meaning, not a desired rendering effect.
em

Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Deleted and Inserted Text
Inhaltsvorschau
The ins and del elements are used to mark up changes to the text and indicate parts of a document that have been inserted or deleted (respectively). They may be useful for legal documents and any instance where edits need to be tracked.
As HTML elements, ins and del are unusual in that they may be used to indicate both block-level and inline elements. They may contain one or more words in a paragraph or one or more elements like paragraphs, lists, and tables. When ins and del are used as inline elements (as in within a p), they may not contain block-level elements because that violates the allowable content of the paragraph.
del, ins

    <del>...</del>, <ins>...</ins>

Attributes
Core (id, class, style, title), Internationalization, Events
cite=" URL "
datetime=" YYYY-MM-DDThh:mm:ssTZD "
The following markup indicates that one name has been deleted and another one inserted in its place.

    Chief Executive Officer: <del title="retired">Peter

Pan</del> <ins>Pippi Longstockings</ins>

Browsers that support the ins and del elements may give it special visual treatment (for example, displaying deleted text in strike-through text), but authors are encouraged to use style sheets to provide presentational instructions.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Generic Elements (div and span)
Inhaltsvorschau
The generic div and span elements provide a way for authors to create custom elements. The div element is used to indicate block-level elements, while span indicates inline elements. Both generic elements rely on id and class attributes to give them a name, meaning, or context.
The div element is used to identify and label any block-level division of text, whether it is a few list items or an entire page.
div

    <div>...</div>

Attributes
Core (id, class, style, title), Internationalization, Events
Deprecated attributes
align="center|left|right"
By marking a section of text as a div and giving it a name using id or class attributes, you are essentially creating a custom HTML element. In this example, a heading and a list are enclosed in a div identified as "sidebar."

    <div id="sidebar">

        <h1>List of links</h1>

        <ul>

            <li>Resource 1</li>

            <li>Resource 2</li>

            <li>Resource 3</li>

        </ul>

    </div>

Because a div is a block-level element, its contents will start on a new line (even text not contained within other block-level elements). Otherwise, div elements have no inherent presentation qualities of their own.
The div really shines when used in conjunction with Cascading Style Sheets. Once you've marked up and named a
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Lists
Inhaltsvorschau
Humans are natural list-makers, so it makes sense that mechanisms for creating lists of information have been part of HTML since its birth. This section looks at the types of lists defined in (X)HTML:
  • Unordered information
  • Ordered information
  • Terms and definitions
Unordered lists are used for collections of related items that appear in no particular order. Most lists fall into this category. Just about any list of examples, components, thoughts, or options should be marked up as an unordered list. Most notably, unordered lists are the element of choice for navigational options. Unordered lists for navigation are discussed later in this section.
In (X)HTML, unordered lists are denoted with the ul element. The content of a ul is limited to one or more list items (li). List items may contain either block-level or inline elements, or both. Unordered lists and their list items are block elements, so each will display starting on a new line.

ul

    <ul>...</ul>

Attributes
Core (id, class, style, title), Internationalization, Events
Deprecated attributes
compact
type="disc|circle|square"

Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Presentational Elements
Inhaltsvorschau
There are a handful of (X)HTML elements that are explicitly presentation oriented. Sometimes called "physical" styles, they provide instructions for the size, weight, or style of the font used to display the element.
If you've been paying attention, you already know that Cascading Style Sheets are now the preferred way to specify presentation instructions. Table 10-2 lists the presentational inline elements, along with the preferred alternative for achieving the same visual effect.
Table 10-2: Presentational inline elements and style sheet alternatives
Element
Description
Alternative
b
Bold
Use the strong element instead if appropriate, or use the font-weight property:

    font-weight: bold

big
Big
Use a relative font-size keyword to make text display slightly larger than the surrounding text:

    font-size: bigger

i
Italic
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Character Entity References
Inhaltsvorschau
Characters not found in the normal alphanumeric character set, such as < and &, must be specified in HTML and XHTML documents using character references . This is known as escaping the character. Using the standard desktop publishing keyboard commands (such as Option-G for the © symbol) within an HTML document will not produce the desired character when the document is rendered in a browser. In fact, the browser generally displays the numeric entity for the character.
In (X)HTML documents, escaped characters are indicated by character references that begin with & and end with ;. The character may be referred to by its Numeric Character Reference (NCR) or a predefined character entity name.
A Numeric Character Reference refers to a character by its Unicode code point in either decimal or hexadecimal form (for more information on Unicode and code points, see Chapter 6). Decimal character references use the syntax &# nnnn ;. Hexadecimal values are indicated by an "x": &# xhhhh ;. For example, the less-than (<) character could be identified as &#60; (decimal) or &#x3C; (hexadecimal).
Character entities are abbreviated names for characters, such as &lt; for the less-than symbol. Character entities are predefined in the DTDs of markup languages such as HTML and XHMTL as a convenience to authors, because they may be easier to remember than Numeric Character References.
XHTML includes the XML entity declaration for the apostrophe (&apos;). In HTML, the apostrophe character entity was curiously omitted, so its numeric reference (&039;) must be used instead.
Table 10-3 presents the (X)HTML character entities and numeric character references for commonly used special characters. The complete list of character entities defined in HTML 4.01 and XHTML 1.0/1.1 appears in Appendix C.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Chapter 11: Creating Links
Inhaltsvorschau
The HTML 4.01 specification puts it simply and clearly: "A link is a connection from one web resource to another." This ability to create hyperlinks from one document to another is what makes HTML unique among document markup languages and is the key to its widespread popularity. You can create a link to any web resource, including (but not limited to) another HTML document, an image, a program, or a particular element within an HTML document.
This chapter focuses on these HTML elements related to linking and building relationships between documents.
a
Anchor (link)
base
Provides a base pathname
link
Establishes relationship between documents
The anchor (a) element is used to identify a string of text or an image that serves as a hypertext link to another document.
a

<a>...</a>

Attributes
Core(id, class, style, title)
Internationalization
Events(plus onfocus, onblur)
accesskey=" character
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Simple Hypertext Links
Inhaltsvorschau
The anchor (a) element is used to identify a string of text or an image that serves as a hypertext link to another document.
a

<a>...</a>

Attributes
Core(id, class, style, title)
Internationalization
Events(plus onfocus, onblur)
accesskey=" character "
charset=" charset "
coords=" x,y coordinates "
href=" URL "
id=" text "
hreflang=" language code "
name=" text "
rel=" relationships "
rev=" relationships "
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Linking Within a Document
Inhaltsvorschau
By default, when you link to a page, the browser displays the top of that page. You may also link to a particular point in a web page (called a fragment).
Linking to document fragments is most often used as a navigational aid by creating a hyperlinked table of contents at the top of a very long scrolling web page. Users can see the major topics at a glance and quickly get to the portions that interest them. When linking down into a long page, it is generally a good idea to add links back to the top of the page or to the table of contents. You can also link to fragments in other documents (as long as they have been named).
Linking to specific destinations in a document is a two-step process in which you give an identifying name to an element and then make a link to that marker.
HTML provides two ways to identify a document fragment: by inserting an anchor (a) element with the name attribute (instead of href) or by adding the id attribute to any HTML element. Both methods act as a marker that can be referenced from a link later.
XHTML documents must use the id attribute for all fragment identifiers in order to be well-structured XML. Unfortunately, the id attribute is not universally supported by all browsers for this purpose (support is lacking in Version 4 browsers). To ensure maximum backward and forward compatibility, the XHTML Recommendation suggests redundant markup using both id and name in the a element.
In this example, a named anchor is used to let users link directly to a "Stock Quotes" section of a web document called dailynews.html. First, the heading is marked up as a named anchor with the name "stocks." Named anchors receive no special style treatment by default (in other words, they are not underlined like anchors with the href attribute).

<h1><a name="stocks" id="stocks">Daily Stock Quotes
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Targeting Windows
Inhaltsvorschau
The problem with a hypertext medium is that when users click on an interesting link that takes them off your page, they might never come back. One solution to this problem is to make the target document appear in a second browser window that opens automatically. In that way, your page is still readily available in the background.
This technique is not without controversy, however. Windows that open automatically, also known as pop-up windows, are now strongly associated with intrusive web advertising. The population's distaste for them is so strong that there are a slew of pop-up blocker programs on the market and even built right into browsers. Consider whether a pop-up window is the best solution given the fact that some users may not see that content. Pop-up windows are also problematic from the standpoint of usability and accessibility. If you do use a pop-up window, it is advised that you let users know what to expect by adding a comment such as "link opens in new window."
The following technique simply opens a new browser window but does not control its size. To do that, you must use JavaScript.
To launch a new browser window for the linked document, use the target attribute in the a element. Setting the target attribute to the standardized "_blank" value causes the browser to open a fresh browser window. For example:

<a href="http://www.oreilly.com/" target="_blank">...</a>

Note that _blank opens a new browser window every time. So if you set every link on your page to target a _blank window, every link will launch a new window, potentially leaving your user with a mess of open windows.
A better method, especially if you have more than one link, is to give the targeted window a specific name, which can then be reused by subsequent links. The following link will open a new window called "display":

<a href="http://www.oreilly.com/" target="display">...</a>

All links that target a window called "display" will now load into that same browser window.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Alternative Protocols
Inhaltsvorschau
Linking to other web pages using the HTTP protocol is by far the most common type of link, but there are several other types of transactions that can be made using other standard Internet protocols.
The mailto protocol can be used in an a element to automatically send an email message to the recipient, using the browser's email application or an external email application. Note that the browser must be configured to support this protocol, so it will not work for all users. The mailto protocol has the following components:

mailto:username@domain

A typical mail link might look like this:

<a href="mailto:jen@oreilly.com">Send Jennifer email</a>

You can also experiment with adding information within the mailto URL that automatically fills in standard email fields such as Subject or cc:.

mailto:username@domain?subject=subject


mailto:username@domain?cc=person1


mailto:username@domain?bcc=person2


mailto:username@domain?body=body

Additional variables are appended to the string with an ampersand (&) symbol as shown:

mailto:username@domain?subject=subject&cc=person1&body=body

In XHTML, the ampersand (&) symbol must be escaped—that is, expressed as a character entity (&amp;) in the string—for the document to be valid. The same link in XHTML would be marked up like this:

mailto:username@domain?subject=subject&amp;cc=person1&body=body

Spaces within subject lines need to be written as %20 (the space character in hexadecimal notation). The following sample mail link employs these additions:

    <a href="mailto:jen@oreilly.com?subject=Like%20your%20book">Email for

    Jen</a>

When you put a link to an email address on a web page, the address is prone to getting "spidered" (automatically indexed) and added to spam mailing lists. To avoid getting spammed, do not put your intact email address in the source document, either as a mailto link or in the content itself. An alternative is to spell out the email address (such as "jen at oreilly dot com") so it is understandable to humans but not recognizable to spambots.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Linking Documents with link
Inhaltsvorschau
The link element defines a relationship between the current document and another external document. It is not the same as a hypertext link because it is not accessible by clicking or otherwise selecting a hyperlink. It is always placed in the header (head) of the document. There can be multiple link elements in a document.
link

<link />

Attributes
Core(id, class, style, title), Internationalization, Events
charset=" charset "
href=" URL "
hreflang=" language code "
media="all|screen|print|handheld|projection|tty|tv|projection|braille|aural"
rel=" relationships "
rev=" relationships "
target=" name "
type=" resource "
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Chapter 12: Images and Objects
Inhaltsvorschau
In addition to text content, web pages may include a wide range of multimedia objects, including images, image maps, Java applets, video, Flash movies, even other HTML documents. This chapter focuses on the (X)HTML elements defined for adding images and media objects, including:
img
Adds an image
map
The map used for an image map
area
A geometric region in an image map
object
A generic media object
param
Specifies values for an object necessary at runtime
embed
Embeds media requiring plug-ins (nonstandard)
noembed
Content displayed if embedded media is not supported (nonstandard)
applet
Adds an applet (deprecated)
iframe
A floating frame that displays an external HTML document
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Inline Images
Inhaltsvorschau
Inline images are images that occur in the normal flow of the document's content. As inline elements, they affect the visual display of other elements in the flow, unlike background images, which render behind elements. Images are added to the document with the img element. Images are considered to be replaced elements because the actual content resides in external files rather than in the source document.
The HTML 4.01 Recommendation allows images to be added using the generic object element, as demonstrated later in this chapter. Because the object method is not universally supported, the img element is still the primary element used to place images in web documents.
img

<img />

Attributes
Core (id, class, style, title), Internationalization, Events
alt=" text " (Required)
ismap
height=" number "
longdesc=" URL "
lowsrc=" URL "
name=" text "
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Image Maps
Inhaltsvorschau
Ordinarily, placing an image within an anchor element makes the entire image a link to a single document when the user clicks anywhere on the image. As an alternative, you can create an image map that contains multiple links, or "hotspots," within a single image. The effect is created with HTML markup (some image maps also use scripts on the server) and an ordinary image that serves as a backdrop for the pixel coordinates.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Embedded Media
Inhaltsvorschau
Images aren't the only things that can be displayed as part of a web page. You can also include content such as QuickTime movies, interactive Flash files, all manner of Java applets, and more. The browser renders embedded media files using the provided self-contained code (as in the case of an applet), using its built-in display devices (as for GIF or JPEG images), or by taking advantage of a plug-in or helper application (as for Windows Media or Flash).
The elements that embed media in (X)HTML are:
object
The W3C recommended element for all media
applet
For Java applets; deprecated in HTML 4.01 and XHTML 1.0
There is a third nonstandard (and therefore, nonvalidating) element for embedding media that is still used by browsers that use Netscape's plug-in architecture:
embed
For plug-in dependent media; not part of any HTML Recommendation
Now, take a closer look at each of these elements and their uses.
According to the HTML 4.01 Recommendation, the object element is an all-purpose object-placer. It can be used to place a variety of object types on a web page, including applets, movies, interactive objects (Flash), and even plain old images. As of this writing, browser support does not quite fulfill the W3C's vision for this element (for example, it still may not be used reliably as a replacement for the img element), however, the object element is still used for a wide range of embedded media .
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Java Applets
Inhaltsvorschau
Java is an object-oriented programming language developed by Sun Microsystems. It is not related to JavaScript, which is a scripting language developed by Netscape to run within an HTML document in a browser. Because Java is a full programming language (like C or C++), it can be used to create whole applications.
Java's primary contribution to web content, however, has been in the form of Java applets , which are self-contained, mini-executable programs. These programs, named with the .class suffix, can be placed right on the web page, like an image. Java applets can be used for all sorts of interactive and multimedia gadgets, such as clocks, calculators, spreadsheets, scrolling marquees, games, text effects, and digital "guitars," just to name a few.
There was a great buzz among web developers when Java applets first hit the scene, but since then, enthusiasm has waned in the face of performance issues (applets take a long time to initialize and tend to crash browsers) and the dominance of Flash for multimedia and interactivity.
If you need a customized applet for your site, your best bet is to hire a programmer to create one to your specifications. However, there are a number of applets available for free or for a licensing fee that you can download from libraries on the Web.
A good place to start is the applets section of Sun's Java site at java.sun.com/applets/. This page provides a list of links to applet-related resources.
If you are looking for cool applets you can use right away, try the JavaBoutique at javaboutique.internet.com. Here you will find hundreds of applets available for download as well as clear instructions for their use. It's a great way to add interactivity to your site without learning any programming.
There are currently two methods for adding an applet to a web page: the object element, recommended by HTML 4.01, and the better supported, though deprecated,
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Inline (Floating) Frames
Inhaltsvorschau
Microsoft Internet Explorer 3.0 introduced a feature called inline frames (also called floating frames ) that are identified with the iframe element. They enable an HTML document to be embedded within another HTML document, viewed in a scrollable frame. An iframe is placed in the document flow as an inline element, much like an image.
iframe

<iframe> ... </iframe>

Attributes
Core (id, class, style, title)
frameborder="1|0"
height=" number "
longdesc=" URL "
marginheight=" number "
marginwidth=" number "
name=" text "
scrolling="yes|no|auto"
src=" URL "
width="
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Chapter 13: Tables
Inhaltsvorschau
HTML table elements, first introduced in Netscape 1.1, were developed to give authors a way to present rows and columns of tabular data. In fact, that has always been and remains their intended use. But it didn't take long for designers, fed up with the one-column, full-width web pages, to co-opt tables as a tool for controlling page layout. For the last 10 years, complex table-based layouts have been the norm. Nobody cared much that it was a misuse of the table elements—there weren't any other options. Today, we do have an option. Cascading Style Sheets offer the ability to create multicolumn pages and sophisticated layouts that were previously achievable only with tables. With improved browser support, pure style sheet layouts are finally a viable solution.
So tables-for-layout are out, but that doesn't mean that the whole set of table elements has been tossed in the dustbin. In fact, tables are still the appropriate markup choice for real tabular data, such as schedules, statistics, and so on.
This chapter takes on the topic of HTML tables, starting with their basic structure and markup and moving on to methods that make data tables accessible when rendered non-visually. Tips for using layout tables responsibly are included as well. Along the way, the following table-related elements will be addressed.
table
Establishes a table
tr
Table row
td
Table cell
th
Table header cell
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Table Uses
Inhaltsvorschau
HTML tables fall into two broad categories: data tables and layout tables . This section takes a look at both types.
Data tables, the arrangement of information in rows and columns, are the intended use of HTML table elements. In visual browsers, the arrangement of data in rows and columns gives users an instant understanding of the relationships between data cells and their respective header labels. These relationships may be lost for users without the benefit of visual presentation unless care is taken to author the data table with accessibility in mind. These techniques are discussed in the upcoming "Accessible Tables" section.
Tables may be used to present calendars, schedules, statistics, or other types of information as shown in Figure 13-1. Note that "data" doesn't necessarily mean numbers. A table cell may contain any sort of information, including numbers, text elements, even images or multimedia objects.
Figure 13-1: Examples of data tables
Layout tables, unlike data tables, are used purely as a presentational device for controlling the layout of a page. The HTML 4.01 Recommendation specifically discourages this use of tables, but it wasn't until CSS became a viable alternative that they have been condemned by the professional web community at large as well.
You can't turn around on the Web without bumping into a site—even big-name sites—that still uses tables for layout . Some sites use tables as a minimal framework; others have complex tables nested several layers deep to hold things together. Figure 13-2 shows just a few examples of layout tables of varying levels of complexity. The borders have been enhanced to reveal the table structure. (As not to point any fingers, these "old-school" examples are all my own work; I assure you, I've changed my ways.)
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Basic Table Structure
Inhaltsvorschau
Put simply, web tables are made up of cells (which is where the content goes), arranged into rows. The HTML table model is said to be "row primary" because rows are identified explicitly in the document structure, while columns are just implied. The following examples illustrate the basic structure of an HTML table.
The minimum elements for defining a table are table, for establishing the table itself, tr for declaring a table row, and td for creating table cells within the row. Explanations and examples of how these elements fit together follow these element and attribute listings.

table

<table>...</table>

Attributes
Core(id, class, style, title), Internationalization, Events
border=" number "
cellpadding=" number of pixels or % "
cellspacing=" number of pixels or % "
frame="void|above|below|hsides|lhs|rhs|vsides|box|border"
rules="all|cols|groups|none|rows"
summary="

Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Row Groups
Inhaltsvorschau
HTML and XHTML define three "row group" elements that enable authors to organize rows into a table header (thead), footer (tfoot), and a table body (tbody). Because these elements share syntax and attributes, they have been aggregated into one element listing, presented here.
thead, tbody, tfoot

<thead>...</thead>, <tbody>...</tbody>, <tfoot>...</tfoot>

Attributes
Core(id, class, style, title), Internationalization, Events
align="left|center|right|justify|char"
char=" character "
charoff=" length "
valign="top|middle|bottom|baseline"
Internet Explorer 3.0 first introduced this system for grouping rows so they can be treated as units by user agents or style sheets. The W3C included the row group elements in the HTML 4.0 Recommendation as a way to allow more meaningful labeling, improve accessibility, and provide more flexibility for applying style sheet properties. Row groups are advantageous for data tables but should be avoided for layout tables.
The rows in a table may be grouped into a table head (thead), a table footer (tfoot), and one or more table bodies (tbody
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Columns and Column Groups
Inhaltsvorschau
As mentioned earlier in this chapter, the columns in a table are just implied by the number of cells in the longest row. In some instances, however, it is desirable to identify conceptual columns of data cells or groups of columns. The col (column) and colgroup (column group) elements allow authors to conceptually join a group of cells that appear in a column (or columns).
Column and column groups offer a number of conveniences. Their original intent was to speed up the display of tables in visual user agents. By specifying the width of each column, the user agent does not need to parse the contents of the entire table in order to calculate column and table. Columns and column groups are also useful for applying attributes (such as width or align) to all the cells they include. They may also be used as "hooks" for a limited number of style properties (see note). When used with the scope attribute (discussed in the upcoming accessibility section), they may also provide helpful context for screen readers and other non-visual browsing devices.
The CSS 2.1 Recommendation states that only the following four style properties may be applied to the col and colgroup elements: border, background, width, and visibility. For an in-depth explanation of why this is the case, read Ian Hickson's blog entry, "The mystery of why only four properties apply to table columns" at ln.hixie.ch/?start=1070385285&count=1. See also Chapter 22 of this book for more information on style properties for tables.
col

<col />

Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Table Presentation
Inhaltsvorschau
As for all matters of presentation , style sheets are the preferred method for changing the appearance of tables and offer more fine-tuned control than HTML attributes. See Chapter 22 for more information on CSS specifically for tables.
That said, there are a number of non-deprecated attributes that may be used to control cell spacing , dimensions, borders, and alignment (although, even most of those have style sheet alternatives). This section takes a look at those presentation-related attributes and also points out the preferred CSS methods.
There are two types of space that can be added in and around table cells: cell padding and cell spacing . The cellpadding and cellspacing attributes are used with the table element and apply to the whole table; you can't specify padding or spacing for individual cells using HTML alone.

Section 13.5.1.1: Cell spacing

Cell spacing refers to the amount of space that is held between the cells in a table. It is specified with the cellspacing attribute in the table element. Values are specified in number of pixels. Increasing the cell spacing results in wider shaded borders between cells. In the second image in Figure 13-7, the darker gray areas indicate the 10 pixels of cell spacing added between cells. The default value for cellspacing is 2; therefore, if no cellspacing is specified, browsers will automatically place two pixels of space between cells.
Figure 13-7: Cell spacing versus cell padding

Section 13.5.1.2: Cell padding

Cell padding refers to the amount of space between the cell's border and the contents of the cell (as indicated by the third image in Figure 13-7). It is specified using the
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Accessible Tables
Inhaltsvorschau
Presenting data in rows and columns is a highly effective device in visual media for adding meaning to data. Consider the simple table example in Figure 13-8.
Figure 13-8: A simple table example
Sighted users can easily trace up a column or across a row to a header cell that explains the data's meaning and context. Blind or severely sight-impaired users do not have this luxury. When using a screen reader or Braille device, the contents of each cell may be read one after another (a process called linearization ). The table in Figure 13-8 might be presented like so: "Planet Diameter measured in earths Orbital period in years Moons Mercury .38 .24 0 Venus .95 .62 0 Jupiter 317.8 11.9 63." It's easy to lose track of the meaning of each statistic for a table as simple as this. For complex data tables, such as those pictured in Figure 13-1, it's nearly impossible.
The (X)HTML specification provides several mechanisms for adding meaning to cell data even when the table is presented non-visually. This section outlines the basics of authoring accessible data tables. For more in-depth tutorials, see these online resources:
  • "Techniques for Accessible HTML Tables" (from Papers on Section 508), by Steve Ferg (www.ferg.org/section508/accessible_tables.html)
  • "Bring on the Tables," by Roger Johansson (www.456BereaStreet.com/archive/200410/bring_on_the_tables/)
  • "Creating Accessible Tables," at WebAIM (www.webaim.org/techniques/tables/2)
The first step in making a table accessible is to provide descriptions of the table using the caption element and summary attribute.
The caption element introduced earlier in this chapter provides a short descriptive title for the table. Visual browsers display the contents of the
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Responsible Layout Tables
Inhaltsvorschau
You've surely heard (throughout this book and elsewhere) that table-based layout has been replaced by CSS for positioning elements on the page. However, during this time of transition, as browser developers work out the kinks in CSS support, some authors still choose to use tables to establish the basic grid of the page. It is possible to rely on a table for layout, but be in line with the current trends of standards compliance and accessibility in contemporary web design.
Layout tables are not inherently evil (or even inaccessible), as long as they are handled the right way. This section recommends ways to use layout tables that do the least harm.
When using a table strictly for layout, use only the minimal table elements:
table
Use to establish the table
tr
Use for table rows
td
Use for table cells
Captions, table headers, row groups, and all features for improving table accessibility as listed in the previous section should be avoided. They will only serve to confuse or slow down readers with assistive devices.
The problem with most layout tables in terms of accessibility is complexity. It is not uncommon for tables aiming to achieve pixel-precise layouts to use techniques such as:
  • Tables nested within tables, some many levels deep
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Chapter 14: Frames
Inhaltsvorschau
Frames are a method for dividing the browser window into smaller subwindows, each displaying a different HTML document. This chapter covers the structure and creation of framed documents, controls for affecting their display and function, and some advanced tips and tricks. The following frame-related elements will be addressed.
frame
Defines a single frame
frameset
Establishes the structure for frames or other framesets
noframes
Content displayed if frames are not supported
Frames allow authors to display several HTML documents in the browser window at one time, each in its own scrollable subwindow. Introduced by Netscape Navigator 2.0, frame support was soon added by other popular browsers. The HTML 4.01 and XHTML 1.0 Recommendations include a Frameset DTD for framed documents. XHTML 1.1 omits all frame elements.
Framed documents are typically used as a navigation device in which all of the navigation options stay put in one frame while the linked content documents are displayed in another frame. Because frames may include scrollbars and scroll independently of one another, frames are a method for making sure one page component stays put on the page while the rest of the page is free to scroll.
It is important to note that frame-like functionality (in which one element stays fixed and the rest of the page scrolls) can also be accomplished with CSS using the
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Introduction to Frames
Inhaltsvorschau
Frames allow authors to display several HTML documents in the browser window at one time, each in its own scrollable subwindow. Introduced by Netscape Navigator 2.0, frame support was soon added by other popular browsers. The HTML 4.01 and XHTML 1.0 Recommendations include a Frameset DTD for framed documents. XHTML 1.1 omits all frame elements.
Framed documents are typically used as a navigation device in which all of the navigation options stay put in one frame while the linked content documents are displayed in another frame. Because frames may include scrollbars and scroll independently of one another, frames are a method for making sure one page component stays put on the page while the rest of the page is free to scroll.
It is important to note that frame-like functionality (in which one element stays fixed and the rest of the page scrolls) can also be accomplished with CSS using the position: fixed property. Unfortunately, Internet Explorer 6 for Windows and earlier do not support fixed positioning , but there are workarounds as noted in Chapter 25.
Due to reliable browser support, frames are still an option for navigation and other uses. However, they do present certain problems and peculiarities that have led to their currently controversial status. Like most things, frames are neither all good nor all bad. It is your responsibility to be familiar with both sides of the coin so you can help present the best solution for your or your clients' needs.
Consider these advantages to using frames:
  • They enable parts of the page to remain stationary while other parts scroll. This is useful for elements you may not want to scroll out of view, such as navigational options or banner advertising.
  • Frames unify resources that reside on separate servers. For instance, you may use frames to combine your own material (and navigation graphics) with threaded discussion material generated by software on a vendor's server.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Basic Frameset Structure
Inhaltsvorschau
A web page that is divided into frames is held together by a top-level frameset document.
Frameset documents are fundamentally different from other HTML documents in that they use the frameset element instead of a body element. The frameset element may not contain any content, but instead defines and names some number of frames (or other framesets), arranged in rows and/or columns. Each frame is indicated with a frame element within the frameset. A frameset document contains a regular header portion (as indicated with the head element).

frameset

<frameset>...</frameset>

Attributes
Core (id, class, style, title), onload, onunload
cols=" list of lengths " (number, percentage, or *)
rows=" list of lengths " (number, percentage, or *)
Nonstandard attributes
border=" number "

Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Frame Function and Appearance
Inhaltsvorschau
By default, frames are separated by borders with 3D beveled edges, and each frame has a scrollbar if its contents do not fit in their entirety. You may want to change these settings using the attributes for controlling frame functionality and presentation.
The scrolling attribute within the frame element controls whether scrollbars appear within the frame, regardless of the frame's contents.
The default setting is auto, which behaves like any browser window—no scrollbars display unless the contents are too big to fit entirely within the frame. The yes value should make scrollbars appear, even for mostly empty frames, however, most current browsers seem to treat it the same as auto. To make sure scrollbars never appear, even when the content is larger than the available space, set scrolling="no".
In Figure 14-5 both frames display the same text document, but scrolling is set to auto in the top and no in the bottom frame.
By default, any user can resize your frames—overriding your size settings—simply by clicking and dragging on the border between frames. You can prevent users from doing that by adding the noresize attribute to the frame element.
Figure 14-5: Setting scrollbars with the scrolling attribute
Be careful that you're not disabling functionality the user needs, though; if the frame contains text, chances are good that some users may need to resize.
As you probably already know, browsers hold a margin space on all sides of the browser window, preventing a document's contents from displaying flush against the edge of the window. The width of the margin varies from browser to browser.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Targeting Frames
Inhaltsvorschau
One of the challenges of managing a framed document is coordinating where linked documents display. By default, a linked document loads into the same window as the link; however, it is often desirable to have a link in one frame load a page into a different frame in the frameset. For instance, this is the desired effect for a list of navigation links in a narrow frame that loads content into a larger main frame on the page.
To load a new linked page into a particular frame, you first need to assign a name to the targeted frame using the name attribute in the frame element, as follows:

<frame src="original.html" name="main" />

Names must start with a letter (upper- or lowercase).
Now you can specify that frame by name within any anchor (a) element with the target attribute, as shown in this example:

<a href="new.html" target="main">...</a>

In this example, the document new.html will load into the frame named "main."
If a link contains a target name that does not exist in the frameset, a new browser window is opened to display the document, and that window is given the target's name. Subsequent links targeted to the same name will load in that window.
If you know that you want all the links in a given document to load in the same frame (such as from a table of contents into a main display frame), you can set the target once using the base element instead of setting the target within every link in the document (saving a lot of typing and extra characters in the HTML document).
Placing the base element in the head of the document, with the target frame specified by name, causes all the links in the document to load into that frame. The following is a sample targeted base element:

    <head>

    <base target="main" />

    </head>

Targets set in individual links override the target set in the base element at the document level.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Frame Design Tips and Tricks
Inhaltsvorschau
Perhaps the most common bit of design advice regarding frames is "don't use them." Although frames once had their heyday, they are no longer used in professional, standards-driven web design.
If you do choose to use frames for a project, there are a few pointers and tricks you should be aware of that go beyond a simple familiarity with the elements and attributes.
Designing a web page to be part of a framed document doesn't guarantee that it will always be viewed that way. Keep in mind that some users might end up looking at one of your pages on its own, out of the context of its frameset (this is possible if a search engine returns the URL of the content, for example). Since frames are often used for navigation, this orphaned content page could be a dead end for a user.
For that reason, you should try to design your content pages so that they stand up on their own. Adding a small amount of redundant information to the bottom of each page can make a big difference in usability. First, indicate the name of the site with a link to its home page on each content document. This helps to orient a newcomer who may have just dropped in from a search engine.
It is important to pay particular attention to the navigational options available on content pages viewed without their frameset. At the very least, provide a small link on every page to a more appropriate (and framed) starting point, such as the top level of your site. Be sure to set the target="_top" attribute so the link won't load the home page frameset within the current frameset.
By default, any link within a frame loads the new document into that same frame. To prevent external links from loading into the current frame, be sure to add target="_top" to all your external links; the new site will open in the full browser window. As an alternative, set the target to "_blank" to open the link in a new browser window.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Chapter 15: Forms
Inhaltsvorschau
Forms provide an interface allowing users to interact in some way with your site. In most cases, they are used to gather data, either for later use or to provide a customized response on the fly. Forms have a wide range of uses, from functions as simple as search boxes, mailing list signups, guestbooks, and surveys to as complex as online commerce systems.
Forms collect input via controls, such as buttons, text fields, or scrolling menus. Controls are placed on the page using special elements in the markup. These elements are merely an interface for collecting user information and do not actually process the data. The real work is done by forms-processing applications on the server, such as CGI scripts, ASP, ASP.NET, ColdFusion, PHP, or Java servlets.
The programming necessary for form processing is beyond the scope of this book. This chapter focuses on the frontend aspects of forms: the elements and attributes for building the form interface as well as the elements used to improve accessibility.
form
Establishes the form
input
Creates a variety of controls
button
Generic input button
textarea
Multiline text entry control
select
Multiple-choice menu or scrolling list
option
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
The Basic Form Element
Inhaltsvorschau
The form element is used to designate an area of a web page as a form.

form

    <form> ... </form>

Attributes
Core (id, class, style, title), Internationalization, Events, onsubmit , onreset, onblur
accept=" content-type-list "
accept-charset=" charset list "
action=" URL " (Required)
enctype=" content type "
method="get|post"
name=" text " (Deprecated in XHTML in favor of id attribute)
target=" name "

Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Form Controls
Inhaltsvorschau
A variety of form control elements (also sometimes called "widgets ") are used for gathering information from a form. This section looks at each control and its specific attributes. Every form control (except submit and reset) requires that you give it a name (using the name attribute) so the form-processing application can sort the information. For easier processing of form data on the server, the value of name should not have any character spaces (use underscores or periods instead).
The name attribute works like a variable name. The value provided for name becomes the variable's name. The content entered by the user into the form control is then assigned to the variable. Of all the attributes, the name attribute is key in passing data from the HTML form to any other place in the page, another page, or out through middleware to a database.
The input element is used to create a variety of form input controls , including:
  • Single-line text entry fields
  • Password entry fields
  • Hidden controls
  • Checkboxes
  • Radio buttons
  • Submit and reset buttons
  • File upload mechanisms
  • Custom and image buttons
The type attribute in the input element specifies the control type. The value of the type attribute also determines which other attributes may be used with the element. The input element and all of its accepted attributes appears here. Control-specific attribute listings appear along with the discussion of each control type.

Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Accessibility Features
Inhaltsvorschau
The HTML 4.01 Recommendation added a few form elements and attributes that aid in accessibility . Some provide improved ways to group and label form structure and content. Others provide keyboard alternatives for selecting and activating (such as bringing focus to) form fields.
The added benefit of elements that describe the structure and relationships within form content is that they provide good "hooks" for applying style sheet rules, as addressed briefly at the end of this chapter.
The label element is used to associate some descriptive text with a form field. This provides important context for users accessing the form with a speech-based browser. Each label element is associated with exactly one form control.

label

    <label> ... </label>

Attributes
Core (id, class, style, title), Internationalization,
Events, plus onfocus , onblur
accesskey=" character "
for=" text "

There are two ways to apply a label to a form control. One is to nest the control and its associated description within the

Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
disabled and readonly
Inhaltsvorschau
The disabled and readonly attributes inhibit the user's ability to select or change the form field. When a form element is disabled, it cannot be selected. Visual browsers may render the element as grayed-out. The disabled state can only be changed with a script. This is a useful attribute for restricting access to some form fields based on data entry earlier in the form.
The readonly attribute prevents the user from changing the value of the form field (although, it can still be selected). This enables developers to set values for controls contingent on other data entry using a script.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Affecting Form Appearance
Inhaltsvorschau
The way a form control appears in the browser depends on that browser's rendering engine. In HTML alone, there are no attributes for affecting the presentation of a form control other than specifying character lengths for text fields. We are left with the knowledge that controls will be rendered slightly differently on different browsers and platforms.
Using Cascading Style Sheets to change the presentation and positioning of the form controls , you can take measures to improve the appearance of your forms. Layout tables have also traditionally been used to align form elements, but tables for layout are no longer the preferred option now that CSS is better supported.
As for any HTML element, you can use Cascading Style Sheets to alter the font, colors, and size of form controls. The form element and the form control elements accept the id, class, and style attributes, so you can alter the font, size, color, and so on as you would for any other web page element. The label, fieldset, and legend elements intended for accessibility also make useful "hooks" for styling form content.
Some browsers, particularly old versions, do not support resizing fields or positioning forms with style sheets, so do so with caution and test thoroughly. Cascading Style Sheets are explained in Part III.
This simple example uses an inline style to create a black submit button with white text in the Impact font face (Figure 15-14):

    <input type="submit" value="SUBMIT" style="font-family: Impact, sans-serif;

    color: white; font-size: 14px; background: black" />.

Figure 15-14: A submit button altered with style sheets
In this example, a style sheet is used to highlight the required fields (last name and phone number) using
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Chapter 16: Cascading Style Sheets Fundamentals
Inhaltsvorschau
Cascading Style Sheets (CSS) is a W3C standard for defining the presentation of web documents. Presentation refers to the way a document is displayed or delivered to the user, whether it's on a computer monitor, a cell phone display, or read aloud by a screen reader. This book focuses primarily on the visual aspects of presentation, such as typography, colors, alignment, layout, and so on. CSS is the mechanism for providing these types of style instructions to elements in a document that has been marked up with XHTML, HTML, or any XML language. Most important, CSS keeps these presentation instructions separate from the content and its structural and semantic markup.
Before CSS, web designers were at the mercy of the browser's rendering engine and internal style sheets for the way HTML elements looked in the browser window. Presentational elements and attributes added to HTML, such as the font tag and the bgcolor attribute, granted some additional control over visual display, but the integrity of markup suffered. Cascading Style Sheets (or just "style sheets" in these chapters) hand visual display decisions back to designers and authors. This comes as good news both for designers who want more control over presentation and for those who are eager to see HTML get back to the exclusive business of defining document structure and meaning. Style sheets make both of these goals possible.
The chapters in this section provide a solid overview and reference of CSS and its properties. This book focuses on CSS used with documents written in (X)HTML, although CSS can also be used with any XML language.
This chapter lays an important foundation for understanding how CSS works, including rule syntax and how style sheets are applied to documents. It also covers some critical key concepts at the core of CSS, such as inheritance, handling conflicting styles (the cascade), how elements display, and the box model. Browser issues are briefly addressed as well. The chapter finishes with a section on specifying values in CSS.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
CSS in a Nutshell
Inhaltsvorschau
The chapters in this section provide a solid overview and reference of CSS and its properties. This book focuses on CSS used with documents written in (X)HTML, although CSS can also be used with any XML language.
This chapter lays an important foundation for understanding how CSS works, including rule syntax and how style sheets are applied to documents. It also covers some critical key concepts at the core of CSS, such as inheritance, handling conflicting styles (the cascade), how elements display, and the box model. Browser issues are briefly addressed as well. The chapter finishes with a section on specifying values in CSS.
Chapter 17 explains all the various ways elements can be targeted for style application, and Chapters 18 through 23 cover the CSS visual display properties as they are specified in the CSS 2.1 Recommendation. These chapters document how CSS is designed to work. Browser support varies, of course, so this book provides notes if a property or its values are particularly problematic in a browser.
Finally, Chapters 24 and 25 put everything together in real-world applications. Chapter 24 is a cookbook of some of the most popular CSS techniques, such as CSS rollovers and multicolumn layouts. All of the browser-related problems and solutions are aggregated in Chapter 25, making it a handy reference if you encounter problems down the road.
In the interest of keeping everything "in a nutshell," the chapters in this section stick to visual media properties. The CSS properties related to interface, paged media, and aural (speech) media are included in Appendix B.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
The Benefits of CSS
Inhaltsvorschau
The benefits of using web standards for web page production were covered in detail in Chapter 1, however, it won't hurt to start off with a refresher of the advantages style sheets offer.
Greater typography and page layout controls
With style sheets, you can specify traditional typography features that you could never do with HTML alone (even with its presentational extensions).
Less work
Not only can you format all similar elements in a document with a single style rule, external style sheets make it possible to edit the appearance of an entire site at once with a single style sheet edit.
Potentially smaller documents
Redundant font tags and nested tables make for bloated documents. Stripping presentational HTML out of the document saves on file size.
Potentially more accessible documents
Well-structured and semantically rich documents are accessible to a wider variety of devices and the people who use them. Techniques based on presentational (X)HTML, such as using the font element to format headings and breaking up content into complex nested tables, damage the integrity of the source document.
Presentational HTML is on its way out
The W3C has deprecated all presentational elements and attributes in the HTML and XHTML specifications. One day, browsers will not be required to support them.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
How CSS Works
Inhaltsvorschau
What follows is a simplified explanation of how style sheets work. At its heart, the process actually is this simple.
  1. Start with an XHTML (or HTML) document. Ideally, this document will have been given a logical structure and semantic meaning using the appropriate XHTML elements. The XHTML markup is commonly referred to as the structural layer of the web page. It forms the foundation upon which the presentation layer is applied.
  2. Write style rules for how each element should ideally look. Each rule targets the element by name, and then lists properties—such as font, color, and so on—to be applied to the element. The specifics of writing style rules are covered in the upcoming "Rule Syntax" section.
  3. Attach the styles to the document. The style rules may be gathered up into a separate document and applied to a whole site, or they may appear in the header and apply only to that document. Style instructions may appear within an XHTML element itself as well. Each of these methods for attaching style rules to the content document is discussed in the "Adding Styles to a Document" section in this chapter.
Needless to say, there's a bit more to each step than is described here. The next section begins to get into the nitty gritty of style sheets by looking at the parts of a style rule.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Rule Syntax
Inhaltsvorschau
Style sheets consist of one or more rules for describing how a page element should be displayed. The following example contains two rules. The first rule makes all the h1s in a document gray; the second specifies that paragraphs should be set in 12-pixel high Verdana or some sans-serif font:

    h1 {color: #eee;}

    p {font-size: 12px;

       font-family: Verdana, sans-serif; }

Figure 16-1 shows the components of a style sheet rule.
The two main sections of a style sheet rule are the selector (which identifies the element to be styled) and the declaration (the style or display instructions to be applied to that element). In the previous sample code, the h1 and p elements are the selectors. The complete list of selectors in the CSS 2.1 specification is covered in Chapter 17.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Adding Styles to a Document
Inhaltsvorschau
Style rules can be applied to documents in three ways: as inline style directions, as style elements embedded at the top of the document itself, and as external files that can be either linked to or imported into the document.
When attaching styles to a document, it is important to keep in mind that other style sheets may apply to your document as well. User agents, such as browsers, have built-in style sheets for rendering content. In addition, individual users may create their own style sheets and apply them to a single site or to all the sites they visit in order to make the text comfortable to read or to meet special needs. Which style sheet takes precedence is covered in the upcoming "Document Structure and Inheritance" section.
You can add style information to an individual element by using the style attribute within the HTML tag for that element. The value of the style attribute is one or more standard style declarations, as shown here:

    <h1 style="color: red">This Heading will be Red</h1>



    <p style="font-size: 12px; font-family: 'Trebuchet MS', sans-serif">

    This is the content of the paragraph to be set with the

    described styles.</p>

Note that if the style attribute uses double quotation marks as shown, quoted values within the list (such as the font name "Trebuchet MS" in the example) must use single quotation marks. The reverse is also valid: if the document uses single quotes for attributes, then contained quoted values require double quotes.
Although a perfectly valid use of style information, inline styles are equivalent to the font extension to HTML in that they pollute the document with presentation information. With inline styles, presentation information is still tied to individual content elements, so any changes must be made in each individual tag in every file. Inline styles are best used only occasionally to override higher-level rules. In fact, the
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Key Concepts
Inhaltsvorschau
To become comfortable with the way CSS behaves, it is important to have an understanding of its guiding concepts . This section provides a basic introduction to these fundamental ideas:
  • Document structure and inheritance
  • Conflicting style rules: the "cascade"
  • Element types
  • The box model
XML, XHTML, and HTML documents have an implicit structure or hierarchy. For instance, the html root element usually contains a head and a body, and the body, in turn, contains some number of block-level elements, such as paragraphs (p). A paragraph may include inline elements such as anchors (a) or emphasized text (em). This hierarchy can be visualized as a tree, branching out from the root. Figure 16-2 shows the document tree structure of a very simple XHTML document.
Figure 16-2: Document tree structure

Section 16.6.1.1: The parent-child relationship

The document tree becomes a family tree when it comes to referring to the relationship between elements. An element that is directly contained by another element is said to be the child of that element. In Figure 16-2, the p element is the child of body, and body is said to be its parent. Elements that have the same parent are called siblings . In the example, the li element is the child of ol, its parent, and the other li elements are its siblings. This parent-child relationship is fundamental to how CSS works.
Notice in the example that the p element contains an a element, which in turn contains the inline element
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Specifying Values
Inhaltsvorschau
It is important to use the proper syntax for specifying length and color values in style sheet rules.
CSS allows measurements to be specified in a variety of units. Some of the units (such as em and pica) are taken from the traditional print publishing world. When specifying lengths, keep the following in mind:
  • Do not add space between the number and the two-letter unit abbreviation. It must be 24px, not 24 px.
  • The only value that does not require a unit abbreviation is 0 (zero).
  • Measurements may contain decimal fractions, such as 14.5cm.
  • Some properties, such as margins, accept negative values: margin: -500px
Table 16-1 lists units of measurements that you can specify in style sheet values.
Table 16-1: Units of measurements for style sheet values
Code
Unit
Description
px
Pixel
Pixel units are relative to the monitor resolution.
pt
Point
A traditional publishing unit of measurement for type. In CSS, a point is equal to 1/72 of an inch.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Browser Support
Inhaltsvorschau
For years, web designers and developers grappled with inconsistencies in the ways browsers supported HTML, but eventually, reliable support for nearly the entire HTML 4.01 Recommendation arrived. Now, the browser developers are working on getting up to speed with CSS, so support of some features (particularly in the newer CSS 2.1 Recommendation) are buggy and inconsistent across browsers.
Chapter 25 specifically addresses the most notorious browser bugs and how to deal with them, but you'll also find browser alert notes when appropriate for each property in Chapters 18 through 23.
No browser support chart is provided with this book, because it would no doubt be obsolete before this book is retired. However, there are several excellent online resources that publish CSS browser support information.
West Civ Browser Support Page (www.westciv.com/style_master/academy/browser_support/index.html)
West Civ provides free support charts online for properties tested on IE, Netscape, and Opera. A complete, more detailed report is available for a nominal fee.
Index DOT Css, by Brian Wilson (www.blooberry.com/indexdot/css/index.html)
This is a remarkably thorough site (albeit somewhat out of date) that documents browser support for every CSS selector, property, and value for Internet Explorer, Netscape/Mozilla, and Opera browsers. It also provides notes on particular bugs and behaviors.
Internet Explorer Blog (blogs.msdn.com/ie/)
Here you can keep up with what the developers are up to at Microsoft.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
For Further Reading
Inhaltsvorschau
CSS is a rich topic. Not surprisingly, there are mountains of information about it in print and on the Web. These are just a few resources that I found invaluable in writing the CSS chapters of this book.
There are many good books on CSS on the shelves these days. These are the ones that helped me out the most and that I recommend wholeheartedly.
  • Cascading Style Sheets: The Definitive Guide, Second Edition, by Eric Meyer (O'Reilly)
  • Web Standards Solutions: The Markup and Style Handbook, by Dan Cederholm (Friends of Ed)
  • The Zen of CSS Design: Visual Enlightenment for the Web, by Dave Shea and Molly E. Holzschlag (New Riders)
  • Eric Meyer on CSS: Mastering the Language of Web Design, by Eric A. Meyer (New Riders)
These sites are good starting points for online exploration of style sheets.
W3C (www.w3c.com/Style/CSS)
The World Wide Web Consortium is where the standards, including CSS, are developed and overseen. Go right to the source for the nitty-gritty details and latest developments.
A List Apart (www.alistapart.com)
This online magazine features some of the best thinking and writing on cutting-edge, standards-based web design. It was founded in 1998 by Jeffrey Zeldman and Brian Platz.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Chapter 17: Selectors
Inhaltsvorschau
The selector is the part of the style rule that identifies the element (or elements) to which the presentation instructions are applied. For instance, if you want all of the h1s in a document to be green, write a single style rule with h1 as the selector. But that's just the beginning. CSS provides a variety of selector types to improve flexibility and efficiency in style sheet authoring. This chapter introduces the selectors included in the CSS 2.1 specification, including:
  • Type (element) selectors
  • Contextual selectors (descendant, child, and adjacent sibling)
  • Class and ID selectors
  • Attribute selectors
  • Pseudoclasses
  • Pseudoelements
Not all of these forward-thinking selectors are supported by today's browsers, so if a particular selector is not quite ready for prime time, it will be noted.
The W3C Selectors specification introduces additional selectors above and beyond those in CSS 2.1, which modern browsers are still in the process of implementing. This book does not describe them. For more information on those new selectors in particular, see the W3C Selectors specification (www.w3.org/TR/css3-selectors).
The most straightforward selector is the type selector that targets an element by name, as shown in these examples:

    h1 {color: blue;}

    h2 {color: blue;}

    p {color: blue;}

Type selectors can be grouped into comma-separated lists so a single property will apply to all of them. The following code has the same effect as the previous code:

    h1, h2, p {color: blue;}

CSS 2 introduced a universal element selector (*) that matches any element (like a wildcard). The style rule * {color: gray} makes every element in a document gray. The universal selector may be a useful tool when used in relation to other elements, as discussed in the next section.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Type (Element) Selector
Inhaltsvorschau
The most straightforward selector is the type selector that targets an element by name, as shown in these examples:

    h1 {color: blue;}

    h2 {color: blue;}

    p {color: blue;}

Type selectors can be grouped into comma-separated lists so a single property will apply to all of them. The following code has the same effect as the previous code:

    h1, h2, p {color: blue;}

CSS 2 introduced a universal element selector (*) that matches any element (like a wildcard). The style rule * {color: gray} makes every element in a document gray. The universal selector may be a useful tool when used in relation to other elements, as discussed in the next section.
The universal selector causes problems with form controls in some browsers. If your page contains form inputs, the safest bet is to avoid the universal selector.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Contextual Selectors
Inhaltsvorschau
Type selectors, such as those in the previous example, apply to all instances of that element found in a document. By contrast, contextual selectors allow you to apply style properties to select elements, based on their context or relation to another element. There are several types of contextual selectors: descendant, child, and adjacent sibling. This is where being familiar with the document tree structure of your document comes in handy.
Contextual selectors use a specific character to signify the type of relationship between the elements in the selectors. This character is known as the combinator.
Descendant selectors target elements that are contained within (therefore descendants of) another element. They are indicated in a list separated by a character space (the combinator for descendant selectors ), starting with the higher-level element. For example, the following rule specifies that em elements should be olive, but only when they are descendants of a list item (li). All other em elements are unaffected by this rule.

    li em {color: olive;}

Like simple type selectors , contextual selectors can be grouped together in comma-separated lists. The following code makes emphasized (em) text red only when it appears in the context of a first-, second-, or third-level heading:

    h1 em, h2 em, h3 em {color: red;}

Descendant selectors may also be nested several layers deep, as shown in this example that targets only emphasized text (em) within anchors (a) within ordered lists (ol).

    ol a em {font-weight: bold;}

A child selector is similar to the descendant selector, but it targets only direct children of a given element. In other words, the element must be contained directly within the higher-level element with no other element levels in between. Child selectors are separated by the greater-than symbol (
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Class and ID Selectors
Inhaltsvorschau
So far, all of the selectors we've seen have been tied to specific elements. Class selectors and ID selectors give you the opportunity to target elements that you've named yourself, independent of the document element.
Elements are named using the class and id attributes. They can be applied to all XHTML elements except base, head, html, meta, script, style, and title. In addition, class may not be used in basefont and param. Class and ID selectors work in slightly different ways.
Use the class attribute to identify a number of elements as being part of a conceptual group. Elements in a class can then be modified with a single style rule. For instance, you can identify all the items in a document that you classify as "special":

    <h1 class="special">Attention!</h1>

    <p class="special">You look marvelous today.</p>

To specify the styles for elements of a particular class, add the class name to the type selector, separated by a period (.).

    h1.special {color: red;}

    p.special {color: red;}

To apply a property to all the elements of the same class, omit the tag name in the selector (be sure to leave the period—it is the character that indicates a class):

    .special {color: red;}

Note that class names cannot contain spaces; use hyphens or underscores instead if necessary (although underscores are discouraged due to lack of support in some browsers).
When choosing a name for a class, be sure that it is meaningful. For example, naming a class redtext merely reintroduces presentational information to the document and does nothing to describe the type of information in the element. It may also be confusing if in a future redesign, the color of those elements changes to blue.
Authors should resist going overboard with class creation (a syndrome commonly referred to as "class-itis"). In many cases, other types of selectors with higher specificity, such as contextual or attribute selectors, may be used instead.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Attribute Selectors
Inhaltsvorschau
CSS 2 introduced a system for targeting specific attribute names or values. This may be useful for XML languages other than XHTML that may not contain class and id attributes . There are plenty of uses for attribute selectors within XHTML as well, but unfortunately, attribute selectors are not widely supported at this time.
Browser alert: Attribute selectors are not supported by Internet Explorer Versions 6 and earlier. As of this writing, support is rumored in IE 7, but it has not been documented. Gecko-based browsers (Mozilla and Netscape 6+), Safari, and Opera 7 do support them, but represent a smaller portion of browser usage.
There are four variations on attribute selectors:
Simple attribute selection
The broadest attribute selector targets elements with a particular attribute regardless of its value. The syntax is as follows:

    element[attribute]

Example: img[title] {border: 3px red;}
Specifies that all images in the document that include a title attribute get a red border.
Exact attribute value
This selects elements based on an attribute with an exact attribute value.

    element[attribute="exactvalue"]

Example: img[title="first grade"] {border: 3px red;}
Only images with the title value first grade are selected. The value must be an exact character string match.
Partial attribute value
For attributes that accept space-separated lists of values, this attribute selector allows you to look for just one of those values (rather than the whole string). The tilde (
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Pseudoselectors
Inhaltsvorschau
Style rules are normally attached to elements in the document tree structure, such as those we've discussed in the chapter so far. But some elements are not necessarily found in the document markup, such as which links have been visited or the first line of a paragraph. To apply style to these instances in a document, CSS provides several pseudoselectors . Instead of targeting a particular element in the document, pseudoselectors are interpreted by the browser based on context and function. Pseudoselectors are indicated by the colon (:) character. Pseudoselectors are divided into pseudoclasses and pseudoelements.
As the name implies, pseudoclasses work as though there is a class applied to a group of elements, most often the anchor (a) element. These "phantom" classes (to use Eric Meyer's term) do not appear in the markup, but rather are based on the state of those elements or the document itself.

Section 17.5.1.1: Anchor pseudoclasses

There are several pseudoclasses that can be used to apply styles to various states of a link:

    a:link {color: red;}

    a:visited {color: blue;}

    a:hover {color: fuchsia;}

    a:active {color: maroon;}

Similar to their body attribute counterparts in the body element, :link applies to hypertext links that have not been visited, :visited applies to links to pages that have been visited, and :active applies during the act of clicking. The difference is that you can do much more than just change color with CSS. Following are popular rules for turning off the underline under linked text.

    a:link {color: red; text-decoration: none;}

    a:visited {color: blue; text-decoration: none;}

The :hover selector is used to create rollover effects in which the link changes in appearance when the mouse pointer moves over it. The examples above turned off underlines for links. The following rule uses
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Chapter 18: Font and Text Properties
Inhaltsvorschau
Cascading Style Sheets offer a degree of control over text formatting that approaches desktop publishing. This certainly comes as a relief after years of misusing HTML markup for presentation purposes. Controls for specifying fonts and text formatting are undeniably the most popular use of style sheets and they are the properties that browsers support the most reliably.
This chapter discusses the challenges of typography on the Web and introduces the following text-related CSS 2 properties:
font-family
text-decoration
letter-spacing
font-size
text-transform
word-spacing
font-weight
line-height
white-space
font-style
text-indent
direction
font-variant
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Typography on the Web
Inhaltsvorschau
For those accustomed to print, the Web offers some unique challenges, usually requiring the relinquishing of control. Typography is a prime example. In print, designers may choose a typeface and point size for headlines and body copy, and as long as the proper font is provided when the printed piece is output, everything looks just the way the designer intended. On the Web, it's not so easy.
Specifying fonts for use on web pages is made difficult by the fact that browsers are limited to displaying fonts that are already installed on the user's local hard drive. So, even though you've specified text to be displayed in the Frutiger font, if users do not have Frutiger installed on their machines, they will see the text in whatever their default browser font happens to be. Fortunately, CSS allows you to specify a list of alternative fonts if your first choice is not found (as discussed in the section "Font Family").
This problem is compounded by the fact that fonts are named inconsistently across platforms and based on the foundry they come from. So even though you want text to show up in plain Times, the font name for that typeface may be Times New Roman or TimesNR or Times Roman. Browsers don't know the difference. This makes it difficult to find a font face even if it (or something like it) is in fact there.
The other web typography challenge is type size. Size is problematic due to varying screen resolutions and different default font sizes built into browsers and operating systems. What looks perfectly fine on your monitor may be too small to read for someone else. On top of that, to keep content accessible, text should be sized in a way that allows the end user to resize it (usually larger) to meet special needs. The specific problems of setting text size along with recommendations will be covered in the upcoming "Font Size" section, but for now, suffice it to say that it is not as straightforward as print. It requires knowledge of the medium and occasionally some tough decisions.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Font Family
Inhaltsvorschau
The CSS specification provides the font-family property for specifying the font face for text elements.
font-family
Values:

    [[<family-name> | <generic-family> ] [,<family-name> |

    <generic-family> ]*] | inherit

Initial value:
Depends on user agent (the default font in the browsing device)
Applies to:
All elements
Inherited:
Yes
Use the font-family property to specify any font (or list of fonts, separated by commas), as shown in these examples:

    h1 {font-family: Arial; }

    tt {font-family: Courier, monospace; }

    p {font-family: "Trebuchet MS", Verdana, sans-serif; }

The value of the property is one or more font names, separated by commas. This allows authors to provide a list of fonts, starting with a first choice, followed by a list of alternates. The user agent (typically a browser) looks for the first font on the user's machine and, if it is not found, it continues looking for the next font in the list until a match is made.
Note that in the third example, the "Trebuchet MS" is enclosed in quotation marks. Font names that contain character spaces must be enclosed in quotation marks (single or double). If the font name appears in an inline style, be sure to use single quotes if the style attribute uses double (or vice versa).
You should include a generic font family as the last option in your list so that if the specified fonts are not found, a font that matches their general style will be substituted. Generic family names must never be enclosed in quotation marks.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Font Size
Inhaltsvorschau
CSS provides the font-size property for specifying the size of text. There are many value options for specifying font size , each with its own pros and cons. This section discusses the various keyword and unit options and their impact on usability.
font-size
Values:

    xx-small | x-small | small | medium | large | x-large |

    xx-large | smaller | larger | <length> | <percentage> | inherit

Initial value:

    medium

Applies to:
All elements
Inherited:
Yes
These examples demonstrate the font-size property used with several different value types.

    p.copyright {font-size: x-small;}

    strong {font-size: larger;}

    h2 {font-size: 1.2em;}

    p#intro {font-size: 120%;}

Before diving into the details of specifying type size, it is worth pausing to clarify the difference between absolute and relative sizes. Absolute sizes have predefined meanings or an understood real-world equivalent. In CSS, absolute values may be expressed as keywords, such as small or x-large (discussed next) or by using absolute length values, such as cm (centimeter), in (inch), or pt (point, 1/72 of an inch).
Relative sizes, on the other hand, are based on the size of something else, like the parent element or the em measurement of the text (see the sidebar "A Word About Ems"). Relative values, such as em and percentages, are generally preferred for web text for reasons that are covered in the upcoming sections.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Other Font Settings
Inhaltsvorschau
Compared to the hassles of font-face and font-size, the other font-related properties are a walk in the park (albeit, a short walk). This section introduces style properties for adjusting font weight, style, and "small caps" display.
The font-weight property specifies the weight, or boldness, of the type.

font-weight
Values:

    normal | bold | bolder | lighter | 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900

| inherit

Initial value:

    normal

Applies to:
All elements
Inherited:
Yes

Font weight can be specified either as a descriptive term (normal, bold, bolder, lighter) or as one of the nine numeric values listed above. The default font weight is normal, which corresponds to 400 on the numeric scale. Typical bold text corresponds to 700 on the numeric scale. There may not be a font face within a family that corresponds to each of the nine levels of boldness (some may come in only normal and bold weights). Figure 18-6 shows the effect of each of the values on the popular Verdana web font face in the Firefox browser (note that bold kicks in at 600, not 700).
It is evident that the numeric font-weight values are not useful when multiple weights are not available for the font. There's no harm in using them, but don't expect them to change the weights of an existing font. It merely looks for font weights that are already available.

Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Text Transformation (Capitalization)
Inhaltsvorschau
The font-variant property uses capital letter shapes for lowercase letters, but doesn't really affect the capitalization of the text, only the character shapes of the font. There is another CSS property, text-transform, for altering the capitalization of text without needing to retype it in the source document. It works by toggling between the upper- and lowercase characters as specified.
text-transform
Values:

    none | capitalize | lowercase | uppercase | inherit

Initial value:

    none

Applies to:
All elements
Inherited:
Yes
Use the text-transform property to change the capitalization of an element without retyping it in the source. This can make changing capitalization of a particular element (like headers) for an entire site as easy as changing one style sheet rule.
The default value is none, which leaves the text as it appears in the source (and resets any inherited value). The capitalize value displays the first letter in each word of the element in uppercase. The lowercase value makes all letters in the element lowercase, and likewise, the uppercase value makes all characters uppercase. The effects of these text-transform property examples are shown in Figure 18-9.
Figure 18-9: The text-transform property
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Text Decoration
Inhaltsvorschau
Use the text-decoration element to specify underlines , overlines (a line over the text), strike-throughs , and the blinking effect .
text-decoration
Values:

    none | underline | overline | line-through | blink

Initial value:

    none

Applies to:
All elements
Inherited:
No, but a text decoration is "drawn through" any child elements (see explanation in this section).
The values for text-decoration are fairly intuitive: underline causes an element to be underlined, overline draws a line over the element, and line-through draws a line through the middle of the element and replaces the deprecated strike and s elements in HTML. text-decoration variations are shown in Figure 18-10.
Figure 18-10: The text-decoration property
There is also an optional blink value that causes the text to flash on and off like the dreaded Netscape blink element (the blink value is deliberately still not supported by Internet Explorer).
The text-decoration property has one strange behavior you should be aware of. Although text-decoration values applied to a block element are not inherited by the block's child elements, the line gets drawn through the child elements anyway. The line (such as an underline, overline, or line-through) will go through the inline elements even if they explicitly have
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Line Height
Inhaltsvorschau
In CSS, the line-height property defines the minimum distance between the baselines of adjacent lines of text. A baseline is the imaginary line upon which the bottoms of characters sit. Line height is analogous to leading or interlinear space (the amount of space between lines) in traditional typesetting. Adjusting the line height can change the color of a block of text. In this case "color" refers not to hue (like blue or green), but rather the overall density or darkness of the text.
This section looks at both the line-height property and the method by which CSS calculates the actual height of lines. CSS line height handling has an impact on vertical alignment within text, discussed later.
line-height
Values:

    normal | <number> | <length> | <percentage> | inherit

Initial value:

    normal

Applies to:
All elements
Inherited:
Yes
These examples demonstrate three alternative methods for specifying the same amount of line spacing. If the font size is 10 pixels, the resulting line height for each of the examples listed would be 20 pixels. Figure 18-11 shows the results (bottom) compared to a paragraph with the default line height (top).

    p.open {line-height: 2; }     /* uses a scaling factor */

    p.open {line-height: 2em; }   /* unit of length */

    p.open {line-height: 200%; }  /* percentage */

The default value is normal
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Text Alignment Properties
Inhaltsvorschau
One of the ways text can be formatted to improve visual hierarchy and readability is through alignment. CSS provides several properties for adjusting the horizontal and vertical alignment of text.
Use the text-indent property to specify an amount of indentation for the first line of text in an element.

text-indent
Values:

    <length> | <percentage> | inherit

Initial value:

    0

Applies to:
Block-level elements and table cells
Inherited:
Yes

The value of text-indent may be any unit of length or a percentage value (calculated as a percentage of the parent element width), as shown in these examples and Figure 18-13:

    p#1 { text-indent: 3em; }

    p#2 { text-indent: 50%; }

    p#3 { text-indent: -20px; }

The third rule in this list shows an allowable negative text-indent value. Negative values can be used to create hanging-indent effects. This feature should be used with care, as it may cause text to disappear off the left edge of the browser (add left padding to compensate) or may not be supported properly in older browser versions.
One last thing to know about indents is that a child element inherits the computed indent value from its parent, not the specified value. So if a div is set to 800 pixels wide with a 10% margin, the computed indent will be 80 pixels. A paragraph within the

Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Text Spacing
Inhaltsvorschau
CSS provides several tools for adjusting the space between words or characters in text. Adding space within a line is another way to affect the character or color of a block of text. For example, adding a little extra space between letters is a common technique for calling more attention to a headline or the first line of text on a page. This section introduces the letter-spacing, word-spacing, and white-space properties.
Use the letter-spacing property to specify an amount of space to be added between characters.

letter-spacing
Values:

    normal | <length> | inherit

Initial value:

    normal

Applies to:
All elements
Inherited:
Yes

Figure 18-19 shows an example of a style sheet rule that adds 3 pixels of extra space between the characters in the first line of text.

    p {letter-spacing: 8px; }



    <p>Nunc a nisl.</p>

Figure 18-19: Letter spacing
The default value normal is equivalent to a numeric setting of zero (0). In other words, whatever value you specify is added to the standard character-spacing text. Negative values are permitted and will cause the characters to overlap.
Note that when specifying relative lengths (such as em, which is based on font size), the

Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Text Direction
Inhaltsvorschau
To accommodate languages that read right to left, such as Hebrew and Arabic, the CSS Recommendation provides two properties that affect the direction of the flow of text.
direction
Values:

    ltr | rtl | inherit

Initial value:

    ltr

Applies to:
All elements
Inherited:
Yes
The direction property affects the direction of text in a block-level element. It also changes the order of column layout, the behavior of text overflow, and margin alignment for justified text. The default is ltr (left to right) unless the browser has an internal style sheet for displaying text from right to left.
unicode-bidi
Values:

    normal | embed | bidi-override | inherit

Initial value:

    normal

Applies to:
All elements
Inherited:
No
The unicode-bidi property is provided to take advantage of the directionality features in Unicode. Unicode and directionality are discussed in Chapter 6. Setting directionality falls outside the realm of the average web designer, but it is a useful feature for multilingual sites. For details on how these properties work, see the CSS 2.1 specification online at
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Chapter 19: Basic Box Properties
Inhaltsvorschau
The box model was briefly introduced in Chapter 16 as one of the fundamental concepts of CSS visual formatting. According to the box model, every element in a document generates a box to which such properties as width, height, margins, padding, and borders may be applied.
These element box properties (as well as those for positioning as discussed in Chapter 21), are at the heart of CSS-driven layout and design. Effects that once required tables, such as putting text in a colored box, can now be handled entirely with style sheets. This is just one way that style sheets have liberated developers from the inappropriate use of (X)HTML elements for visual effects. And that's just scratching the surface. Many visual effects created with CSS box properties simply weren't possible before using (X)HTML alone.
The box model is also at the core of some of the most notorious headaches for web developers, namely, the fact that all versions of Internet Explorer for Windows (except IE 6 and 7 running in Standards mode, as described in Chapter 9) interpret the width of the box differently than all other CSS-compliant browsers. This has made it necessary for web developers to jump through all sorts of hoops to replicate layouts consistently on all browsers. For more on the IE/Windows box model problem, see Chapter 25.
This chapter covers the box model in more depth and introduces the basic box properties for specifying size and adding margins, borders, and padding, as listed next.
height
border-top-style
border-top
width
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
The Box Model, Revisited
Inhaltsvorschau
According to CSS, every element in a document, both block-level and inline-level, generates a rectangular box called an element box. Figure 19-1 shows all the areas and boundaries defined by the CSS box model.
At the core of the element box is the content itself, called the content area. Its sides are referred to as the inner edges of the element box. The width and height of an element are calculated as the distance between these inner edges.
The padding is the area held between the content area and an optional border. The border is one or more lines that surrounds the element and its padding.
Background colors and images applied to an element are visible in the padding and extend behind the border (if there are gaps in the border style, the background color will show through).
Finally, on the outside of the element border, there is an optional amount of margin. The margin area is always transparent, which means that the background of the parent element shows through.
The outside edges of the margin area make up the outer edges of the element box. The total width that an element box occupies on the page is measured from outer edge to outer edge and includes the width of the content area plus the total amount of padding, border, and margins .
Keep in mind that when you specify the width value for an element, that sets the width of the content area only, so there's some extra math to do before you know the total width of the element. This calculation may be critical for positioning elements precisely on a page.
Here is where the IE/Windows box model problem comes into play. With the exception of IE 6 and 7 in Standards mode, Internet Explorer for Windows
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Width and Height
Inhaltsvorschau
Use the width and height properties to specify the dimensions of a block-level element or an inline replaced element (like an image). The width and height properties do not apply to inline text (non-replaced) elements and will be ignored by standards-conformant browsers. In other words, you cannot specify the width and height of an anchor (a) or a strong element unless you change its display role to a block-level display value like block, list-item, or inline-block.
height
Values:

    <length> | <percentage> | auto | inherit

Initial value:

    auto

Applies to:
Block-level elements and replaced elements (such as images)
Inherited:
No
width
Values:

    <length> | <percentage> | auto | inherit

Initial value:

    auto

Applies to:
Block-level elements and replaced elements (such as images)
Inherited:
No
Using the height and width properties is straightforward, as shown in these examples and Figure 19-3.

    div#tall {
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Margins
Inhaltsvorschau
Margins are an amount of space that may be added around the outside of the element's border. There are properties for specifying a margin amount for one side at a time or by using the shorthand margin property.
margin-top, margin-right, margin-bottom, margin-left
Values:

    <length> | <percentage> | auto | inherit

Initial value:

    0

Applies to:
All elements (except elements with table display types other than table and inline-table)
Inherited:
No
margin
Values:

    [<length> | <percentage> | auto]{1,4} | inherit

Initial value:
See individual properties
Applies to:
All elements (except elements with table display types other than table and inline-table)
Inherited:
No
With the margin-top, margin-right, margin-bottom, and margin-left properties, you can specify a margin for one side of an element. Margin size may be specified in any of the accepted units of length. Negative values are permitted. Figure 19-4 shows examples of adding margins to individual sides of an element. Note that the dotted lines are a device to point out the outer edge of the margin and would not display in the browser.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Borders
Inhaltsvorschau
A border is simply a line drawn around the content area of an element and its (optional) padding. The three aspects of a border that can be specified are its style, width (thickness), and color. As for margin, each of these qualities may be specified for an individual side at a time or for several sides at once using shorthand properties.
There are only a few things to know about border style behavior:
  • Borders are drawn on top of an element's background, so the background color or image will show through the gaps in the intermittent border styles.
  • Borders applied to non-replaced inline elements (text elements) have no effect on the line height for that line. In other words, they are not included in the inline box for the element.
  • Borders applied to replaced elements, however, do affect line height, just as margins do.
The border style is the most important of the border qualities because, according to the CSS specification, if there is no border style specified, the border does not exist. In other words, you must always declare the style or other border settings will be ignored.
Figure 19-7 shows the nine border styles you have to choose from.
Figure 19-7: The nine available border styles
There is a bug in Internet Explorer 6 for Windows that causes borders specified as dotted to render as dashed.
Border styles can be applied one side at a time or by using the
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Padding
Inhaltsvorschau
The padding area is an optional amount of space held between the content area of an element and its border. If you are putting a border on an element, it is usually a good idea to add a bit of padding as well to keep the border from bumping against the content.
Now that you've seen margins and borders at work, the padding properties should look familiar. There are side-specific properties for setting an amount of padding on each side by name, and a shorthand padding property that applies padding to combinations of four sides.
padding-top, padding-right, padding-bottom, padding-left
Values:

    <length> | <percentage> | inherit

Initial value:

    0

Applies to:
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Chapter 20: Color and Backgrounds
Inhaltsvorschau
Once upon a time in 1993, when Mosaic was the only widely distributed browser in town, all web pages had black text on a gray background with blue hyperlinks and purple visited hyperlinks (unless the user changed it in the browser preferences to something more jazzy—say, lime green on purple). Then in 1994, along came Netscape, and HTML extensions for coloring text and backgrounds were born. Even those limited controls came as a welcome relief to web designers and users clamoring for color.
CSS offers control over color and backgrounds that is worlds away from the effects possible with HTML extensions alone. This chapter introduces the properties for adding color and backgrounds to elements listed here.
color
background-position
background-color
background-attachment
background-image
background
background-repeat
Say goodbye to <font color=> forever. You can pitch the text, link, vlink, and alink attributes for the body element while you're at it.
The color property is used to describe the text (a.k.a. "foreground") color of an element. The foreground color is also used for an element's border unless it is specifically overridden with a border color rule.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Foreground Color
Inhaltsvorschau
Say goodbye to <font color=> forever. You can pitch the text, link, vlink, and alink attributes for the body element while you're at it.
The color property is used to describe the text (a.k.a. "foreground") color of an element. The foreground color is also used for an element's border unless it is specifically overridden with a border color rule.
color
Values:

    <color> | inherit

Initial value:
Depends on user agent
Applies to:
All elements
Inherited:
Yes
The value of the color property is any of the valid color types and system colors. Here's a refresher.
RGB colors can be specified in any of the following formats:

    {color: #0000FF;}

    {color: #00F;}

    {color: rgb(0,0,255);}

    {color: rgb(0%, 0%, 100%);}

The first example uses three two-digit hexadecimal RGB values (for a complete explanation, see Appendix D). The second example uses a shorthand three-digit syntax, which is converted to the six-digit form by replicating each digit (therefore, 00F is the same as 0000FF).
The last two formats use a functional notation specifying RGB values as a comma-separated list of regular values (from 0 to 255) or percentage values (from 0 to 100%). Note that percentage values can use decimals, e.g., rgb(0%, 50.5%, 33.3%).
CSS 1 and 2 also recognize 16 valid color names: aqua, black, blue, fuchsia, gray, green, lime, maroon, navy, olive, purple, red, silver, teal, white, and yellow
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Background Color
Inhaltsvorschau
It's been common practice to add a background color to a page using the bgcolor attribute in the body element in HTML. With CSS, not only can you provide a background color for a whole page, but for any element in the document, both block-level and inline. Boxes of color anywhere you want them . . . and no tables required!
Background color is declared with the (no surprise here) background-color attribute.
background-color
Values:

    <color> | transparent | inherit

Initial Value:

    transparent

Applies to:
All elements
Inherited:
No
Background properties are applied to the "canvas" behind an element. With regard to the box model, background colors fill the content area, the padding area, and extend behind the border to its outer edge. This means that if the border has gaps, the background color will show through.
Background properties are not inherited, but because the default value is transparent, the parent's background color shows through its child elements. Figure 20-2 shows an example of the background-color property. Note how a little padding added to the element gives the content a little breathing room inside the resulting rectangular colored box.

    p {padding: 5px;}

    p.a {background-color: #333333;}

    p.b {background-color: #666666;}

    p.c {background-color: #CCCCCC;}



    <p class="a">Fusce rhoncus facilisis sapien.</p>

    <p class="b">Fusce rhoncus facilisis sapien.</p>

    <p class="c">Fusce rhoncus facilisis sapien.</p>

Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Background Images
Inhaltsvorschau
Once again, CSS beats HTML hands down in the background department (but then, HTML was never intended to be fussing around with things like background images). With CSS, you're not stuck with a repeating tile pattern, and you can position a background image wherever you like. You can also apply a background image to any element in the document.
This section covers the CSS properties for adding and manipulating background images, with the basic background-image property as a starting point and moving on to more advanced background image behaviors such as controlling repeating patterns, positioning the image within the element, and preventing the image from scrolling off the page.
background-image
Values:

    <uri> | none | inherit

Initial value:

    none

Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Chapter 21: Floating and Positioning
Inhaltsvorschau
CSS isn't limited to just "prettying up" elements in the flow of the document. You can also use it to achieve basic page layout such as multiple columns, text wrap, and even positioning with pixel precision. This chapter introduces floating and positioning, the CSS methods for arranging elements on the page.
It should be noted that this chapter covers the CSS 2.1 specification for layout-related properties as they are intended to work. There are some notorious browser bugs that make implementing the tools illustrated here challenging. Browser issues will be noted here, but the details about specific browser problems and how to compensate for them are discussed further in Chapter 25.
This chapter covers these CSS 2.1 properties for controlling the positioning of elements.
float
bottom
overflow
clear
top
clip
position
left
visibility
bottom
right
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Normal Flow
Inhaltsvorschau
Before jumping into methods for positioning elements, it is useful to have an understanding of what is meant by the "normal flow " of a document according to the CSS layout model. In the normal flow, text elements are laid out from top to bottom, and from left to right in left-to-right reading languages (or from right to left in right-to-left reading languages). This is the default behavior of the web browser.
In the normal flow, block-level elements stack on top of one another and inline elements fill the available space. When the browsing window is resized, the block elements expand or contract to the new width, and the inline content reflows to fit. Objects in the normal flow influence the position of the surrounding content (sibling elements).
In CSS positioning, blocks are defined as being either in the normal flow or removed from the normal flow. Floating and positioning elements changes their relationship to the normal flow, as discussed in the following sections.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Floating
Inhaltsvorschau
If you've ever aligned an image to the right or left margin and allowed text to wrap around it, then you understand the concept behind floats in CSS. In fact, that is precisely the functionality that the float property was created to provide. The primary difference is that you can float any element with CSS (paragraphs, lists, divs, and so on), not just images. It is important to note that floating is not a positioning scheme; it is a unique feature with some interesting behaviors to be aware of, as discussed later in this section.
Floats are useful for far more than just occasionally pushing an image off to one side. In fact, they are one of the primary tools used in modern CSS-based web design. Floats are used to create multicolumn layouts, navigation toolbars from unordered lists, table-like alignment without tables, and more. See Chapter 24 for examples.
To make an element float to the left or right and allow the following text to wrap around it, apply the float property to the element.
float
Values:

    left | right | none | inherit

Initial value:

    none

Applies to:
All elements
Inherited:
No
In this simple example, the float property is used to float an image to the right (Figure 21-1).

    img {float: right; margin: 20px;}



    <p><img src="img/placeholder.gif">Aliquam pulvinar volutpat...</p>

Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Positioning Basics
Inhaltsvorschau
It is obvious by how readily web designers co-opted HTML tables that there was a need for page-like layout on web pages. Cascading Style Sheets provides several methods for positioning elements on the page relative to where they would normally appear in the document flow.
If you thought tables were tricky to manage, get ready for CSS positioning! While the positioning properties are fairly simple at face value, inconsistent and buggy browser implementation can make it challenging to achieve the results you're after on all browsers. If fact, positioning can be complicated even when the CSS Recommendation is followed to the letter. It's a recipe for frustration unless you get to know how positioning should behave and then know which browsers are likely to give you trouble (some notorious browser bugs are listed in Chapter 25). This section introduces the positioning-related properties as they are defined in CSS 2.1 as well as some key concepts.
To get the ball rolling, we'll look at the various options for positioning elements and how they differ. There are four types of positioning, specified by the position property.

position
Values:

    static | relative | absolute | fixed | inherit

Initial value:

    static

Applies to:
All elements
Inherited:
No

The position property identifies that an element is to be positioned and selects one of four positioning methods (each will be discussed in detail in upcoming sections in this chapter):

Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Absolute Positioning
Inhaltsvorschau
There have been examples of absolute positioning throughout this chapter, but this section examines this popular method of positioning in more detail.
An absolutely positioned element has these basic characteristics:
  • It is declared using {position: absolute;}.
  • It is positioned relative to the edges of its containing block using one or more of the offset properties (top, right, bottom, left). Properties that are not specified are set to auto (the default). The offset values apply to the outer edge of the element box (including the margin value, if there is one).
  • It is completely removed from the document flow. The space it would have occupied in the normal flow is closed up and it no longer has an affect on other elements (for instance, text won't wrap around it).
These points are demonstrated in this simple example of an absolutely positioned list element (Figure 21-15).

    div {position: absolute; background-color: #999; width: 440px;}

    ul {position: absolute; left: 60px; top: 30px; background-color: #CCC; margin: 0px;}



    <div>

      <p>Phasellus feugiat eros at mi. Integer leo tellus, hendrerit non, euismod

non, condimentum in, sem. </p>

       <ul>

           <li>Lorem ipsum dolor</li>

           <li>Sit amet, consectetuer</li>

          <li>Adipiscing elit</li>

          <li>Vel nonummy ligula</li>

          <li>Tempus dignissim</li>

       </ul>

      <p>Fusce suscipit, ligula eget tempus ...</p>

    </div>

Figure 21-15: Absolute positioning
In all of the previous examples, elements have been positioned using length measurements for the offset property values. The
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Fixed Positioning
Inhaltsvorschau
Fixed positioning is essentially the same as absolute positioning, only the containing block is the viewing area (or viewport ; typically the browser window). The distinguishing feature of fixed elements is that they do not scroll with the document, but are persistent on the page. On printed pages, fixed elements may appear in the same place on all pages.
In addition to not scrolling, fixed elements share these basic characteristics:
  • They are declared using {position: fixed;}.
  • They are positioned relative to the edges of the viewport (browser window) using one or more of the offset properties (top, right, bottom, left). Properties that are not specified are set to auto (the default). The offset values apply to the outer edge of the element box (including the margin value, if there is one).
  • Like absolutely positioned elements, they are completely removed from the document flow, and the space they would have occupied is closed up.
Fixed elements can be used to create frame-like interfaces or to place persistent elements on the page. In this example, a fixed element is used as a short sidebar that stays put as the document scrolls (Figure 21-19).

    ul {position: fixed; top: 0px; left: 0; width: 100px; background-color:

#999; margin: 0; padding: 10;}

    p, h1 {margin-left: 150px;}

Figure 21-19: Fixed positioning
Internet Explorer 6 and earlier for Windows does not support fixed positioning. Objects with fixed positioning are treated as though they are static, and therefore behave as though they have not been positioned at all. There are workarounds available; to find them, search for "CSS fixed position in IE" or something similar in your favorite search engine. Support in IE 7 for Windows (in beta as of this writing) has not been confirmed.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Relative Positioning
Inhaltsvorschau
Relative positioning works differently than absolute and fixed positioning. The critical difference is that although the element is moved around, the space where it would have appeared in the normal flow is preserved and continues to influence the elements that surround it.
Relatively positioned elements have these characteristics:
  • They are declared using {position: relative ;}.
  • They are positioned relative to their initial position in the normal flow using one or more of the offset properties (top, right, bottom, left). Properties that are not specified are set to auto (the default).
  • Their original space in the document flow is preserved.
  • Because they are positioned elements, they can potentially overlap other elements.
This example of a relatively positioned emphasized (em) element demonstrates the basic syntax and behavior of relative positioning (Figure 21-20). Notice that when the element is moved, its space is left behind and the surrounding elements behave as though it is still there.

    em {position: relative; top: -36px; right: -36px; background: #ccc; }

Figure 21-20: Relative positioning
In relative positioning, the top, right, bottom, and left properties move the element relative to its original position. Specifying a positive value for top moves the element down by that amount. Specifying a value for left moves the element to the right, and so on, such that a positive value for one side is equivalent to a negative value on the opposite side (the computed values are right=-left
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Chapter 22: CSS for Tables
Inhaltsvorschau
Tables have gotten a bad reputation in web design circles because of their notorious misuse as page layout devices. Although CSS now offers alternatives to tables for presentation purposes, it's not necessary to kick tables to the curb entirely. In fact, they serve an important purpose: the presentation of tabular data. Using CSS table properties with the full set of HTML table elements allows tables to go back to their original calling, but with more sophisticated tools for handling them.
This chapter explains these CSS 2 properties for controlling table presentation:
caption-side
border-spacing
table-layout
empty-cells
border-collapse
display (table-related values)
If you are familiar with table structure in HTML, then the way CSS handles tables should not be a big surprise. For reasons of backward compatibility, the CSS specification used the row-based table layout model as the starting point for additional layout models and properties for controlling presentation. CSS is broader in its scope, however, because it is designed to work with document languages other than just HTML and XHTML. The system for providing table layout capabilities for non-HTML languages is discussed in the "Table Display Values" section at the end of this chapter.
The CSS 2.1 Recommendation is very detailed in its description of the defined behaviors for the table layout model. For a deeper look into the CSS table model , read the specification online at
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
The Essence of Tables
Inhaltsvorschau
If you are familiar with table structure in HTML, then the way CSS handles tables should not be a big surprise. For reasons of backward compatibility, the CSS specification used the row-based table layout model as the starting point for additional layout models and properties for controlling presentation. CSS is broader in its scope, however, because it is designed to work with document languages other than just HTML and XHTML. The system for providing table layout capabilities for non-HTML languages is discussed in the "Table Display Values" section at the end of this chapter.
The CSS 2.1 Recommendation is very detailed in its description of the defined behaviors for the table layout model. For a deeper look into the CSS table model , read the specification online at www.w3.org/TR/CSS21/tables.html. Once again, Eric Meyer's Cascading Style Sheets: The Definitive Guide (O'Reilly) is the book to turn to for making sense of the spec.
This section provides a summary of some of the key concepts of the CSS table model.
At the most basic level, tables are divided into rows and columns. CSS 2.1 describes the model as row primary, because rows are identified explicitly in the document structure. Cells are always descendants of rows, not columns. Columns are merely derived based on the number of cells in the rows.
The intersection of all the rows and columns in a table forms a grid and defines a basic grid cell unit. The actual cells (the boxes that contain the content) in the table may be composed of more than one grid cell, as is the case when cells are set to span rows or columns. Figure 22-1 shows the structure of the CSS table model.
Figure 22-1: Table structure
In addition to cell boxes, the CSS visual box model for tables generates (implied) boxes around rows, row groups, columns, column groups, and the table itself. These boxes correspond to the
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Styling Tables
Inhaltsvorschau
For the most part, you don't need any special properties to control the presentation of tables and their content. Most of the properties listed in the previous chapters apply to table elements as well, although some may have different values when applied to table objects. This list is an overview of the styles to use for formatting typical aspects of a table and its content.
Text content
Style the text content within tables, rows, and cells as you would any other text element in a document. You can apply the following properties to any table element.
  • font and all font-related properties
  • All text-formatting properties
  • color (changes the text color)
Alignment of content in cells
You can use style properties to adjust the horizontal and vertical placement of cell content. Note that applying text-align: center to the table element does not center the table on the page, but rather centers all the content within each table cell.
  • text-align for horizontal alignment within a cell. The values left, right, and center apply.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Borders
Inhaltsvorschau
There are two models for handling borders in CSS 2.1. In one, the borders around cells are separated from each other. In the other, borders are said to "collapse" and are continuous from one cell to the next. The border-collapse property allows authors to choose which model the table should follow.
border-collapse
Values:

    collapse | separate | inherit

Initial value:

    collapse

Applies to:
table and inline-table elements
Inherited:
Yes
In the separated borders model , the border is drawn on all four sides of each cell (or as specified by the border properties), and an amount of space can be added between cells with the border-spacing property.
The border-spacing property is not supported by Internet Explorer Versions 6 and earlier. Support in IE 7, in beta as of this writing, is not documented.

border-spacing
Values:

    <length> <length>? | inherit

Initial value:

    0

Applies to:
table and inline-table elements
Inherited:

Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Table Layout (Width and Height)
Inhaltsvorschau
User agents (typically browsers) may use one of two algorithm-driven approaches to calculate the width of a table: fixed-width layout and automatic-width layout. Web page authors may specify which layout approach to use for a specific table using the table-layout property.
table-layout
Values:

    auto | fixed | inherit

Initial value:

    auto

Applies to:
table and inline-table elements
Inherited:
No
The fixed value for table-layout tells the browser or other user agent to calculate the size of the table using the "fixed" algorithm. This method requires the least work of the user agent because the table width is determined by the width values of the table, columns, and cells within the table.
First, the user agent takes the widths of column elements that are set to a specific width (not auto). Then it looks at the cells in the first row of the table. Cells with specific width values (not auto) set the width for their columns. Any remaining columns that have the width set to auto are sized so their widths are roughly equal to fill the remaining space in the table.
The final width of the table is the sum of the column widths or the table element's width value, whichever is greater.
The important aspect of this model is that only width values provided for cells in the first row of the table apply. Therefore, if the top cell in a table is set to 200 pixels and another cell farther down in the same column is set to 350 pixels, the column will be 200 pixels wide. The setting in the lower row is simply ignored in the fixed layout model.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Table Display Values
Inhaltsvorschau
CSS was designed to work with all XML document languages, not just XHTML. It's likely that other languages may have the need for tabular layouts, but will not have elements like table, td, or tr in their vocabularies.
To this end, the CSS 2.1 specification allows authors to assign table element roles to any element using the display property. The display property was discussed in Chapter 16 in relation to block and inline elements. This section covers the values listed in bold.
display
Values:

    inline | block | list-item | run-in | inline-block | table | inline-table

 | table-row-group | table-header-group | table-footer-group

 | table-row | table-column-group | table-column

 | table-cell | table-caption | none | inherit

Initial value:

    inline

Applies to:
table and inline-table elements
Inherited:
No
Using the table-related display values , the elements from any markup language can be "mapped" to table elements. A simple example should make this clear. Consider this markup written in a hypothetical XML language.

    <platter>

      <cheese>

        <name>Brie</name>

        <origin>France</origin>

      </cheese>

      <cheese>

        <name>Manchego</name>

        <origin>Spain</origin>

      </cheese>

    </platter>

By attaching these style rules:

    platter { display: table; }

    cheese { display: table-row; }

    name, origin { display: table-cell; }

The example would display in the user agent as though it were marked up like this:
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Chapter 23: Lists and Generated Content
Inhaltsvorschau
One of the advantages to using an ordered list element on a web page is that the browser numbers list each item automatically. This makes it easier to add, delete, or move list items around without manually editing the numbers, because they aren't in the source document in the first place—they're generated by the user agent. CSS 2.1 provides a number of properties for controlling the style, content, and position of numbers and bullets (called markers ) used for unordered and ordered lists .
The creators of the CSS 2.1 specification realized there might be other instances in which it would be useful to have user agents generate content that isn't actually present in the document tree. The generated content features of CSS 2.1 provide a mechanism for inserting any specified text or counters (automatic numbering) before or after any element in an (X)HTML or XML document.
This chapter covers the CSS 2.1 properties related to controlling markers for list items as well as the properties associated with generated content.

    list-style-type         list-style

    list-style-image        display: list-item

    list-style-position     content

    quotes                  counter-reset

    counter-increment

Bulleted and numbered lists have been around since the very beginning of HTML. Extensions to the ul and ol elements gave designers the ability to choose a bullet shape or numbering format, but beyond that, authors have had little control over list presentation. CSS 2.1 offers some improvements, most notably the ability to replace bullets with your own images.
In modern standards- and accessibility-driven web design, lists are being used in interesting ways to create navigation that previously would have been created with graphics and JavaScript (see Chapter 24).
Ordered and unordered lists are unique elements in that they automatically add a marker
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
CSS for Lists
Inhaltsvorschau
Bulleted and numbered lists have been around since the very beginning of HTML. Extensions to the ul and ol elements gave designers the ability to choose a bullet shape or numbering format, but beyond that, authors have had little control over list presentation. CSS 2.1 offers some improvements, most notably the ability to replace bullets with your own images.
In modern standards- and accessibility-driven web design, lists are being used in interesting ways to create navigation that previously would have been created with graphics and JavaScript (see Chapter 24).
Ordered and unordered lists are unique elements in that they automatically add a marker (a bullet or a number) to the page that isn't part of the document source. Use the list-style-type property to select the type of marker that appears with each list item. This property replaces the deprecated type attribute in XHTML.

list-style-type
Values:

disc | circle | square | decimal | decimal-leading-zero |

lower-roman | upper-roman | lower-greek | lower-latin |

upper-latin | lower-alpha | upper-alpha | none | inherit

Initial value:

disc

Applies to:
Elements whose display value is list-item (in XHTML, the ul, ol, and li elements)
Inherited:
Yes

Three values for list-style-type (disc, circle, and square) generate a bullet shape, just as browsers have been doing for unordered lists for years. The actual design and rendering of each bullet shape is left to the user agent. In other words, there is no way to alter the color, size, or other presentation attributes of a generated bullet. Figure 23-1 shows each of the bullet markers .

Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Generated Content
Inhaltsvorschau
Generated content refers to content that is not in the document tree, yet is inserted in the page when it is displayed in a browser window, printed on paper, projected on a screen, read aurally, or otherwise delivered. Generated content may be specified text, images, or other media (or even the values of attributes) added before or after an element. It could be used to insert the name of the person making an edit after deleted text (del element). Used together with media-specific style sheets, generated content could be used to write out the URL after links only when the document is printed, or to say "end of table" at the end of a long table only when the document is read aurally.
There are also several properties that control counters, the mechanisms that keep track of the numbering for ordered list. Used together with generated text, it is possible to insert the word "Section" before each automatically numbered section heading. Allowing the user agent to automatically insert labels and numbers makes it easier to reorganize and relabel long documents because the numbers don't need to be edited manually in the source.
Unfortunately, no version of Internet Explorer as of this writing supports generated content , because IE doesn't support the :before and :after pseudoselectors . If you do specify generated content, IE will just ignore it, so it does no harm. You can begin using it immediately to provide a richer experience for users with browsers that do support it (Mozilla, Firefox, Netscape 6+, Opera). Safari offers partial support as noted in the chapter.
Generated content is specified in the style sheet with the :before and :after pseudoelements (pseudoelements are discussed in Chapter 17). The :before selector inserts content (most commonly, but not limited to, text characters, an image, or quotation marks) immediately before the targeted element. The :after pseudoelement inserts the generated content just after the targeted element.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Chapter 24: CSS Techniques
Inhaltsvorschau
The previous chapters introduced the CSS tools available in web designers' tool-belts: the properties and values provided in the CSS specification. This chapter puts them together in a few of the most popular design and layout techniques used in CSS-driven web design, including:
  • Centering a fixed-width page
  • Multicolumn layouts
  • Boxes with rounded corners
  • Replacing text with background images
  • CSS rollovers
  • List-based navigation
As in so many web-related tasks, there are seemingly endless variations on accomplishing the same goal. Each example in this chapter represents just one solution (you may know of better approaches). The intent is to demonstrate basic style sheet strategy and to provide "starter kits" for achieving basic visual and layout effects with CSS. There is usually much more to be said about each technique, so references to additional resources are provided when available. The "CSS Techniques Resources" section at the end of the chapter lists recommended reading for those interested in learning more about what can be done with CSS-driven design.
As a strategy for controlling the width of a page while allowing for varying monitor resolutions, it is common for web designers to create fixed-width pages that are then centered in the width of the browser window. In the past, this was achieved by slapping a center tag (or <div align="center">...</div>) around a table. In this section, we'll look at three CSS methods for centering a fixed-width page: the official CSS way, a way that works in Internet Explorer, and an effective "hack." All three examples have the effect shown in Figure 24-1.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Centering a Page
Inhaltsvorschau
As a strategy for controlling the width of a page while allowing for varying monitor resolutions, it is common for web designers to create fixed-width pages that are then centered in the width of the browser window. In the past, this was achieved by slapping a center tag (or <div align="center">...</div>) around a table. In this section, we'll look at three CSS methods for centering a fixed-width page: the official CSS way, a way that works in Internet Explorer, and an effective "hack." All three examples have the effect shown in Figure 24-1.
Figure 24-1: Centering a fixed-width page element
In CSS, the proper way to center a fixed-width element is to specify a width for the element that contains all the page's contents (a div is the usual choice), and then set the left and right margins to auto. According to the CSS visual formatting model, this will have the net effect of centering the element in the initial containing block.

   div#page {

      width: 500px;

      margin-left: auto;

      margin-right: auto; }

This method works for all current standards-compliant browsers, including Internet Explorer 6 for Windows when it is in "Standards" mode (see Chapter 2 about triggering standards-compliance mode in browsers using the DOCTYPE declaration). It will not work with in IE 6/Windows in "Quirks" mode or any earlier version.
An alternative, yet inelegant, solution is to center the whole page using the text-align property on the body element. This technique ultimately amounts to a hack, because it takes a text property and uses it to center any number of items.
The problem with this method is that because horizontal alignment is inherited, all the text on the page will be centered in its element boxes. It is necessary to override the inherited centering by also specifying left alignment for every descendant of the
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Two-Column Layouts
Inhaltsvorschau
Multicolumn layouts that once required HTML tables are now achievable using CSS alone. Column layouts can be done using floats or absolute positioning (see Chapter 21 for details on both).
Of course, there are endless variations on two-column layouts in terms of page components, measurements, backgrounds, and so forth. The examples in this section represent just a few very basic possibilities. They reveal the general strategy for approaching two-column designs and should serve as a good head start toward implementing your own layouts. It should be noted, however, that they are based on the assumption that the main content column will be longer than the side columns. If your side columns are longer, it may be necessary to make adjustments to the code examples shown here.
The markup and styles in this example produce a page with a header area, a main column of content, a sidebar of links, and a footer for copyright information, as shown in Figure 24-2.
This markup provides the necessary elements for the two-column layout . The masthead and footer are optional and could be omitted for a minimal two-column structure.

    <div class="masthead">

    Masthead and headline

    </div>

     

    <div class="main">

    Main article

    </div>>

     

    <div class="sidebar">

    list of links

    </div>

     

    <div class="footer">

    copyright information

    </div>

Figure 24-2: Two-column layout
The source document has been divided into four divs, one each for the masthead, content, sidebar, and footer. The content has been placed before the sidebar in the source document so that it is accessed first by users with non-graphical browsers. That means that we can't float the sidebar because it will not float above the preceding block element to the top of the page. Instead, the main content
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Three-Column Layouts
Inhaltsvorschau
Three-column layouts are fundamentally the same as the previous two-column examples; they just require some extra planning for the third column. These examples use length values instead of percentages to create fixed layouts. In addition, padding, borders, and margins are added in one of the examples, requiring a fix for a well-known browser bug. Browser bugs and fixes are briefly addressed here but are covered in detail in Chapter 25. Again, these examples assume that the main content column will be longer than the side columns, which of course, is not always the case in the real world. It may be necessary to make adjustments to these examples to make them work for your content, but they are a good push in the right direction.
This example uses floated elements to create a three-column layout (a main content column flanked by left and right sidebars) with optional header and footer (Figure 24-4). The advantage of floating is that you can set the footer to start below the longest column without knowing its height ahead of time (usually not possible). Remember that with floating, the order that the elements appear in the source document is significant. To keep this example straightforward, the content div has been moved between the sidebar divs in the source.
Figure 24-4: Three-column layout using floats
The basic structure of the markup for the layout is shown here. In this example, all of the elements have been placed in a container div so the width of the entire layout can be specified. A border has been added to the container to reveal its edges.

    <div id="container">

     

    <div id="masthead">

    Masthead and headline

    </div>

     

    <div id="links">

    list of links

    </div>

     

    <div id="main">

    Main article...

    </div>>

     

    <div id="news">

    Announcements...

    </div>

     

    <div id="footer">

    copyright information

    </div>

     

    </div>

Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Boxes with Rounded Corners
Inhaltsvorschau
Rounded corners are de rigeur in contemporary graphic design. Due to the rectangular nature of web design, there's no getting around using graphics for the rounded corners. But prior to CSS, the only option for creating an expanding box with rounded corners was to set up a nine-celled table. The same effect can be achieved using CSS styles and logical markup (and no tables, of course). As for most web design problems, there are many related solutions, the most simple of which are presented here. Other resources are listed at the end of this section.
The box in the first example creates a simple expandable rounded box filled with a solid color, as shown in Figure 24-8.
Figure 24-8: Simple box with rounded corners
These separate images could be combined into a single image file and applied in varying positions to each corner of the box. The advantage is the need to load or preload only one image, as opposed to four. This technique is discussed in more detail in the upcoming "CSS Rollovers" section.
This technique takes four image files (one for each corner) and applies them as background images to four elements in the markup. Figure 24-9 shows each image file used in the example.
Figure 24-9: The corner graphics for the simple box
The trick is making sure that the markup has four available elements for background image placement. This is what CSS designers commonly refer to as finding hooks in the markup to which styles can be applied. If your document structure has fewer than four elements, it may be necessary to add a div or two to get the necessary number of hooks (see note below). This generic, all-purpose example is created entirely out of
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Image Replacement
Inhaltsvorschau
Web designers frustrated with typography limitations on the Web have been replacing text with inline images for more than a decade. The problem with swapping out real text, such as an h1 element, for an img is that the text is removed from the source document entirely. Providing alternative text improves accessibility, but it does not repair the damage to the semantic structure of the document. Not only that, in terms of site maintenance, it's preferable to control matters of presentation from the style sheet and leave the source free of purely decorative elements.
The year 2003 saw the dawn of CSS image replacement techniques that replace a text element with a background image specified in a style sheet. The text element itself is still present in the source document, but is prevented from displaying via some CSS sleight of hand. It should be noted that, as of this writing, there is no ideal solution for CSS image replacement, just different approaches and trade-offs. Most techniques rely on users being able to read the content in images when the text is hidden, which means users who have CSS turned on but images turned off (or who are simply waiting for images to load over a slow connection) are not well served. This problem remains to be solved.
This section introduces the most popular image replacement techniques as of the end of 2005, along with the advantages and disadvantages of each. To check in with the state of image replacement, see David Shea's (of Zen Garden fame) list and articles at www.mezzoblue.com/tests/revised-image-replacement/.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
CSS Rollovers
Inhaltsvorschau
A rollover is a visual effect in which an item on the page changes when the pointer is placed over it. It has proven to be an effective interface device for indicating that a button or link is interactive and is ready to be clicked. Previously, it was necessary to use JavaScript to create rollover effects, but the same thing can be accomplished with CSS alone using the :hover pseudoclass selector.
It should be noted that Internet Explorer 6 (and earlier) does not support :hover on elements other than links (a), so this section focuses on text and image link rollovers . The good news is that IE 7 expands the use of :hover to apply to all elements.
A rollover can be used to change any aspect of an element's appearance. You can change the size or color of the text, its background color, its decoration, or virtually any property that can be used to style text. Figure 24-12 shows just a few examples. Styles are applied to the a element, and an alternate style is specified with the a:hover selector for the rollover state.
Remember, to work correctly, the pseudoclass selectors must appear in the style sheet in the following order: :link, :visited, :hover, :active (think LVHA, or "Love, Ha!").
In all three examples, the default link is set in gray text with its underline turned off using this rule.
Figure 24-12: Examples of text rollover effects on links

    a:link {

        text-decoration: none;

        color: #666;

        }

In Example 1, the rollover changes the link to black and makes the underline appear.

    a:hover {

        text-decoration: underline;

        color: #000; }

Example 2 demonstrates a popular technique of using a fancy bottom border instead of the generic underline. A little padding is added to give the link enough space.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
List-Based Navigation Bars
Inhaltsvorschau
Horizontal navigation toolbars are a staple of web interface design. Traditionally, they were created with some number of adjacent text links or a line-up of images. Either way, there wasn't much meaning to their markup in the document source. When you think about it, it makes sense for a list of navigational options to be marked up as a list in the source. With CSS, it is possible to give it the appropriate semantic markup while visually presenting the options as a familiar horizontal bar.
There are two methods for changing a bulleted list into a horizontal navigation bar. The first makes the list items display inline instead of stacked (the default display mode for block elements). The second uses floats to line up the list items and links. Both examples below use this markup for an ordinary unordered (bulleted) list with five list items. Figure 24-15 shows how it looks using the default browser styles.

    <ul id="nav">

        <li><a href="/">Water</a></li>

        <li><a href="/">Fire</a></li>

        <li><a href="/">Air</a></li>

        <li><a href="/">Earth</a></li>

        <li><a href="/">Beyond</a></li>

    </ul>

Figure 24-15: The unstyled list
We'll start with the minimum style rules for removing the bullets (list-style-type: none) and making the list items appear next to each other instead of in a list (display: inline). The margins and padding are set to 0 to prepare for anchor (a) element styling. The results of the styles thus far are shown in Figure 24-16.

    ul#nav {

        list-style-type: none;

        margin: 0px;

        padding: 0px; }

     

    ul#nav li {

        display: inline; }

Figure 24-16: Making a list display horizontally
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
CSS Techniques Resources
Inhaltsvorschau
With CSS (and a little know-how), you can make your page as hip, pretty, gothic, mod, or corporate as you like. It's limited only by your imagination. To see just how sophisticated CSS-based web design can be, I enthusiastically refer you to the CSS Zen Garden site at www.csszengarden.com. It is a showcase of stunningly varied designs, all based on the same marked-up XHTML document. The spin-off book, The Zen of CSS Design: Visual Enlightenment for the Web by Dave Shea and Molly E. Holzschlag (Peachpit Press) dissects design elements in 36 designs and demonstrates the CSS techniques behind them.
For more detailed demonstrations of what you can do with CSS, I recommend Eric Meyer on CSS and More Eric Meyer on CSS, written by (surprise) Eric Meyer (New Riders).
Another book that has served as a reference and inspiration for this chapter is Web Standards Solutions: The Markup and Style Handbook by Dan Cederholm (Friends of Ed).
There are also a number of online resources that offer CSS tips, techniques, and tutorials.
A List Apart (www.alistapart.com)
A List Apart is the go-to source for articles on CSS and other web design matters. Their all-star contributing writers are authorities in all matters of web design.
Stopdesign (www.stopdesign.com)
Doug Bowman is one of the top dogs in standards-based web design. His site offers useful tutorials and commentary on designing with CSS.
Mezzoblue (www.mezzoblue.com)
This is the personal site of Dave Shea, the creator and cultivator of the CSS Zen Garden.
Meyerweb (www.meyerweb.com)
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Chapter 25: Managing Browser Bugs: Workarounds, Hacks, and Filters
Inhaltsvorschau
by Aaron Gustafson
In an ideal world, software would be flawless, W3C Recommendations would be clear, and this chapter would never have to be written. Welcome to reality.
This chapter will address most of the common browser bugs you will encounter when designing with CSS and will help you quickly and easily wrangle those bugs into submission by using each browser's own misinterpretation or ignorance of the specs against them (in the form of hacks and filters). First, the chapter will tackle the buggy browsers on a per-browser basis and then, it will wrap with a hack management strategy that will make your life much easier, today and in the future.
Before getting into listing all of the problems that we, as CSS designers, have to deal with when it comes to browsers, it is important to take a step back and realize why we have browser bugs in the first place.
As anyone who has tried reading them can attest, the W3C specifications aren't exactly clear in many areas and they certainly are not a roadmap to implementation for browser manufacturers. In many cases, browser developers have to interpret what they read in the specs and try to make them work while simultaneously trying to get the browser out the door on time. In other cases, decisions have been made to deviate from the specs to make life "easier" for the designer or developer (see Internet Explorer's box model problem, later in this chapter).
We could spend countless hours discussing the problems with any one browser, but it's really best to take a step back and realize that no browser is perfect. Making yourself aware of each browser's inadequacies and figuring out what can be done (if anything) to overcome these problems is far more constructive. And this chapter will help you do exactly that.
This section will address the most common browsers and the hacks and filters that can be used to make sure they get the CSS rules they need (or don't get the ones they don't understand) to render pages appropriately. We'll start with some of the older browsers that are still kicking around and work toward modernity.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Working with "Troubled" Browsers
Inhaltsvorschau
Before getting into listing all of the problems that we, as CSS designers, have to deal with when it comes to browsers, it is important to take a step back and realize why we have browser bugs in the first place.
As anyone who has tried reading them can attest, the W3C specifications aren't exactly clear in many areas and they certainly are not a roadmap to implementation for browser manufacturers. In many cases, browser developers have to interpret what they read in the specs and try to make them work while simultaneously trying to get the browser out the door on time. In other cases, decisions have been made to deviate from the specs to make life "easier" for the designer or developer (see Internet Explorer's box model problem, later in this chapter).
We could spend countless hours discussing the problems with any one browser, but it's really best to take a step back and realize that no browser is perfect. Making yourself aware of each browser's inadequacies and figuring out what can be done (if anything) to overcome these problems is far more constructive. And this chapter will help you do exactly that.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
The Browsers
Inhaltsvorschau
This section will address the most common browsers and the hacks and filters that can be used to make sure they get the CSS rules they need (or don't get the ones they don't understand) to render pages appropriately. We'll start with some of the older browsers that are still kicking around and work toward modernity.
Thankfully, this archaic browser is finally on its way out with less than 0.3% market share according to most statistics, and probably even lower by the time you read this. Originally launched in 1997, Netscape Navigator 4 (NN4.x) was an impressive browser. Needless to say, it hasn't aged all that well.
NN4.x's CSS support is pretty basic and, although some people still spend time designing for it, most sites do not get the kind of traffic that would warrant spending much time discussing its numerous issues. In fact, most CSS designers and web standards advocates have, instead, embraced the idea of "graceful degradation" and provide only the most rudimentary styling (mostly fonts and colors) to this outdated browser.
Be sure to consult your own site's browser statistics to decide when, and if, you need to degrade your design for a particular browser. Remember that percentages can be misleading: 0.3% of users who visit your personal photo gallery is likely to be a far cry from the same percentage visiting eBay. To make a design degrade gracefully for NN4.x, you need to serve it a simple style sheet and hide the stuff it doesn't understand. This is easily accomplished by using NN4.x's basic understanding of CSS against it in one of two ways. The first involves use of the @import rule, which is not understood by NN4.x:

    <link rel="stylesheet" type="text/css" href="my_basic.css" />

    <style type="text/css">@import(my_advanced.css)</style>

In the above example, NN4.x applies the first style sheet because it understands how to "link" a style sheet. The second style sheet it ignores, because Netscape has no idea what
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Hack and Workaround Management 101
Inhaltsvorschau
Now that your head is spinning with all of the browser hacks and workarounds needed to make most of the modern browsers fall in line, it's time to bring some order to the chaos. In the browser world, change is steady, if not rapid. You need to plan for the future and for the eventuality of "retiring" certain browsers. You need to craft a strategy for long-term hack management .
Molly E. Holzschlag wrote an excellent article on long-term hack management for InformIT called "Integrated Web Design: Strategies for Long-Term CSS Hack Management," which you can find at www.informit.com/articles/article.asp?p=170511&rl=1. As her article outlines, you can manage the use of browser hacks and workarounds by making deliberate and thoughtful choices about what hacks you use and how you integrate them with the rest of your CSS. How might you organize your screen media CSS for a site that has the following requirements?
  • Full support for IE 5.5+/Win, Netscape 7.1+, Firefox, Safari, and Opera
  • Degraded support for NN4.x (typography) and IE 5.x/Mac (typography and color)
  • Easy-to-add/change the color information for the site
Sometimes drawing the page out on paper gives the clearest picture. Figure 25-3 outlines one way you might address the requirements.
Figure 25-3: A basic outline of CSS file and rule management
If you start on the left with the (X)HTML page, you see this link to a single CSS file (main.css)

    <link rel="stylesheet" type="text/css" media="screen" href="main.css" />

That file includes the basic rules you want to show NN4.x and IE 5.x/Mac as well as two @import rules. The first
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Chapter 26: Introduction to JavaScript
Inhaltsvorschau
by Aaron Gustafson
A web page that is semantically marked up and beautifully designed (with CSS, of course) is wonderful, but to really make it an experience, it needs some interactivity. This is what we call the "behavior layer" and, in most cases, it is made possible through use of a technology called JavaScript . This chapter will walk you through a little history of the JavaScript language and then discuss the basic building blocks of modern JavaScript.
JavaScript is an object- and prototype-based programming language that got its start in 1995 as the creation of Brendan Eich at Netscape. It was originally named "Mocha" and then "LiveScript" before being confusingly re-christened JavaScript in conjunction with its release in Netscape Navigator 2.0 Beta 3 in December of 1995.
It is important to note that JavaScript is not Java. Both are similar to the C programming language and share a similar syntax, but that is pretty much where their similarity ends. The Java programming language was creating quite a stir in the computer world when Netscape was readying LiveScript for release, and, somehow, the decision was made to rename the language JavaScript to cash in on some of the buzz. Unfortunately, it did more to confuse the programming world than it did to improve the popularity of JavaScript.
JavaScript was standardized in 1996 when it was turned over to the European Computer Manufacturer's Association (ECMA) for maintenance and further development. The latest version, JavaScript 1.5, arrived in 1999 and corresponds to ECMA-262 Edition 3. Consequently, JavaScript is sometimes referred to as ECMAScript.
Microsoft offers a competing language, VBScript , based on Visual Basic, but as it is only supported in Internet Explorer, it is a poor choice for the Web. It should also be noted that Microsoft offered its own port of JavaScript, JScript, which supports most of the standard JavaScript functions (albeit in sometimes peculiar ways) and extends some functionality, but, again, only for Internet Explorer.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
A Little Background
Inhaltsvorschau
JavaScript is an object- and prototype-based programming language that got its start in 1995 as the creation of Brendan Eich at Netscape. It was originally named "Mocha" and then "LiveScript" before being confusingly re-christened JavaScript in conjunction with its release in Netscape Navigator 2.0 Beta 3 in December of 1995.
It is important to note that JavaScript is not Java. Both are similar to the C programming language and share a similar syntax, but that is pretty much where their similarity ends. The Java programming language was creating quite a stir in the computer world when Netscape was readying LiveScript for release, and, somehow, the decision was made to rename the language JavaScript to cash in on some of the buzz. Unfortunately, it did more to confuse the programming world than it did to improve the popularity of JavaScript.
JavaScript was standardized in 1996 when it was turned over to the European Computer Manufacturer's Association (ECMA) for maintenance and further development. The latest version, JavaScript 1.5, arrived in 1999 and corresponds to ECMA-262 Edition 3. Consequently, JavaScript is sometimes referred to as ECMAScript.
Microsoft offers a competing language, VBScript , based on Visual Basic, but as it is only supported in Internet Explorer, it is a poor choice for the Web. It should also be noted that Microsoft offered its own port of JavaScript, JScript, which supports most of the standard JavaScript functions (albeit in sometimes peculiar ways) and extends some functionality, but, again, only for Internet Explorer.
JavaScript does have uses beyond the browser as well. It is available in PDF documents, is a primary driver in the Mozilla platform, and even powers the Dashboard Widgets in Apple's Mac OS X 10.4 (Tiger). Using JavaScript outside of a web context is beyond the scope of this chapter, but there are many resources online if you are interested in exploring.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Using JavaScript
Inhaltsvorschau
Like many tools, JavaScript can be used for good or evil. The evil uses of JavaScript are all around: rapid-fire pop-ups that open faster than you can close them, sites that automatically set themselves as your home page, the list goes on and on. If that's what you're interested in doing, please stop reading now.
As web professionals, we have a duty to make the user experience as positive as possible and make our sites both usable and accessible. We always need to consider how our choices as programmers impact our users. Not only should we not wield JavaScript maliciously, but we should take care to use it in such a way that a page or site can be used without it.
As with CSS, JavaScript should "degrade gracefully," in other words, your scripts should be written in such a way that they know if they will be able to run or not and quietly fail if methods they make use of are not supported. It is also important, for many reasons, including accessibility, that your scripts be unobtrusive. This is easily tested by turning off JavaScript support entirely in your browser to make sure the page can still be used.
This is a topic that will be touched on several times throughout this chapter and the next, but we'll begin by discussing how to use JavaScript in your pages.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
JavaScript Syntax
Inhaltsvorschau
Once you get the hang of it, JavaScript can be a very easy language to write. In fact, it is very similar to other common web languages, including ActionScript (which is itself an ECMA scripting language and is the underlying language of Flash) and PHP (which is a server-side scripting language). We'll begin with the basics of syntax.
Each script we write consists of a series of statements . Statements can be terminated with a line break

    first statement

    second statement

or with a semicolon (;)

    first statement; second statement;

For readability, and to avoid potential statement termination problems, it is recommended that you use both:

    first statement;

    second statement;

Sometimes it is helpful to make notes for yourself to keep track of what is going on in a script. As in HTML, JavaScript allows you to make comments in your code but offers a few different ways to do it. The first style of comment uses two forward slashes:

    // this is a comment

This type of comment makes the interpreter ignore the remainder of the line. The second method allows you to comment out multiple lines:
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Event Handling
Inhaltsvorschau
With HTML 4.0, we were given the ability to tie scripts to certain events triggered on a web page. The most famous use of events is still probably JavaScript rollovers on links, triggered by the onmouseover and onmouseout events. Of course, CSS can handle that much easier now, but it doesn't render events useless, as there are many we can tap into (see Table 26-5) and put to good use.
Table 26-5: Common events
Event handler
Event
onblur
An element loses focus (note: buggy).
onchange
The content of a field changes.
onclick
The mouse clicks an object.
onerror
An error occurs when loading a document or an image.
onfocus
An element gets focus.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
The Browser Object
Inhaltsvorschau
Finally, you should at least briefly consider the Browser Object Model or Browser Object. Using JavaScript, you can not only read and control the page and its contents, but also read and adjust properties of the browser displaying it. This can be in the form of resizing the window, or simply getting the value of the URI displayed in the address bar. Table 26-6 summarizes a few of the common properties and methods available to you in the Browser Object, which is accessed programmatically as window.
Table 26-6: Browser Object properties and methods
Property/method
Description
event
Represents the state of an event
history
Contains the URLs the user has visited within a browser window
location
Gives read/write access to the URI in the address bar
opener
Sets or returns a reference to the window that created the window
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Where to Learn More
Inhaltsvorschau
For a more in-depth discussion of JavaScript and access to a lot more properties and methods of native objects, be sure to check out JavaScript: The Definitive Guide by David Flanagan and JavaScript and DHTML Cookbook by Danny Goodman, both of which are published by O'Reilly.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Chapter 27: DOM Scripting
Inhaltsvorschau
by Aaron Gustafson
The Document Object Model (DOM) is an Application Programming Interface (API) for working with structured documents or, in layman's terms, a means of accessing and manipulating the content of an HTML (or XML) file. The DOM is language agnostic and can be accessed by numerous languages, including C++, Java, Perl, PHP, Python, and Ruby. This chapter, however, will focus solely on how JavaScript interfaces with the DOM. Though our main focus will be working with (X)HTML documents, many of these same techniques will work equally well on XML documents.
During the Browser Wars of the late '90s, the two major players in the web browser world, Netscape and Microsoft, enabled developers to manipulate a web page to create what marketing folks termed Dynamic HTML (DHTML). DHTML was essentially a combination of HTML for markup, CSS for style, and JavaScript for manipulating both of those (mostly in the forms of mouseovers and form validation).
DHTML was good in theory, but the two companies pushing the technology each developed distinct ways of coding the same behavior and accessing the same parts of a document. This led many developers down the dark path to "code forking" --that is, writing code to do the same thing in at least two different ways, in order to supply each browser with code only it understands through an intricate (and often fragile) system of browser-detection scripts.
For instance, Netscape enabled you to interact with its proprietary label elements when you gave them a unique ID:

document.layers['myLayer'];

Microsoft enabled similar access, but through a slightly different method:

document.all['myLayer'];

And the differences didn't end there.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
A Sordid Past
Inhaltsvorschau
During the Browser Wars of the late '90s, the two major players in the web browser world, Netscape and Microsoft, enabled developers to manipulate a web page to create what marketing folks termed Dynamic HTML (DHTML). DHTML was essentially a combination of HTML for markup, CSS for style, and JavaScript for manipulating both of those (mostly in the forms of mouseovers and form validation).
DHTML was good in theory, but the two companies pushing the technology each developed distinct ways of coding the same behavior and accessing the same parts of a document. This led many developers down the dark path to "code forking" --that is, writing code to do the same thing in at least two different ways, in order to supply each browser with code only it understands through an intricate (and often fragile) system of browser-detection scripts.
For instance, Netscape enabled you to interact with its proprietary label elements when you gave them a unique ID:

document.layers['myLayer'];

Microsoft enabled similar access, but through a slightly different method:

document.all['myLayer'];

And the differences didn't end there.
Programming in DHTML was time-consuming both in initial development as well as maintenance. Scripts, which should have been short and sweet, sprawled out over hundreds of lines of code. It was incredibly inefficient and frustrating for many. Eventually, DHTML became something of a black art, and the topic wasn't often discussed in polite web design circles. You will sometimes hear the collective access methods of this period in the history of the DOM referred to as "DOM Level 0."
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Out of the Dark Ages
Inhaltsvorschau
October 1998 saw the release of DOM Level 1 by the web standards body, the World Wide Web Consortium (W3C). A collective effort on the part of Microsoft, Netscape, and many other W3C members, the standardized DOM finally enabled DHTML to deliver on its promise of bringing interactivity to the web page through JavaScript. Moreover, it provided a means to manipulate any structured document using any programming language (as discussed above). The W3C defines the DOM as a "platform- and language-neutral interface that will allow programs and scripts to dynamically access and update the content, structure, and style of documents."
Thanks in a large part to the lobbying efforts of the Web Standards Project (WaSP), the newly standardized DOM found a home in Internet Explorer 5 and Netscape 6, making life easier for web developers everywhere. Unfortunately, this change went largely unnoticed in the web community, and many developers continued to ignore DHTML because of the stigma it gained early on.
With the arrival of 2003 came a resurgence of interest in the DOM and a shift in language away from the term DHTML to the new term: DOM Scripting. The shift in nomenclature is a conscious attempt to distance standards-based DOM manipulation from its checkered past. DOM Scripting encourages feature sniffing, browser independence, and graceful degradation. Sounds like a tall order, but in reality, more than 95% of the browsers on the market support at least DOM Level 1, with many even supporting the current standard, DOM Level 2.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
The DOM
Inhaltsvorschau
Perhaps the easiest way to think of the DOM is to think of the document tree . Let's take the following XHTML document as an example:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>

  <title>Sample XHTML</title>

  <meta http-equiv="content-type"

    content="text/html; charset=iso-8859-1" />

  <meta http-equiv="Content-Language" content="en-us" />

</head>

<body>

  <h1>This is a heading, level 1</h1>

  <p>This is a paragraph of text with a

    <a href="/path/to/another/page.html">link</a>.</p>

  <ul>

    <li>This is a list item</li>

    <li>This is another</li>

    <li>And another</li>

  </ul>

</body>

</html>

This is a pretty basic web page, making use of a few different elements. If we were to visualize this as a document tree , it would look something like Figure 27-1.
Figure 27-1: A sample document tree
A document tree like this is roughly akin to a very high level view of the DOM's node tree.
Essentially, the DOM is a collection of nodes. These nodes usually take one of three forms:
  • Element nodes
  • Attribute nodes
  • Text nodes
These nodes are arranged in a hierarchy that we sometimes refer to using a familial model. In (X)HTML, the hierarchy begins with the html element, which is the root element, meaning it has no ancestors. In the above example, html has two child nodes (head and
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Manipulating Documents with the DOM
Inhaltsvorschau
The majority of your DOM Scripting work will likely center around reading from and writing to the document. But before you can do that, you need to understand how to traverse the node tree.
The DOM offers many ways to move around and find what you want. As any HTML or XML document is essentially a collection of elements arranged in a particular hierarchy, we traverse the DOM using the elements as markers . In fact, a lot of what we do in the DOM is akin to wayfinding: using elements (especially uniquely id-ed ones) as signposts, which let us know where we are in our documents and help us get deeper and deeper into our documents without losing our way.
Let's take the following snippet of (X)HTML, for example:

<div id="content">

  <h1>This is a heading</h1>

  <p>This is a paragraph.</p>

  <h2>This is another heading</h2>

  <p>This is another paragraph.</p>

  <p>Yet another paragraph.</p>

</div>

If you wanted to find the h2 in this snippet, you would need to use two of JavaScript's interfaces to the DOM, getElementById( ) and getElementsByTagName( ):

var the_div = document.getElementById( 'content' );

var h2s     = the_div.getElementsByTagName( 'h2' )

var the_h2  = h2s[0];

In the first line, you use the DOM to find an element on the page with an id equal to content and assign it to the variable the_div.
If you don't already have an element reference to begin with, default to the document object, which refers to the page. getElementById( ) is always used with document.
Once you have your container div assigned to the_div, you can proceed to find the h2 you want, using getElementsByTagName( ) (line 2). That method returns an array of elements (h2s), referred to as a collection. Finally, you know that the desired h2 is the first one in that collection and, as Chapter 26 showed, the first element in an array has an index of 0, therefore, the
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Working with Style
Inhaltsvorschau
Once you've mastered the art of structural manipulation with the DOM, you should turn your focus to working with Cascading Style Sheets. The DOM allows access to add, modify, and remove CSS styles. DOM-based CSS manipulation works just like applying inline style using the style attribute.
It is possible, in most modern browsers, to use the setAttribute( ) method to assign a value to the style attribute of an element:

var div = document.getElementById( 'content' );

div.setAttribute( 'style', 'color: #f00; font-weight: bold;' );

Unfortunately, Internet Explorer (at least through Version 6) does not support this method of style application. Thankfully, there is an HTML DOM convention that is available consistently in all browsers: the style property.

div.style.color = '#f00';

div.style.fontWeight = 'bold';

Although not nearly as efficient as using setAttribute( ), this convention does allow granular control of styles.
The style property can be used to get or set style values.

var old_color   = div.style.color; // red

div.style.color = '#f90';          // orange

Individual CSS properties are available as properties of the style property. Hyphenated property names are shortened to camel case to avoid conflict with the subtraction operator (-) in JavaScript. For example, font-weight becomes fontWeight, border-left-width becomes borderLeftWidth, and so on.
The DOM also gives you the ability to disable and enable entire style sheets. To do this, you simply tap into the link elements within the head of the page and then use getAttribute( ) to find the style sheet you want to disable/enable. Setting the disabled property of a style sheet's link element to true will disable it. Setting it to false will enable it again.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
DOM Scripting in Action
Inhaltsvorschau
To better appreciate the power of DOM Scripting, take a look at two relatively simple examples . Instead of breaking down the JavaScript into chunks, helpful JavaScript comments have been added that discuss what the script is doing at each step in the process. The reasoning for this is twofold: it lets you see the script as a whole and it gets you used to seeing comments in code (a habit which is worth picking up to ease long-term maintenance).
This function is an extreme simplification of the technique employed in Invasion of the Body Switchers (alistapart.com/articles/bodyswitchers) by Andy Clarke and James Edwards. It also makes use of John Resig's addEvent( ) function (quirksmode.org/blog/archives/2005/10/_and_the_winner_1.html) for simple event management. It uses a single external CSS file to handle three different font sizes for the browser. We are going to change the font size of the page by changing a class on the body element.
We start with the external style sheet (switcher.css):

body.normal {

  font-size: 80%;

}

body.large {

  font-size: 100%;

}

body.huge {

  font-size: 150%;

}

h1 {

  font-size: 2em;

}

p {

  font-size: 1em;

}

Then we have our XHTML page, with a link to our CSS file, and a placeholder script referring to our JavaScript file (switcher.js):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>

  <title>Switcher Example</title>

  <meta http-equiv="content-type" content="text/html;

    charset=iso-8859-1" />

  <meta http-equiv="Content-Language" content="en-us" />

  <link rel="stylesheet" type="text/css" media="screen"

    href="switcher.css" />

  <script type="text/javascript" src="switcher.js"></script>

</head>

<body class="normal">

  <div id="content">

    <h1>Title</h1>

    <p>This is a paragraph.</p>

    <p>This is another paragraph.</p>

  </div>

  <div>

    <form id="switcher_form" action="switch.php">

      <fieldset>

        <legend>Please choose a font size</legend>

        <select name="size">

          <option value="normal" selected="selected">Normal</option>

          <option value="large">Large</option>

          <option value="huge">Huge</option>

        </select>

        <input type="submit" value="Apply It" />

      </fieldset>

    </form>

  </div>

</body>

</html>

Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Supplement: Getting Started with Ajax
Inhaltsvorschau
The start of 2005 saw the rise of a relatively new technology, dubbed "Ajax" by Jesse James Garrett of Adaptive Path. Ajax stands for Asynchronous JavaScript and XML. In a nutshell, it is the use of the nonstandard XMLHttpRequest( ) object to communicate with server-side scripts. It can send as well as receive information in a variety of formats, including XML, HTML, and even text files. Ajax's most appealing characteristic, however, is its "asynchronous" nature, which means it can do all of this without having to refresh the page. This allows you to update portions of a page based upon user events and provides one of the cornerstones of Rich Internet Applications (RIA) referred to in discussions of "Web 2.0."
The DOM plays into Ajax in a number of ways. How you use the DOM depends a good deal on how you handle the content returned from the server. You can treat the content as simple text using the responseText property of the server response, or you can treat it as XML using responseXML. Assuming the content you pull back from the server is an (X)HTML snippet and you've gotten it as responseText, you could drop that content into a particular spot on the page using innerHTML. On the flip side, if the content you pull back is XML and you've gotten it as responseXML, you can traverse its DOM, cherry-picking or performing functions on the elements, attributes, and text nodes.
This probably sounds very confusing, but it is pretty easy once we go over a few simple examples. For these examples, we are using the XHConn library for simplifying our interaction with XMLHttpRequest( ). The XHConn library is freely available at xkr.us/code/javascript/XHConn/ and allows simple access to XMLHttpRequest( ) by creating a new XHConn object and then initiating its connect( ) method as you will soon see.
As with the DOM Scripting examples (above), for a blow-by-blow of what the script is doing, read the JavaScript comments.
For a simple innerHTML-based Ajax example, we'll create a quasi-functional address book application. We'll start with the XHTML page:
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Chapter 28: Web Graphics Overview
Inhaltsvorschau
Simply put, web graphics must be low-resolution, bitmapped images saved in GIF, JPEG, or PNG format. That statement may be loaded with new terms and acronyms, but rest assured, this chapter provides an explanation of each component. It also takes a look at how color works on monitors and in web browsers, and how that may impact your design decisions. Finally, it provides tips on finding and producing web graphics.
Although there are dozens of graphic file formats out there in the world, only three are supported by web browsers for use on web pages: GIF (pronounced "jif"), JPEG ("jay-peg"), and PNG ("ping"). These formats were selected for use on the Web by browser creators because they are easily ported from platform to platform over a network.
What follows is a brief introduction to each of these online graphic formats. More detailed descriptions are provided in the upcoming chapters dedicated to each format.
The GIF (Graphic Interchange Format) file format is the traditional darling of the Web. It was the first file format to be supported by web browsers, and it continues to be the format for the vast majority of graphics on the Web today.
GIFs are indexed color files with a maximum 8-bit palette capacity, which means that a GIF can contain a maximum of 256 pixel colors. Because they compress color information by rows of pixels, GIF files are most appropriate for graphics that contain areas of flat color, such as logos, cartoon-like illustrations, icons, and line art. GIFs are not efficient at saving photographic images.
GIFs have other advantages. You can make parts of a GIF file transparent, allowing your background image or color to show through. They can also contain multiple images, allowing for simple, self-contained animations. The vast majority of animated ad banners you see on the Web are animated GIFs.
See Chapter 29 for complete information on the GIF file format. Animated GIFs are discussed in Chapter 32.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Web Graphic File Formats
Inhaltsvorschau
Although there are dozens of graphic file formats out there in the world, only three are supported by web browsers for use on web pages: GIF (pronounced "jif"), JPEG ("jay-peg"), and PNG ("ping"). These formats were selected for use on the Web by browser creators because they are easily ported from platform to platform over a network.
What follows is a brief introduction to each of these online graphic formats. More detailed descriptions are provided in the upcoming chapters dedicated to each format.
The GIF (Graphic Interchange Format) file format is the traditional darling of the Web. It was the first file format to be supported by web browsers, and it continues to be the format for the vast majority of graphics on the Web today.
GIFs are indexed color files with a maximum 8-bit palette capacity, which means that a GIF can contain a maximum of 256 pixel colors. Because they compress color information by rows of pixels, GIF files are most appropriate for graphics that contain areas of flat color, such as logos, cartoon-like illustrations, icons, and line art. GIFs are not efficient at saving photographic images.
GIFs have other advantages. You can make parts of a GIF file transparent, allowing your background image or color to show through. They can also contain multiple images, allowing for simple, self-contained animations. The vast majority of animated ad banners you see on the Web are animated GIFs.
See Chapter 29 for complete information on the GIF file format. Animated GIFs are discussed in Chapter 32.
JPEG (Joint Photographic Experts Group) files contain 24-bit color information—that's millions of colors, as opposed to a GIF file's 256. They use what is called a lossy compression scheme, which means that some image information is thrown out in the compression process, but in most cases, the degradation of the image is not detrimental or even noticeable. You can control the amount of compression when you save an image as a JPEG, so you can prioritize smaller file sizes or better image quality, based on your needs. JPEG offers excellent image quality packed into smaller files.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Image Resolution
Inhaltsvorschau
GIFs, JPEGs, and PNGs are pixel-based, or bitmapped (also called raster ), images. When you zoom in, you can see the image is like a mosaic made up of many pixels (tiny, single-colored squares). These are different from vector graphics that are made up of smooth lines and filled areas, all based on mathematical formulas (Figure 28-1).
Figure 28-1: Bitmapped versus vector graphics
When dealing with bitmapped images , you must be aware of the resolution, usually measured in the number of pixels per inch (ppi) of the image. On the Web, graphics are always displayed on low-resolution monitors, so high resolutions typical of print are unnecessary. Web designers typically create graphics at a resolution of 72 ppi as compared to 266 ppi, 600 ppi, or even higher resolutions common to print design.
Working at a low resolution may be an adjustment for a designer accustomed to handling the hi-res images appropriate for print. Most notably, the image quality is lower because there is not as much image information in a given space. This tends to make the image look more grainy or pixelated, and unfortunately, that's just the nature of images on the Web.
When a graphic is displayed on a web page, the pixels in the image map one to one with the display resolution of the monitor. Monitors with a higher display resolution use smaller pixels. Therefore, a graphic that appears to be about one inch square on your 72 ppi monitor may actually appear to be quite a bit smaller on a monitor with a resolution closer to 100. See Figure 28-2.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Color on the Web
Inhaltsvorschau
It is an inescapable fact of web design that there is no guarantee that users will see the colors on your page the way you do. For some, they will look brighter; for others, darker. Some may see a dither pattern where you see smooth color . This is the nature of designing for a medium that is dependent on computer monitors for final display.
Although you can't absolutely control the end display of colors on your page, you can understand the ways monitors handle color. This understanding may influence the decisions you make when designing.
Computer monitors use the RGB color model to display colors. RGB color combines red, green, and blue light (thus, RGB) in various amounts to create a range of colors between black and white. The model is additive, which means the more light you add, the closer the resulting color is to white.
Although all monitors use the RGB color model, the actual hues of red, green, and blue light vary from monitor to monitor. This means that even specific RGB colors that are identified numerically may look quite different on different machines. As a web designer, you need to allow for a certain amount of variation in the way your chosen colors will look to your site's visitors.
The number of colors from the RGB color space a monitor can display at one time is known as its color depth. More specifically, color depth is the number of bits of data used to represent the color of a single pixel on the screen (also called bits per pixel or bpp).
The vast majority of monitors fall into one of three color depth categories: Truecolor (millions of colors), Highcolor (also called HiColor; thousands of colors), or Indexed color (256 colors or fewer). How these systems work has a direct impact on the quality of your colors and tasks such as matching colors in graphics and backgrounds.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Web Graphics Production Tips
Inhaltsvorschau
The nature of the Web and web browsers requires some special considerations when producing graphics. The unique limitations and techniques may take some getting used to, especially if you are more familiar with creating graphics for print.
This section presents a number of production tips that apply to web graphics in general. Additional format-specific techniques can be found in the respective GIF, JPEG, and PNG chapters.
Nearly all commercial graphics programs—both bitmap image editors and vector drawing programs—include some function for saving or exporting graphics in GIF and JPEG format. But if you are serious about creating high-quality images at small file sizes, it is highly recommended that you invest in a tool with web-specific features, such as Adobe Photoshop and ImageReady or Macromedia Fireworks. If you work on a PC and are on a budget, you might want to try out Corel Paint Shop Pro , which has many of the same features as Photoshop, but at a much lower cost.
Without a doubt, the de facto standard for creating web graphics is Adobe Photoshop and its web-specific sidekick, ImageReady. Since Version 5.5, Photoshop has included many web-specific features such as a Save to Web option that shows previews of your graphic in different file formats and at different compression rates.
The other major contender is Macromedia Fireworks, which has similar web graphics features as ImageReady with the addition of vector drawing tools. As this book goes to print, the fate of Fireworks is unclear as a result of Macromedia's acquisition by Adobe.
One of the greatest benefits of using these tools is that they offer previews of your optimization settings (even providing side-by-side comparisons), so you can make adjustments to the settings while keeping an eye on the resulting file size and overall image quality. Both offer very similar controls for file format, color depth, palette dithering, loss, and color palette editing.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Chapter 29: GIF Format
Inhaltsvorschau
GIF (Graphic Interchange Format) was the first graphic file type to be displayed by early web browsers, and it remains one of the most popular and versatile formats for distributing color images on the Web to this day. The GIF format was originally developed by CompuServe in 1987 to distribute images over their network to a variety of platforms (this is why you sometimes see GIFs referred to as "CompuServe GIF").
GIF files have the following characteristics:
  • They are indexed color images with a maximum of 8-bit color information (256 colors).
  • They use LZW compression, which is a lossless compression algorithm.
  • They may be interlaced, displaying in a number of passes on download.
  • They may contain transparent areas.
  • They may contain multiple images, allowing for simple animations.
Any image can be saved as a GIF, but the format is most appropriate for images with areas of flat, solid color, such as logos, icons, charts, and so on (see Figure 29-1). Even if the image contains some photographic elements, if the majority of the image is flat color, GIF is your best bet. GIF is also a good option if you want portions of your image to be transparent, and it's your only option if you want the graphic to contain animation.
The GIF format is not particularly good for photographic images, because quality suffers as a result of the reduction to 256 colors and its compression scheme cannot work efficiently, resulting in larger files. Use JPEG for photos instead.
This chapter begins with further explanation of each of the features listed at the beginning of this chapter (with the exception of animation, which is covered in detail in Chapter 32). The second half of the chapter provides tips for creating GIFs, minimizing file size, and working with the web palette.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
8-Bit Indexed Color
Inhaltsvorschau
GIF files are indexed color images that can contain a maximum of 8-bit color information (they can also be saved at lower bit rates). This means they can contain up to 256 colors—the maximum number that 8 bits of information can define (28 = 256). GIFs may be saved at lower bit depths as well. Lower bit depths result in fewer colors and also reduce file size. This is discussed in the section "Minimizing GIF File Sizes" later in this chapter.
Indexed color means that the set of colors in the image, its palette, is stored in a color table (also called a color map). Each pixel in the image contains a reference (or "index ") to a position in the color table. Figure 29-2 illustrates how a 2-bit indexed color image references its color table for display. In Adobe Photoshop, you can view the table for an indexed color image by selecting Image → Mode → Color Table. The color table is also displayed when you choose GIF in the Save for Web window in Photoshop and the Optimize panel in Adobe ImageReady and Macromedia Fireworks.
Figure 29-2: A 2-bit indexed color image and its color table
When you convert a 24-bit (millions of colors) image to GIF, the colors in the image must be reduced to a palette of 256 colors or fewer. In Photoshop and Fireworks, the conversion to indexed color happens as part of the Save to Web or Export function. Other image editing programs may require you to convert the image to indexed color manually prior to export. In either case, you are usually asked to choose a palette for the resulting image. The sidebar "Common Palettes" outlines the various options available in the most popular image tools.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
LZW Compression
Inhaltsvorschau
The GIF format uses LZW (Lempel-Zev-Welch) compression, which takes advantage of repetition in data streams. Translated into graphic terms, this means that LZW compression is extremely efficient at condensing strings of pixels of identical color. To use an extremely simplified example, when the compression scheme encounters a row of 15 identical blue pixels, it makes up a shorthand notation that means "15 blue pixels." The next time it encounters 15 blue pixels, it uses only the code shorthand. By contrast, when it encounters a row that has a gentle gradation from blue to black, it needs to store a description for every pixel along the way, requiring more data. This is why GIFs are efficient at storing simple graphical images; the areas of flat color take advantage of the LZW compression.
One of the advantages of LZW compression is that it is "lossless," meaning no image information is lost in the compression process, and the decompressed image is identical to the original. While some information may be lost in the conversion process from RGB to indexed color format, once it is converted, the compression itself is lossless.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Interlacing
Inhaltsvorschau
Normal GIFs are either displayed one row of pixels at a time, from top to bottom, or all at once when the entire file has downloaded. On slow connections, this can mean potentially long waits with empty space and generic graphic icons on the screen.
As an alternative, you can save a GIF87a or 89a with interlacing . An interlaced GIF is displayed in a series of four passes, with the first hint of the upcoming image appearing after only 1/8th (12.5%) of the file has downloaded. The first pass has the appearance of a blurry mosaic; as more data flows in, the blurred areas are filled in with real image information, and the image becomes more defined (Figure 29-3). The three subsequent passes fill in 25%, 50%, and 100% of the image information, respectively.
Graphics programs that support the GIF format provide an interlacing option (usually a checkbox) in the Save As or Export dialog box. Simply turn the interlacing on or off when you save the GIF.
Figure 29-3: Interlaced GIFs display in a series of passes
The advantage to using interlacing is that it quickly gives the viewer some idea of the graphic to come. This peek may be enough to make some important decisions. For instance, if the graphic is a familiar image map, the user can use the link to go to another page before the entire image has downloaded. In some cases, the partially downloaded image might be enough for the viewer to decide that he doesn't want to wait for the rest. Now that broadband has become the norm, interlacing is less relevant than it used to be.
The main trade-off in choosing to make a GIF interlaced is that it slightly increases the file size of the resulting graphic. There are also aesthetic considerations involved that come down to a matter of personal taste. Some viewers would rather see nothing at all than look at the temporary visual chaos an interlaced GIF creates. For these reasons, you may choose to limit interlacing to instances when it makes sense, such as for large image maps, instead of using it for every graphic on a page.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Transparency
Inhaltsvorschau
The GIF89a format introduced the ability to make portions of graphics transparent. Whatever is behind the transparent area (most likely the background color or pattern of the page) will show through. With transparency , graphics can appear to be shapes other than rectangles (Figure 29-4).
Figure 29-4: The same GIF image with transparency (left) and without (right)
GIF offers only binary transparency, meaning an area is 100% transparent, or it is 100% opaque (PNG one-ups GIF by offering variable levels of transparency). To understand how transparency works, you need to start with the color table (the table that contains the palette) for the indexed color image. In transparent GIFs , one position in the color table is designated as "transparent," and whatever pixel color fills that position is known as the Transparency Index Color (usually gray by default). All pixels in the image that are painted with that color will be transparent when viewed in a browser.
In image editing tools that use layers, such as Photoshop and Fireworks, you can choose to preserve transparent areas in your layered file when you save or export the GIF. In other graphics tools, the transparent area is specified by selecting a specific pixel color in the image with a special transparency pointer or eyedropper tool.
Occasionally, you see transparent graphics on the Web with light-colored fringe around the edges (called a "halo") that doesn't blend into the background color (see Figure 29-5).
Figure 29-5: A "halo" effect created by anti-aliased edges in a transparent graphic
This effect is the result of anti-aliasing
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Minimizing GIF File Sizes
Inhaltsvorschau
When you are designing and producing graphics for the Web, it is of utmost importance to keep your file sizes as small as possible. The standard "lowest common denominator" guideline for estimating download time over a modem is one second per kilobyte. Of course, actual download times will vary widely, but this gives you a ballpark number to use for comparisons.
Following are a few simple strategies you can follow to minimize the size of your GIF files while keeping an eye on image quality.
You can help keep file size under control by the design decisions you make. After a while, designing graphics for the Web becomes second nature.
Figure 29-8: The Matte color tool (shown in Photoshop CS)

Section 29.5.1.1: Limit dimensions

Though it may seem obvious, the easiest way to keep file size down is to limit the dimensions of your graphic. There aren't any numerical guidelines here; just don't make graphics larger than they need to be.
  • Scale down large images.
  • Crop out any extra space around the important areas of your image.
  • Avoid large graphics if they are not absolutely necessary.

Section 29.5.1.2: Design with flat color

If you design your graphics with flat color from the beginning, you are basically giving the LZW compression the kind of file it likes—rows of repetitive pixel colors.
  • Fill areas with solid colors rather than gradients (fades from one color to another).
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Designing GIFs with the Web Palette
Inhaltsvorschau
When your GIF is viewed in a browser on an 8-bit monitor, the colors in the image get remapped to the browser's built-in web-safe palette. This often results in unwanted dithering in areas of flat color. You can prevent dithering on 8-bit monitors by designing with colors from the web palette in the first place. It requires a little extra effort and an adjustment to a limited color choice, but the payoff is that you, not the browser, control whether and how the image dithers. Figure 29-11 shows how dithering can be avoided by using a web-safe color in the design.
Remember that the web palette comes into play only on 8-bit monitors. 24-bit and 16-bit monitors do not use palettes and are capable of rendering your colors without dithering (although, there may be some slight color shifting on 16-bit monitors). For general web traffic, a mere 1 to 3% of users view web pages on 8-bit monitors, and those web users are probably used to reduced image quality by nature of the limited color display.
For a general consumer site, sacrificing color choice for 8-bit performance may not be worth it. However, if you know that a significant share of your audience may be using older systems with 8-bit monitors (such as schools), you may want to continue using the web palette in your designs to avoid unwanted dithering in flat color areas.
There are two opportunities to apply the web palette in the image creation process. The first is to choose web-safe colors when designing the image. As an alternative, you can apply the web palette to the image when reducing it to indexed color before saving or exporting a GIF or 8-bit PNG.
Figure 29-11: Designing with the web-safe palette prevents dithering
If you are making graphics from scratch, especially graphics such as logos or simple illustrations that contain areas of flat color, you can use web palette colors right from the start. The major drawback is that with only 216 colors to choose from (a good 30 of which you wouldn't be caught dead using for anything), the selection is extremely limited. The trick is to have the web palette colors loaded into the Swatches palette or in whatever device your graphics program uses for making colors handy. You should be aware, however, that even if you select web colors for fills, any shades of colors created by soft drop shadows or anti-aliased edges between areas of color probably will not be web-safe.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Chapter 30: JPEG Format
Inhaltsvorschau
Developed by and taking its name from the Joint Photographic Experts Group, JPEG is a compression algorithm used by files in the JFIF format, commonly referred to as "JPEG files." JPEGs use either the .jpg or .jpeg suffix. Like any graphics file format in widespread use on the Web, JPEGs are platform-independent.
JPEG files have the following characteristics :
  • They are 24-bit color images.
  • They use JPEG's "lossy" compression scheme.
  • They may be "progressive" (interlaced), displaying in a number of passes on download.
Any image can be saved in JPEG format, but due to its true color capacity and the way JPEG compression works, the format is ideal for photographic and other continuous tone images, such as paintings, watercolor illustrations, and grayscale images with the 256 shades of gray (see Figure 30-1). JPEGs do not support transparency or animation .
JPEGs are notably not good at compressing graphical images with large areas of solid color, such as logos, line art, type, and cartoon-like illustrations. Not only could the image end up blotchy, but the file usually will be quite a bit larger than a GIF file of the same image. JPEG compression is also not good at sharp edges or typography because it tends to leave artifacts that "ripple" the edges.
This chapter begins with further explanations of the JPEG features listed earlier. It also discusses strategies for keeping JPEG file sizes at a minimum.
JPEG images contain 24-bit RGB color information, which means they are composed of colors from the Truecolor space of millions of colors (see Chapter 28 for a description of 24-bit color). JPEG files can also carry grayscale images. 24-bit color allows for higher image quality and richer and more subtle color variations. Unlike GIF files, JPEGs do not use palettes for referencing color information.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
24-Bit Color
Inhaltsvorschau
JPEG images contain 24-bit RGB color information, which means they are composed of colors from the Truecolor space of millions of colors (see Chapter 28 for a description of 24-bit color). JPEG files can also carry grayscale images. 24-bit color allows for higher image quality and richer and more subtle color variations. Unlike GIF files, JPEGs do not use palettes for referencing color information.
Figure 30-1: Examples of images appropriate for JPEG format
Be aware that specific RGB color values may not be maintained after an image is compressed as a JPEG. So although you may fill an area with a color using its numeric RGB values, the way the JPEG compression scheme samples and compresses the image may result in blotchy color or overall color shifting. The effect is lessened at higher image quality levels (using less JPEG compression), but there is still no guarantee a specified color will remain numerically exact. If you need to match a graphic to a specific RGB color (such as the background color of a page), use a GIF with its fixed color table.
The color in a JPEG may also be altered (or more accurately, approximated) when the image is viewed on an 8-bit monitor. On 8-bit monitors, the browser will remap the colors in the JPEG to its built-in web palette. This dithering is generally acceptable in photographic image areas.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
JPEG Compression
Inhaltsvorschau
JPEG uses what is known as a "lossy" compression scheme, meaning that some image information is actually thrown out in the compression process. Fortunately, for photographic images at most compression levels, this loss is not discernible to the human eye, particularly when the image is displayed on a monitor at screen resolution (and even less so for images saved at print resolutions).
Using "lossy" compression algorithms, JPEG is able to achieve 10:1 to 20:1 data-compression ratios without visible loss in quality. Of course, the savings in file size at any given compression depends on the content of the specific image, and results vary. If maintaining high image quality is not a priority, these ratios can go even higher.
The efficiency of JPEG compression is based on the spatial frequency, or concentration of detail, of the image. Image areas with low frequency (smooth gradients, like a blue sky) are compressed much further than areas with higher frequency (lots of detail, like blades of grass). Even a single sharp color boundary, although not giving "lots of detail," represents a surge in spatial frequency and therefore poses problems for JPEG compression.
The compression algorithm samples the image in 8 × 8-pixel squares and then translates the relative color and brightness information into mathematical formulas. These sampling squares may become visible when images are compressed with the highest compression ratios (lowest quality settings).
It is perhaps most meaningful to compare JPEG and GIF compression on photographic images. A detail-rich photographic image that takes up 85K of disk space as a GIF image may require only 35K as a JPEG. Again, the rate of compression depends on the specific image, but in general, a JPEG compresses a photographic image two to three times smaller than GIF. For flat-color graphics, however, GIF is far more efficient than JPEG.
Once image quality is lost in JPEG compression, you can never get it back again. Loss in image quality is also cumulative, meaning you lose a little bit more information each time you decompress and compress an image. Each time you open a JPEG and resave it, you degrade the image further. Not only that, you may introduce new artifacts to the image that prevent the second compression from working as efficiently as the first, resulting in higher file sizes.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Progressive JPEGs
Inhaltsvorschau
Progressive JPEGs are just like ordinary JPEGs except they display in a series of passes (like interlacing in the GIF format). Each pass contains more detailed information, until the whole image is rendered clearly. Graphics programs allow you to specify the number of passes it takes to fill in the final image (3, 4, or 5 scans). Bear in mind that over a fast Internet connection, the image may load and render so quickly the user may not see any passes at all.
The advantage to using Pro-JPEGs is that like interlaced GIFs, they provide some indication of the full image for the reader to look at without having to wait for the entire image to download. Progressive JPEG files are also generally slightly smaller than standard JPEG files.
One disadvantage to Progressive JPEGs is that they require more processing power to display. The higher the specified number of passes, the more power it takes the user's machine to render the image. The other disadvantage is that this feature of JPEG is not supported by Internet Explorer, so it will be lost on the vast majority of your audience.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Creating JPEGs
Inhaltsvorschau
Because JPEG is a standard file format, it is supported by all the popular graphics tools. Adobe Photoshop/ImageReady, JASC Paint Shop Pro, and Macromedia Fireworks all provide similar options for saving JPEGs. All of these products allow you to set the quality/compression level and save images in Progressive JPEG format .
Make sure your file is in RGB or grayscale format. You can apply JPEG compression to CMYK files in some applications, but these files are not compatible with web browsers. Be sure to name your file with the suffix .jpg or .jpeg. This is necessary for the browser to recognize it as a readable JPEG file type.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Minimizing JPEG File Size
Inhaltsvorschau
As for all files intended for web delivery, it is important to optimize JPEGs to make the file size as small as possible. Because JPEGs are always 24-bit by nature, reducing bit-depth is not an option. For the most part, all you have to play with is the Quality setting, but it is possible to prepare an image prior to compression. There are a number of strategies and tools available for making JPEGs as small as they can be while letting you make decisions about image quality.
The most direct way of optimizing a JPEG is to adjust its Quality setting. If your image has a lot of continuous tone or gradient colors, you can be pretty aggressive with the compression level and not worry too much about loss of quality in the resulting JPEG. Even at some of the lowest quality settings, the image quality is still suitable for viewing on web pages. Of course, this depends on the individual image. A low quality setting (for example, below 30 in Photoshop) usually results in a blocky or blotchy image, which may be unacceptable to you.
Each tool provides sliders for controlling quality/compression ratios, although they use different numbering systems. Fireworks uses a percentage value from 1 to 100%. Paint Shop Pro uses a scale from 1 to 100, but it works as the inverse of the standard scale: lower numbers correspond to higher image quality and less compression.
Photoshop uses a scale of 0 to 12 when you select JPEG from the Save As dialog box. When you choose Save for Web in Photoshop or Save Optimized in ImageReady, the quality rating is on a scale from 0 to 100. It should be noted that Photoshop is much less aggressive with its numbering; 0 on the Photoshop scale corresponds to about 30 on the standard scale.
The easiest way to get the balance of compression and image quality just right is to watch the effects of your settings in the image preview available in Photoshop/ImageReady and Fireworks.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Chapter 31: PNG Format
Inhaltsvorschau
The Portable Network Graphic format (PNG for short—pronounced "ping") is a versatile and full-featured graphics file format. Despite some attractive features and the fact that it was created with web use specifically in mind, the PNG has been slow to catch on in the web development world. This is due in part to initial poor browser support and the lack of tools capable of making PNG files as small as they ought to be. But all that is changing, and PNG is poised to live up to its full potential.
PNGs offer an impressive lineup of features:
  • They can store 24- or 48-bit color, 16-bit grayscale, or 8-bit indexed color images.
  • They use a lossless compression scheme that offers better compression than GIF for indexed color images and no cumulative degradation like JPEG.
  • They offer 8- or 16-bit alpha-channel transparency information, which means pixels can have 256 or up to 65,000 shades of transparency. They also offer binary (on/off) transparency like GIFs.
  • They may use progressive display (similar to, yet more sophisticated than GIF interlacing).
  • They may contain gamma adjustment and color correction information.
  • They may contain embedded text for information like author, copyright, and so on.
This chapter introduces these impressive features and provides basic guidelines for creating and optimizing PNG graphics.
PNG is capable of supporting both indexed and Truecolor image types, so there's no bitmapped graphic it can't handle. Virtually all browsers in use today support PNGs as inline images, although they may not support all the bells and whistles, as you'll see in the "Platform/Browser Support" section later in this chapter.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
When to Use PNGs
Inhaltsvorschau
PNG is capable of supporting both indexed and Truecolor image types, so there's no bitmapped graphic it can't handle. Virtually all browsers in use today support PNGs as inline images, although they may not support all the bells and whistles, as you'll see in the "Platform/Browser Support" section later in this chapter.
For web design purposes, there are a few criteria to consider for choosing PNG over another format for an image.
For images with sharp edges and areas of flat color that would typically be saved as GIFs, the 8-bit PNG is a viable option. It can even handle transparency. You may find that a PNG version of an image has a smaller file size than the GIF version of the same image, but that depends on whether your image editing tool handles PNG compression properly and efficiently. Adobe Photoshop/ImageReady and Macromedia Fireworks now do an impressive job of creating PNGs. Using the Preview function in both tools, it's easy to compare the file sizes of each format. If the PNG is smaller, use it with confidence.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
PNG Features
Inhaltsvorschau
PNG is like a superhero of the graphics format world. This section takes a more detailed look at PNG's capabilities.
PNG was designed to replace GIF for online purposes and the inconsistently implemented TIFF format for image storage and printing. As a result, there are three types of PNG files: indexed color (palette images), grayscale , and Truecolor.

Section 31.2.1.1: 8-bit palette images

Like GIFs, PNGs can be saved as 8-bit indexed color, containing up to 256 colors, the maximum number that 8 bits of information can define. Indexed color is discussed in detail in Chapter 29.
Although 8-bit is the maximum, PNGs may be saved at 1-, 2-, and 4-bit depths as well, thus reducing the maximum number of colors in the image (and the file size).

Section 31.2.1.2: Grayscale

PNGs can also support 16-bit grayscale images —that's as many as 65,536 shades of gray (216), enabling black-and-white photographs and illustrations to be stored with enormous subtlety of detail. This is useful for medical imaging and other types of imaging where detail must be maintained, but it is not much of an advantage for images intended for web delivery due to the inherent limitations of low-resolution images. Grayscale images are supported at 1-, 2-, 4-, and 8-bit depths as well.

Section 31.2.1.3: Truecolor

PNG can support 24- and 48-bit Truecolor images. The term "Truecolor" refers to the full color range (millions of colors) that can be defined by combinations of red, green, and blue (RGB) light on a computer monitor (see Chapter 28 for more information). Truecolor images do not use color tables and are limited only by the number of bits available to describe values for each color channel. In PNG format , each channel can be defined by 8- or 16-bit information. It should be noted that 48-bit images are useless for the Web. Even 24-bit should be used with care (JPEG usually offers smaller file sizes with acceptable image quality).
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Platform/Browser Support
Inhaltsvorschau
PNG was designed to be network-friendly, so naturally it is recognized and supported on all platforms. Fortunately, as of this writing, PNGs can be displayed as inline images in virtually all browsers (initially, PNGs required plug-ins such as PNG Live). However, not all of the advanced features, such as progressive display and embedded text, are supported. In fact, Internet Explorer didn't start natively supporting alpha-channel transparency until its Version 7 release.
Table 31-1 lists the more popular browsers capable of displaying PNGs and the features they support. Note that there are myriad lesser-known browsers out there that also support PNG in all its glory. Some older browsers are included in the table for historical interest. For a complete list of PNG behavior on all browsers, see the browser support page on the official PNG web site at www.libpng.org/pub/png/pngapbr.html.
Table 31-1: Browser support for PNG
Browser
Progressive display
Binary transparency
Alpha channel transparency
Gamma correction
Windows
IE 7 (beta)
Yes
Yes
Yes
Yes
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Creating PNG Files
Inhaltsvorschau
While browser support played a part in PNG's slow adoption, the other side of the coin was the lack of image tools that could do the PNG format justice. For a while, decent PNGs could be created only with fairly obscure command-line utilities (see the sidebar "For PNG Geeks Only"). Fortunately, decent (albeit often incomplete) PNG support is now available in most professional graphics programs. This section outlines the ins and outs of creating PNGs in the two most popular professional web graphics tools, Photoshop/ImageReady and Fireworks.
For a comprehensive list of image editing tools and graphics file converters that support PNG compression (as well as their known bugs), see the official PNG site at www.libpng.org/pub/png/pngaped.html.
Adobe Photoshop introduced read/write PNG support in Version 4, but due to poor support for the PNG compression engine, the resulting PNG file sizes couldn't compete with their GIF counterparts, thus knocking PNGs temporarily out of the race. Compression support has since improved, and the later versions of Photoshop (CS2 is the latest as of this writing) are able to squeeze an 8-bit image smaller in PNG format than GIF at the same settings.

Section 31.4.1.1: Saving as PNG

To save an image as a PNG in Photoshop, simply select PNG-8 or PNG-24 from the file format pop-up menu in the Save for Web dialog box. In ImageReady, select PNG-8 or PNG-24 in the Optimize panel. Creating a PNG-8 is essentially the same as making a GIF, and the same optimization tools and guidelines apply. 24-bit PNGs may be interlaced or contain transparency, but there are no settings for optimization.

Section 31.4.1.2: PNG transparency in Photoshop/ImageReady

Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
PNG Optimization Strategies
Inhaltsvorschau
The following are a few strategies for keeping PNG file sizes small and for using PNGs wisely.
Figure 31-3: PNG transparency options in Fireworks
Use 8-bit (or smaller) PNGs.
Index color PNGs are always smaller than their 24-bit RGB counterparts.
Use JPEGs instead of RGB (24-bit) PNGs.
Photographic images are best saved in JPEG format for use online. The resulting file sizes are smaller (with only minimal image quality loss) and more appropriate for web delivery.
Use GIF optimization techniques.
8-bit PNGs benefit from all the same tactics used to minimize GIFs, including limiting dithering and reducing the number of colors and bit depth. See Chapter 29 for more information on optimization methods.
Avoid interlacing.
Interlacing always adds to the size of a PNG. It is usually unnecessary anyway for small graphics or any graphic accessed via a high-bandwidth connection or locally (as from disk or CD-ROM).
Use maximum compression (if available) for final images.
If your image tool offers control over compression, use level 9 (or "max" or "slowest") for the final version of your image. Use lower compression (3 or 6) for intermediate saves. Most commercial programs (such as Fireworks and Photoshop) handle compression and filter application internally, so you may not have control over specific levels.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
For Further Reading
Inhaltsvorschau
If you are interested in learning more about the PNG format, definitely check out PNG: The Definitive Guide by Greg Roelofs (O'Reilly). There are also a few good resources available online:
PNG home page (www.libpng.org/pub/png/)
This site is written and maintained by Greg Roelofs. It contains a complete history of PNG's birth, descriptions of its features, and up-to-date lists of applications that support the new format. It also includes a copy of the PNG Specification and the official PNG extensions documents (as well as the draft MNG Spec). It is written with so much enthusiasm that you can't help but become a PNG fan.
PNG Specification (www.w3.org/TR/png.html)
This is the complete PNG specification (Version 1.0) as published by the W3C. For a technical document, it is very user-friendly to nonprogrammers and offers detailed information on how PNGs work, as well as some useful background information and tutorials. The updated Version 1.2 of the specification is available at the PNG web site at www.libpng.org/pub/png/spec/.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Chapter 32: Animated GIFs
Inhaltsvorschau
It's just about impossible to browse the Web without seeing the flashing, bouncing, and wiggling of GIF animation. The animated GIF is ubiquitous, and there are many reasons for its popularity.
Users need no special software or plug-in.
All they need is a browser that supports GIF animation, which is true of nearly all graphical browsers available today.
GIF is the standard file format for the Web.
Animated GIFs are not a unique file format in themselves, but merely take advantage of the full capabilities of the original GIF89a specification. Even if a browser cannot display all of its frames, the GIF will still be visible as a static image.
They're easy to create.
There are scores of GIF animation tools available (some are built into larger web graphics applications), and they're simple to learn and use.
They require no server configuration.
Because they are standard GIF files, you do not need to define a new file type on the server.
They use streaming technology.
Users don't need to wait for the entire file to download to see something. Each frame displays as soon as it downloads.
The only drawback to animated GIFs is that they may cause some extra work for the user's hard disk to keep refreshing the images. And they can be annoying, but more on that later.
Animated GIFs work a lot like traditional cell animation. The file contains a number of frames layered on top of each other. In simple animations, each frame is a complete scene. In more sophisticated animations, the first frame provides the background and subsequent frames just provide the changing portion of the image.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
How They Work
Inhaltsvorschau
Animated GIFs work a lot like traditional cell animation. The file contains a number of frames layered on top of each other. In simple animations, each frame is a complete scene. In more sophisticated animations, the first frame provides the background and subsequent frames just provide the changing portion of the image.
A GIF animation file consists of a number of images and a set of instructions that specify the length of delay between frames, as well as other attributes like transparency and palettes.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Using Animated GIFs
Inhaltsvorschau
Nowhere has GIF animation made a larger impact than in banner advertising. Ad agencies aren't stupid; they know that adding motion and flashing lights to a web page is a sure-fire way to attract attention. And it's true—adding animation is a powerful way to catch a reader's eye.
But beware that this can also work against you. Many users complain that animation is too distracting, making it difficult to concentrate on the content of the page. Although it adds a little "pizzazz" to the page, overall, too much animation can quickly spoil the user's enjoyment of your page.
Use animated GIFs wisely. A few recommendations:
  • Avoid more than one animation on a page.
  • Use the animation to communicate something in a clever way (not just as gratuitous flashing lights).
  • Avoid animation on text-heavy pages that might require concentration to read.
  • Consider whether the extra bandwidth to make a graphic "spin" is actually adding value to your page.
  • Decide whether your animation needs to loop continuously.
  • Experiment with timing. Sometimes a long pause between loops can make an animation less distracting.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Tools
Inhaltsvorschau
You don't need to search very far to find a GIF animation tool—there seem to be scores of them available. Regardless of the tool you choose, the interface is basically the same. Tools tend to differ somewhat in the degree to which they are able to optimize (shrink the file size of) the resulting graphic. The following sections provide an overview of the most popular and/or recommended tools.
GIF animation tools are built in or bundled with many popular graphics applications, eliminating the need to jump between different software packages.
Adobe ImageReady (Mac and Windows)
Adobe ImageReady is a tool (bundled with Photoshop 5.5 and higher) especially for preparing and optimizing web graphics. It includes a GIF animation tool that converts layers into frames and allows easy layer editing. ImageReady offers advanced optimization methods for making the smallest possible animations. For more information, see Adobe's site at www.adobe.com.
Macromedia Fireworks (Mac and Windows)
Macromedia Fireworks was designed specifically for the creation of web graphics. It supports multiple layers that can be converted to multiple animation frames. Among other features are automatic super-palette optimization and the ability to perform LZW optimization. For more information, see Macromedia's site at www.macromedia.com/software/fireworks/. As of this writing, Fireworks' fate is unknown, as Macromedia has been acquired by Adobe.
Animation Shop (Windows only)
Animation Shop is a tool that complements Paint Shop Pro, an inexpensive and powerful graphics creation application from Corel (it was originally developed by JASC Software, Inc.). For more information, see Corel's web site at
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Creating Animated GIFs
Inhaltsvorschau
Regardless of the tool you choose, the process of creating an animated GIF is about the same and involves making decisions about a standard set of features and options. The exact terminology may vary from tool to tool, but the concepts and settings are consistent.
Also called "interframe delay ," this setting specifies the amount of time between frames. Frame delays are measured in 1/100ths of a second. You can apply a different delay time to each frame in the animation to create pauses and other timing effects. This differs from digital video formats, in which the delay between all frames is consistent.
You can set transparency for each frame within an animation. Previous frames will show through the transparent area of a later frame if disposal methods are set correctly.
If the background frame is made transparent, the browser background color or pattern will show through.
Don't be surprised if the transparent areas you specified in your original graphics are ignored when you import them into a GIF animation utility. You may need to set transparency in the animation package. Some standard transparency options include:
None
No transparency.
White
All the white pixels in the image will become transparent.
Based on first pixel
The color of the "first pixel"—that is, the top-left pixel, the one at coordinates 0,0—is transparent. This is a handy option, because you'll often have an image in the center, and the four corners will be transparent.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Optimizing Animated GIFs
Inhaltsvorschau
As with any file served over the Web, it is important to keep animated GIFs as small as possible. I highly recommend reading "Optimizing Animated GIFs," an article and tutorial by Andrew King in WebReference.com, from which many of the following tips were summarized (with permission). You can find it at www.webreference.com/dev/gifanim/index.html. It is a little dated, but it is still an excellent starting point for understanding how GIF animations work and the tools available for optimizing them.
Start by applying the same file size-reduction tactics used on regular, static GIF files to the images in your animation frames. For more information, see "Minimizing GIF File Sizes" in Chapter 29. These measures include:
  • Reducing the number of colors/bit depth.
  • Eliminating unnecessary dithering.
  • Applying the "loss" feature available in Adobe ImageReady and Macromedia Fireworks. ImageReady allows you to do weighted optimization where loss can be applied more aggressively to selected areas of the image. If your tool does not include a loss function, you can manually remove stray pixels from otherwise solid areas.
In addition to the standard image-compressing methods, GIF animation tools optimize animations by eliminating the repetition of pixels in unchanging image areas. Only the pixels that change are recorded for each frame. Different tools use different optimizing methods, which are not equally efficient. These methods, in order from least to most compression, include:
Bounding box (also called "minimum bounding rectangle")
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Chapter 33: Audio on the Web
Inhaltsvorschau
Simple audio files found their way onto the Web in its earliest days when they could be linked to and downloaded like any other file. The drawback to this technique is that traditional audio files are generally quite large and may take a prohibitively long time to download. As the Web evolved, some major breakthroughs have been made in web audio. First, streaming audio (files that play as they download) made long-playing audio and even live broadcasts possible. Then the MP3 format exploded into popularity around 1999. MP3's ability to crunch audio files to one-tenth their original size while maintaining very good quality made it a perfect solution for sharing music over the Internet.
Obviously, audio, even specialized for the Web, is a rich and complex topic that cannot be thoroughly treated in a single chapter of a Nutshell reference book. This chapter introduces general audio concepts and a number of popular web audio file formats, including MP3, QuickTime, RealAudio, Windows Media, Flash audio, MIDI, and AAC. It also discusses the many options for adding audio to a web site. It begins with an introduction to basic audio terminology that will be useful to know when it comes time to create and optimize sound files.
To distribute recorded speech or music over the Internet, an analog signal must be converted to digital information (described by bits and bytes). This process is called encoding . It is analogous to scanning a photograph to a digital bitmap format, and many of the same concepts regarding quality and file size apply. Some audio file formats (such as MPEG) are compressed in size during encoding using a specialized audio compression algorithm to save disk space. In the encoding process, you may be asked to provide settings for the following aspects of the audio file.
Sampling rate
To convert an analog sound wave into a digital description of that wave, samples of the wave are taken at timed intervals (see Figure 33-1). The number of samples taken per second is called the
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Basic Digital Audio Concepts
Inhaltsvorschau
To distribute recorded speech or music over the Internet, an analog signal must be converted to digital information (described by bits and bytes). This process is called encoding . It is analogous to scanning a photograph to a digital bitmap format, and many of the same concepts regarding quality and file size apply. Some audio file formats (such as MPEG) are compressed in size during encoding using a specialized audio compression algorithm to save disk space. In the encoding process, you may be asked to provide settings for the following aspects of the audio file.
Sampling rate
To convert an analog sound wave into a digital description of that wave, samples of the wave are taken at timed intervals (see Figure 33-1). The number of samples taken per second is called the sampling rate. The more samples taken per second, the more accurately the digital description can recreate the original shape of the sound wave, and therefore the better the quality of the digital audio. In this respect, sampling rate is similar to image resolution for digital images.
Sample rates are typically measured in kilohertz (kHz). On the high end, CD-quality audio has a sampling rate of 44.1 kHz (or 44,100 samples per second). On the low end, 8 kHz produces a grainy sound quality that is equivalent to a transistor radio. Standard sampling rates include 8 kHz, 11.025 kHz, 11.127 kHz, 22.05 kHz, 44.1 kHz, and 48 kHz. The high-end standard is 96K, which may be seen in DVD audio but is not applicable to the Web. The higher the sampling rate, the more information is contained in the file, and therefore the larger the file size.
Figure 33-1: Audio wave after lowering sample rate and bit depth
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Using Existing Audio
Inhaltsvorschau
The simplest way to add audio to a site is to use found music, sound effects, or other resources. But before you start featuring music and sound effects from your personal CD collection, it is important to be aware of copyright issues.
With few exceptions, it is illegal to reproduce, distribute, or broadcast a sound recording without the permission of the copyright owner. Copyright issues have been brought to the forefront with the growing popularity of MP3 distribution through peer-to-peer networks, but they apply to all audio published on the Internet. To get permission, you usually need to pay licensing fees.
Be aware that simply posting somebody else's music or recordings from a CD without her expressed written permission is a copyright violation. Record companies, entertainment corporations, and the RIAA (Recording Industry Association of America) are taking measures to crack down on the illegal use of copyrighted material. So be smart and be sure that you have the rights to the sound you use on your site.
Fortunately, collections of prerecorded sound effects and music are available for multimedia and Internet use. Many are royalty-free, meaning once you've purchased the package of sounds, you can use them however you wish and pay no licensing fees. Search Google for "royalty-free audio" for a list of vendors.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Preparing Your Own Audio
Inhaltsvorschau
Recording and producing your own audio can require a significant investment in hardware, software, and time spent learning. If you need to put professional-quality audio on your site but aren't likely to make the investment in time and equipment yourself, consider outsourcing the work to professionals.
The final product may be anything from a simple personal greeting to a live concert broadcast. The preparation of original audio requires a number of standard steps: recording , basic sound editing, and then optimization for web delivery.
The first step is to make a recording of the music, spoken word, or sound effects for your site. As for most things, when it comes to sound quality, you get what you pay for. It is possible to capture sound using available resources (such as the microphone that came with your computer), but the quality will not be appropriate for a professional site. The cost of recording equipment escalates quickly for each level of sound quality. An investment of $800 to $4,000 in equipment (not counting the computer) is enough to get started on creating a home or small business studio. Getting a studio up and running also requires investments of time, effort, and education.
Although this may be a good choice for a business, it may be too expensive for many hobbyists and garage bands. It may be more cost-effective for an individual or organization on a strict budget or tight deadline to hire the services of a professional studio. Depending on how well the studio is equipped, it can cost from $30 to $250 per hour, and up.
Once you've recorded raw audio, the next step is to clean up the recording. This can involve removing unwanted sounds, setting the beginning and end of the file, and/or making a loop. You may want to apply effects to the sound, such as reverb or a delay.
Consider also using mastering processing techniques such as normalization or compression that can balance out the level of your audio such that no part is too loud or too quiet.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Streaming Audio
Inhaltsvorschau
Once upon a time, the only way to play audio from a web page was to link to it and wait for it to download to the hard drive so it could be played. With this method, once the file finishes downloading, the browser either launches an external player or uses a plug-in (or ActiveX control in Internet Explorer on Windows) to play the audio. The most common players are QuickTime, Windows Media Player, and RealPlayer , all of which are available on Mac and Windows.
Downloaded audio has a few distinct disadvantages. First, because the file needs to download to the hard disk in its entirety before it can begin playing, users may be faced with a very long wait before they hear any sound. In addition, because the audio file is copied to the hard drive, it is more difficult for artists and publishers to limit distribution and protect copyrights.
Although it is still possible and common to deliver static audio files in this manner, it is far more effective to use one of several streaming media technologies. Streaming media (be it audio or video) begins playing almost immediately after the request is made and continues playing as the audio data is being transferred. Streaming audio technology was developed to address the problem of unacceptable download times. It can even be used to broadcast live programs, such as concerts or baseball games.
The advantages to streaming audio are:
  • Audio begins playing soon after the stream begins.
  • Using new technologies and formats, sound quality doesn't need to be as severely sacrificed.
  • Artists and publishers can better control distribution and protect copyright because the user never gets a copy of the audio file.
Consider also these disadvantages:
  • The potentially high cost of server software may be prohibitive.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Audio Formats
Inhaltsvorschau
At last, we get to the heart of web audio—the various file formats . This section provides an introduction to some of the most common formats for web audio.
The WAV and AIFF audio formats are very similar in performance and these days are probably ill suited for most web audio. However, these formats remain the standard for high-quality uncompressed audio before it gets converted for use on the Web. The Waveform Audio File Format (.wav) was originally developed as the standard audio format for the Microsoft Windows operating system, but it is now supported on the Macintosh as well. WAV files can support arbitrary sampling rates and bit depths, although 8 kHz and 11.025 kHz at 8 or 16 bits are most common for Web use.
The Audio Interchange File Format (.aif or .aiff) was developed as the standard audio format for the Macintosh platform, but it is now supported by Windows and other platforms. It can support up to six channels and arbitrary sampling rates and bit depths, with 8 kHz and 11.127 kHz at 8 and 16 bits being the most common online.
WAV and AIFF files are less commonly used on the Web than they once were, now that we have audio formats that are better suited for web delivery (MP3) or designed specifically for the Web (streaming formats). They sound good when uncompressed, but they suffer drastic loss of quality when compressed to small file sizes. For this reason they are useful for very short, downloadable audio clips, such as short greetings. They are usually added to web pages via a link for download.
The following summarizes the WAV and AIFF formats:
Good for...
Storing high-quality source audio before converting to web formats, delivering short clips where pristine sound quality is not important, reaching the lowest common denominator (because everyone can play them).
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Choosing an Audio Format
Inhaltsvorschau
Which audio format or system you choose depends on your communication goals, the scale of your site, and your budget. Table 33-1 provides suggestions for some common scenarios. Consider them only as starting points for researching the solution that best meets your needs.
Table 33-1: Suggested audio formats
Audio needs
Suggested formats
Short voice greetings
QuickTime (via regular HTTP server), MP3, AAC
Narration (news broadcasts, interviews, and other voice-only content)
Streaming solutions such as RealAudio, Windows Media, or QuickTime for large audiences; RealAudio or QuickTime via HTTP server for limited traffic and few simultaneous listeners
Background music (ambient sound loops)
MIDI, WAV
Short interactive sound effects (such as button rollover and transition sounds)
Flash
Music samples for a limited audience
MP3, AAC, RealMedia, or QuickTime via HTTP server
Music samples for a large-scale site with heavy traffic
Complete streaming solution, such as Real Helix or Windows Streaming Media
Radio-style music broadcasting
Real Helix, streaming MP3s (via a streaming server such as SHOUTcast), Windows Media System
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Adding Audio to a Web Page
Inhaltsvorschau
There are a number of ways to add audio to a web page. This section covers the most common techniques.
You can link to an audio file from a web page using a simple anchor (a) element, as follows:

    <a href="audio/song.mp3">Play the song (3.5 MB)</a>

    <a href="groovy.mp3"><img src="buttons/playme.gif"></a>

When the reader clicks on the linked text or image, the browser retrieves the audio file from the server and launches a helper application (or plug-in, if the browser is so configured) to play the file. Files accessed in this manner are typically downloaded to the user's hard drive (stored in cache).
If the browser uses an external player, a new small window from the helper application opens with the controls for playing the audio. If the browser is configured to use a plug-in player (such as the popular QuickTime plug-in), a control panel may load right in the browser window, replacing the original web page.
It is good web etiquette to warn readers of the size of an audio file so they can make an informed decision as to whether they want to spend the time downloading the file.
Although it is possible to embed an audio file on a web page so that it starts playing automatically when the page loads, this technique is not recommended. The problem with background sounds is that users have no way of turning the sound off if they do not like it. Also, if the audio file is large, you are forcing a potentially lengthy download on the user. Furthermore, background music on a web page is almost always unnecessary.
If you do need to add a background sound to a page, you can do it with this nonstandard markup. Be aware that this element will cause your document not to validate.

    <embed src="audio/song.mid" autostart="true" hidden="true"></embed>

Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Chapter 34: Video on the Web
Inhaltsvorschau
Like audio, video clips were linked to web pages in the Web's earliest days. Delivering video via the Web is especially problematic because video files require huge amounts of data to describe the video and audio components, making for extremely large files.
Many of the same technologies that have improved the experience of receiving audio over the Web have been applied to video as well. As with audio, you have the option of simply linking a video to your web page for download and playback, or you can choose from a number of streaming solutions. Streaming means the file begins playing almost immediately after the request is made and continues playing as the data is transferred; however, the file is never downloaded to the user's machine. For a more complete description of streaming versus nonstreaming media, see Chapter 33.
Many of the principles for developing and delivering video content for the Web are the same as those for audio. In fact, some of the file formats are the same as well. This chapter introduces you to basic video technology and concepts, including the video file formats QuickTime, Windows Media, RealMedia, AVI, and MPEG. If you are interested in learning how to produce video files for the Web, the books listed at the end of this chapter are a good start.
The following is a list of aspects of digital video that can be manipulated with standard video-editing software. It is important to be familiar with these terms so you can create video optimized for web delivery.
Movie length
It's a simple principle: limiting the length of your video clip limits its file size. Videos longer than a minute or two may cause prohibitively long download times. If you must serve longer videos, consider one of the streaming video solutions.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Basic Digital Video Concepts
Inhaltsvorschau
The following is a list of aspects of digital video that can be manipulated with standard video-editing software. It is important to be familiar with these terms so you can create video optimized for web delivery.
Movie length
It's a simple principle: limiting the length of your video clip limits its file size. Videos longer than a minute or two may cause prohibitively long download times. If you must serve longer videos, consider one of the streaming video solutions.
Frame size
Obviously, the size of the frame has an impact on the size of the file. "Full-screen" video is 640 × 480 pixels. The amount of data required to deliver an image of that size would be prohibitive for most web applications. The most common frame size for web video is 320 × 240 pixels. Some producers go as small as 160 × 120 pixels.
Frame rate
The frame rate is measured in number of frames per second (fps) . Standard TV-quality video uses a frame rate of approximately 30 frames per second to create the effect of smooth movement. For the Web, a frame rate of 15 or even 10 fps is more appropriate and still capable of producing fairly smooth video playback. For "talking head" and other low-motion subjects, even lower frame rates may be satisfactory. Commercial Internet broadcasts are routinely done as low as 0.5, 0.25, or even 0.05 frames per second (resulting in a slideshow effect rather than moving video).
Quality
Many video-editing applications allow you to set the overall quality of the video image. The degree to which the compression algorithms crunch and discard data is determined by the target quality setting. A setting of Low or Medium results in fairly high compression and is appropriate for web delivery. Frame rate, frame size, and quality are often traded off in different degrees in relation to each other, depending on the application, to reduce bandwidth requirements.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Compression
Inhaltsvorschau
Digital video wouldn't be possible without methods for compressing the vast amounts of data necessary to describe sound and frame images. Video files can be compressed in a number of ways. This section looks at a variety of compression schemes and introduces the methods they use for achieving compression rates. Understanding your options can help you make better decisions for optimizing your video files.
Compression can be lossless, which means no information is lost and the final file is identical to the original.
Most compression schemes use forms of lossy compression. Lossy compression sacrifices some data from the file to achieve much higher compression rates. Lossy compression schemes, such as MPEG, use complicated algorithms that toss out data for sound and image detail that is not discernible to the human ear or eye. The decompressed file is extremely similar in character to the original, yet is not identical. This is similar to the way JPEG handles still images.
Spatial (or intraframe) compression takes place on each individual frame of the video, compressing the pixel information as though it were a still image.
Temporal (or interframe) compression happens over a series of frames and takes advantage of areas of the image that remain unchanged from frame to frame, throwing out data for repeated pixels.
Temporal compression relies on the placement of key frames interspersed throughout the frames sequence. The key frames are used as masters against which the following frames (called delta frames) are compared. It is recommended that a key frame be placed once every 3 to 10 seconds. Videos without a lot of motion, such as talking head clips, take the best advantage of temporal compression . Videos with pans and other motion are compressed less efficiently.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Video File Formats
Inhaltsvorschau
As with audio, in the early days of the Web, adding video to a web page meant using one of the currently available video formats (such as QuickTime or AVI) and linking it to a page for download. The evolution of streaming media has changed that, and now adding video content like movie trailers, news broadcasts, even live programming to a web site is much more practical and widespread.
This section looks at the video formats that are most common for web delivery.
Windows Media is a new standard for audio and video, created by Microsoft and therefore very closely integrated with the Windows OS. The Windows Media Player is capable of playing Microsoft's proprietary Windows Media Video (.wmv) and Advanced Streaming Format (.asf), as well as a number of other formats such as AVI, MPEG, MP3, and QuickTime.
Windows Media movies are encoded using the proprietary Windows Media Video codec designed especially for the Windows Media system. They may also feature DRM (digital rights management) capabilities.
In addition to the player, the Windows Media 9 Series platform includes Windows Media Encoder, Windows Media Rights Manager 9 Series SDK, Windows Media Services, and a collection of audio and video codecs.
For more general information about Window Media, visit Microsoft's site at www.microsoft.com/windows/windowsmedia/. Resources related specifically to codecs (video and audio) are available at www.microsoft.com/windows/windowsmedia/mp10/codecs.aspx. If you want to create and stream Windows media, the book Microsoft Windows Media Resource Kit, by Tricia Gill, Bill Birney, and the Microsoft Windows Media Team (Microsoft Press) offers a comprehensive overview.
The following summarizes the Windows Media format:
Good for...
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Adding Video to an HTML Document
Inhaltsvorschau
This section looks at the ways video files can be linked to or embedded within an HTML document.
Like audio, downloadable video files (AVI, MPEG, Windows Media, and QuickTime) can be linked to HTML documents using the standard anchor (a) element:

    <a href="video.mov">Check out the video (1.3MB)</a>

When the user clicks on the link, the browser looks at the file type (as defined in the filename suffix) and launches an external player application or uses a plug-in to play the movie right in the browser window. Which player it uses depends on the file format and how that user has the browser configured, so it is out of the control of the web page designer.
When linking to media, it is good form to provide an indication of the file size so users with slower connections can make the decision whether to click.
As in audio, streaming media in the RealMedia (.rm) and streaming Windows Media (.asf) formats are added to web pages via linked or embedded reference files (also called metafiles). The process, covered in detail at the end of Chapter 33, is exactly the same for video as for audio.

Section 34.4.2.1: Windows Media

To link to a Windows Media Video file for download and playback, create a link directly to the video file:

    <a href="movie.wmv">See the movie</a>

To link to a streaming Windows Media file for unicasting (a single stream triggered by a user request), make a link to an active stream redirector file (.asx).

    <a href="streamingmovie.asx">See a streaming movie</a>

The content of the .asx file is the location (URL) of the actual movie and looks like this:

    <ASX version="3">

       <Entry>

          <ref href="path/streamingmovie.asf" />

       </Entry>

    </ASX>

Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Chapter 35: The Flash Platform
Inhaltsvorschau
by Todd Marks
Flash has come a long way since its infancy as FutureSplash in the late 1990s. "Flash" started as means of adding animation and interaction to a web page, but has since evolved into a robust platform. Flash has seen significant improvements in not only its content delivery capabilities, including the addition of video and an object-oriented programming language, but also in its ability to allow for live communications and Rich Internet Applications (RIA) development. At the core of these features is the real hero of it all, the Flash Player .
The Flash Player allowed Flash to take off on the Web due to its small plug-in size and use of vector graphics and reusable shapes . Vector graphics were a big improvement over traditional raster graphics, because they were typically much smaller in file size and allowed users to animate graphics easier. The Flash Player's and Flash files' biggest contribution, however, was that they brought reusable graphical shapes to the Web. Flash allows graphics, buttons, and code objects to be duplicated over and over in a Flash file, but without adding additional file size to the page. This shift allowed designers and developers to start creating worlds to explore over the Web, during the pre-broadband era.
The name "Flash" traditionally has referred to the Macromedia Flash authoring environment , which produces .swf files, and the Macromedia Flash Player, which plays those files on the Web. Now, the name "Flash" refers to a platform, with the Flash Player at the center and several applications leveraging the power of that player.
The Flash authoring environment is still the primary application that uses the Flash Player. Flash includes tools for illustration, animation, interaction sequencing, sound editing, video, and working with its procedural language, ActionScript. Macromedia Flash 8, the latest version as of this writing, offers an improved interface, new templates for handheld and mobile devices, a new video codec and encoder, as well as several new "components," which are packaged as customizable code objects that can be used to add robust functionality to a web page or application. These features make Flash one of the most versatile and powerful formats for web multimedia.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Using Flash on Web Pages
Inhaltsvorschau
Flash movies can be placed on a web page, or they can be used as a web page. Moreover, with the advanced scripting present since Flash 5, and the inclusion of server-side applications such as Flash Media Server 2, Breeze, and Flex, the uses for Flash movies are limited only by imagination. Some possibilities include:
  • Art and motion graphics
  • Animation and cartooning
  • Splash pages, intros, and ad banners
  • Interaction and navigation
  • Multimedia web sites
  • Video and audio players
  • E-commerce
  • Rich media applications
  • Data and statistical applications
  • Web-based training
  • Distance learning
  • Live communication
While Flash introduces a number of significant improvements over what can be accomplished using just HTML and scripting in the browser, there are a few drawbacks to using Flash as well. Let's look at the pros and cons of using Flash on a site.
Many aspects of the Flash file format make it ideal for adding interactive content to web pages:
File sizes are small.
Flash allows for reusable graphics, buttons, and code objects without adding additional bytes for every instance used. Flash movies also use vector graphics, which rely on math to designate lines and color as opposed to storing the colors of individual pixels, such as with raster graphics. This saves a lot of file size.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Creating Flash Movies
Inhaltsvorschau
Although it is beyond the scope of this book to teach the myriad information about Flash authoring, this section will give you a high-level overview of creating Flash movies, by reviewing file formats, interface basics, optimization, server configuration, action scripting, and adding Flash movies to a web page. Full-featured Flash movies are best created using Macromedia's Flash software, but I will also show you several third-party software products that allow you to create specific types of .swf files and still use the Flash player. For a more hands-on look at creating movies, I recommend using the tutorials that come with the software as well as support documents provided by Macromedia (www.macromedia.com/support/flash/). For an incredibly thorough book of tutorials and reference material, check out Flash 8 Bible by Robert Reinhardt and Snow Dowd (Visual).
The Flash authoring tool saves information about a movie in a .fla source file (also called a "Flash document" or "Flash editor document"). The .fla file contains all the separate elements that make up the movie and its timeline information in a fully editable format.
When the movie is ready to go on the Web, it must be exported to .swf format. The suffix originally stood for Shockwave Flash, but in the face of confusion with Macromedia's Shockwave for Director format, the meaning is more accurately understood as simply a compiled Flash application.
To better understand the way Flash handles multimedia content, it is useful to be generally acquainted with the Flash authoring environment. Figure 35-1 shows the core features of the Flash interface as seen on Windows XP.
Figure 35-1: The Flash interface
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
ActionScript
Inhaltsvorschau
Flash uses the robust ActionScript scripting language for adding behaviors and advanced interactivity to Flash movies . ActionScript is an object-oriented language based on a version of ECMAScript (the ECMA-262 Edition 4 spec, for those who need to know), so although it shares characteristics with the JavaScript we know and love, the two are not 100% compatible.
ActionScript, which was introduced in Flash 4, evolved into a much more powerful and useful tool in Flash 5, and later again with ActionScript 2.0 in Flash MX 2004 and Flash 8 to adhere more closely to ECMAScript standards. Not only is it responsible for controlling basic playback and user-triggered behaviors, it also enables Flash to integrate with JavaScript, XML, web services, and other server technology. If you are set on becoming a Flash power-user, you will definitely want to learn ActionScript 2.0. For a robust overview of ActionScript, check out Macromedia's learning guides, www.macromedia.com/devnet/flash/actionscript/actionscript.html. The following gives a quick overview of their different features.
ActionScript started out with simple commands to control the Timeline, such as play and stop. Additionally you could control the Timelines of objects within the Flash environment, called Movie Clips, as well as control their x and y placement, and width and height. You could also set and return variables, use loops, and communicate with databases using PHP, ASP, ColdFusion, and so on, and that was about all that was required to make Flash explode. Developers were soon adding code to create spinning DNA helixes, complex animations, games, and web applications such as shopping carts and multimedia galleries.
ActionScript 1.0, with the release of Flash MX, evolved to include several more objects and available methods, and would allow for object oriented programming, but it was limited with regards to its implementation of classes. It wasn't long after, however, that ActionScript 2.0 was released with the next version of Flash, Flash MX 2004, although ActionScript 1.0 remained to provide easy scripting for nonprogrammers. Flash 8 once again includes a Script Assistant to help nonprogrammers with object scripting, which was in previous versions of Flash, but omitted with the last version, Flash MX 2004.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Adding Flash to a Web Page
Inhaltsvorschau
Flash movies are exported by the Flash authoring environment using a combination of the object and embed elements with parameters and attributes for controlling display and playback. Both elements are used in order to accommodate the incompatibilities of the various web browsers while still providing as many player attribute settings as possible.
Internet Explorer on Windows uses the object element, which also enables it to automatically download the ActiveX controls for playing Flash media. Netscape on PC and Mac, and Internet Explorer and Safari on Mac, do not support ActiveX, so they use embedding information provided by the embed element. Note, the embed element is not standards-compliant and doubles much, if not all, of the information found in the object element.
You can generate the HTML using Flash's Publish feature, write it out by hand, or add a Flash element to a page using a What You See Is What You Get (WYSIWYG) editor such as Macromedia Dreamweaver MX 2004. The following sections take a look at the first two methods.
The easiest way to get your SWF files on the Web is to let the Flash authoring tool do the work for you. Flash 4 introduced the Publish feature for exporting movies along with automatically generated HTML for placing the Flash (.swf) file in an HTML document.
The Publish Settings dialog box also allows you to select the export format of the movie (whether it's to be a Flash movie, Standalone Projector, static graphic format, and so on) and control the variables of the export. For now, I'll focus on the HTML settings that are relevant to placing an SWF movie on a page.
The most welcomed feature of the HTML Publish Settings is the collection of preformatted templates that generate object and embed elements tailored to specific uses. The Flash Only (Default) template generates bare minimum code. Other templates generate HTML code with extra functionality, including:
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Integrating Flash with Other Technologies
Inhaltsvorschau
Flash has proven to be such a popular multimedia format for the Web that it can now be integrated with the other web media staples such as QuickTime and RealMedia. Additionally, Flash files can be used within both Macromedia Director and Macromedia Dreamweaver.
QuickTime is a multitrack container format. Traditionally, this meant tracks for audio and video. In the evolution of QuickTime, support has been added for other tracks such as text, timecode, and (starting with QuickTime 4) Flash content.
To add a Flash track to a QuickTime movie, use the Flash authoring tool and export the file to the QuickTime format (.mov). The resulting file is a QuickTime movie that can simultaneously play video, audio, and Flash media elements.
The QuickTime 4 Player or higher is required to view QuickTime Flash. QuickTime 5 supports most of the functions of Flash 4. QuickTime 6 supports ActionScript and most Flash 5 player features.
As an alternative to using the Flash authoring tool, you can also import an existing .swf file into QuickTime Player (or Player Pro) and save it as a QuickTime movie. Plus, as mentioned in the "Advantages" section previously, you can import and trim QuickTime movies in the Flash 8 Professional authoring environment and output them as FLV files using the new On2 VP6 codec.
Macromedia Director is capable of importing Flash files into its Cast and having those Flash elements play in its Timeline. When including Flash elements in Director, the Flash Assets Xtra plug-in is automatically included in the list of dependent plug-ins added to the movie.
Although there is a Shockwave Player for Director movies published for the Web, Director has increasingly become a product for developing interactive and robust CD-ROM presentations. For more information about Flash and Director, see Macromedia's web site:
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
The Flash Player
Inhaltsvorschau
Several applications now leverage the Flash Player, such as Macromedia Flash Media Server 2 for real-time audio and video communications, Macromedia Breeze for web conferencing and distance learning , Macromedia Captivate for software simulation creation, the Macromedia Flex Builder and Macromedia Zorn for web application development, as well as several third-party applications, such as Swift 3D (Electric Rain) and 3ds Max (Autodesk) for three-dimensional art, and Swish and Wildform for producing text effects and animations at a lower price point than Flash 8.
The Flash Player, in addition, has now completely broken away from its roots as a web browser plug-in with several flavors to choose from. The Stand-Alone Flash Player has recently taken a big step with Macromedia Central harnessing it to combine the power of the Web with desktop applications.
The Flash Player has also crossed over well into the world of handheld and mobile devices. There now exists not only the Flash Player for Pocket PCs, but the new Flash Lite and Macromedia FlashCast client-server solution for delivering rich data services to mobile phones. Flash is also available in a wide array of other consumer electronics, including set-top boxes, home control systems, toys, refrigerators, electronic keyboards, and many others. The best part is that all of these platforms can still be developed for, using the Flash authoring environment.
To keep abreast of all these innovations, check Macromedia's web site at www.macromedia.com. You can search for any of the applications or players mentioned, and the site will direct you to several resources including forums, developer centers, download locations, and training.
Just as web browsing has moved from PCs to handhelds and now mobile phones, the Flash Player has morphed into new versions to support each of the different platforms. The Flash Players available currently are:
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Flash Resources
Inhaltsvorschau
If you need a book about Flash, again try Flash 8 Bible by Robert Reinhardt and Snow Dowd (Visual). For information on ActionScript, see ActionScript for Flash MX: The Definitive Guide, and Essential ActionScript 2.0, both by Colin Moock and published by O'Reilly. In addition to the many shelves full of other Flash books in your local bookstore, there are a number of resources for Flash online.
  • Macromedia's Flash Page: www.macromedia.com/software/flash
  • Macromedia's Developer Center: www.macromedia.com/desdev/mx/flash/
  • Flash Kit: www.flashkit.com
  • ChattyFig listserver Search: chattyfig.figleaf.com
  • Ultrashock: www.ultrashock.com/
  • Flash Magazine: www.flashmagazine.com/
  • ActionScripts.Org: www.actionscripts.org/
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Chapter 36: Printing from the Web
Inhaltsvorschau
The Web is undeniably an amazing resource for information, but it's not the most comfortable or portable of reading environments. For this reason, many people print web pages to read away from their desks or to file for later use.
The ability to print the contents of the window has been built into browsers from the beginning. The real breakthrough in controlling printed versions of web pages is the use of Cascading Style Sheets to customize the presentation of the document for the printed page. This alleviates the need for separate HTML documents or templates that provide "printer-friendly" versions of every page on a site.
The Web has proven to be an effective delivery device for printed documents in the form of PDF (Portable Document Format) files. Flash movies also offer some interesting possibilities for printing . This chapter explores all of these methods for bringing content from the Web to the printed page.
All graphical browsers have basic print and page setup controls that interface with the printer the same as any other application. In the Page Setup dialog box, users can generally select whether the page should print in portrait (vertical) or landscape (horizontal) format and specify how many copies to print.
In addition, most browsers have a Print Preview that shows how the page will look when it is printed. The Preview may also provide the ability to add headers and footers with URL and other page information, whether images print, and whether background and text colors should be preserved.
In most cases, browsers do a reasonably good job of printing web pages by default. They generally try to shrink the contents to fit the print area, and they may also be sophisticated enough to preserve background and text colors (for printing light text on a dark background). But if you want to be absolutely sure your pages print in a predictable way, you may choose to take measures into your own hands.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Browser Print Mechanisms
Inhaltsvorschau
All graphical browsers have basic print and page setup controls that interface with the printer the same as any other application. In the Page Setup dialog box, users can generally select whether the page should print in portrait (vertical) or landscape (horizontal) format and specify how many copies to print.
In addition, most browsers have a Print Preview that shows how the page will look when it is printed. The Preview may also provide the ability to add headers and footers with URL and other page information, whether images print, and whether background and text colors should be preserved.
In most cases, browsers do a reasonably good job of printing web pages by default. They generally try to shrink the contents to fit the print area, and they may also be sophisticated enough to preserve background and text colors (for printing light text on a dark background). But if you want to be absolutely sure your pages print in a predictable way, you may choose to take measures into your own hands.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Cascading Style Sheets for Print
Inhaltsvorschau
In the past, to provide a version of a web page that was appropriate for printing, it was common to create an alternate, "printer-friendly" version of each page on a site. In general, printer-friendly pages were stripped-down versions of the document, containing just the necessary content and presented in a single column with minimal markup (see the sidebar, "Still Need a Printer-Friendly Version?").
Your client may have specific ideas of what a printout of their site should look like. Some clients may want the printout to match the way it looks on the screen. Be sure to have a conversation about print version expectations before launching into the print style sheet production.
Now that Cascading Style Sheets (CSS) are widely supported, it is possible to create a version of the document that is customized for print without having to create a separate document. One well-structured and semantically marked up (X)HTML document provides the content (yet another reason to start with good markup), and CSS does all the rest. The method involves creating two style sheets --one appropriate for screen display and one appropriate for print—and using the media attribute or @media rule to match the style sheet to its intended medium. A more detailed explanation follows.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Portable Document Format (PDF)
Inhaltsvorschau
PDF (Portable Document Format) is a technology developed by Adobe for sharing electronic documents. The remarkable thing about PDF files is that they preserve the fonts, colors, formatting, and graphics of the original source document. Ideally, a PDF document looks exactly the way it was designed, regardless of the platform, hardware, and software environment of the end user. It can be viewed on the screen or printed out to a high-quality hardcopy.
PDF existed before the Web, but the two make great partners—PDF is the ideal file format for sharing documents, and the Web provides a highly accessible network for distributing them. You can make any document into a PDF file and make it available from a web page. The advantage, of course, is that you have precise control over fonts and layout.
Forms, documentation, and any other materials that rely on specific formatting are good candidates for PDF files. For example, the IRS makes tax forms available for download in PDF format so taxpayers can print them out at home.
PDF files are not necessarily static. They can contain links to online material and other PDF files. With Adobe Acrobat, authors can even create interactive PDF forms that can be filled out, automatically updated, and submitted online. PDFs can also be dynamically generated based on user input.
With the control PDF offers over presentation, it's tempting to want to use it for all online material. It's important to understand that PDF is not a substitute for HTML and CSS, nor is it likely ever to be. But it is a powerful tool for sharing any sort of document electronically. It's like sending a piece of paper through the lines.
PDFs are viewed and printed via the freely available and widely distributed Acrobat Reader . Acrobat Reader is also available as a plug-in (called PDFViewer) or ActiveX control and is supported by all the popular browsers (Internet Explorer, Netscape, Firefox/Mozilla, Safari, Opera) on a variety of platforms including Windows, Mac, and Unix.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Flash Printing
Inhaltsvorschau
Another interface between the browser and printer comes from the folks at Macromedia. Flash 4.0 introduced a new feature to give developers control over printing Flash content. Prior to Version 4, when a Flash movie was printed from a browser, the printout contained only the first frame (probably not the most useful frame) or nothing at all. To fix this, Flash Player can print any content specified by the designer.
This feature can be used to print out a more meaningful frame from the movie, but why stop there? Because any content can be cued to print, the Flash movie can serve as an interactive interface to all sorts of documents. A banner ad can spit out a coupon that shoppers can take to the store. A children's drawing program could print out the finished artwork or other coloring book-like pages. A small diagram could print pages of detailed specifications. Flash printing offers powerful possibilities for enhancing online interactivity with print components.
Users print Flash content via a context-sensitive menu accessed when clicking (Option-click for Windows; Control-click for Mac) on the Flash content, or by using a button designed into the Flash movie itself. The print function in the browser does not print the alternative Flash content.
The Flash print command triggers an ActionScript (the scripting language used in Flash) that detects the plug-in version; if it finds the compatible plug-in, it prints the specified Flash content. The content it prints is stored in a separate file in the Flash (SWF) format. This could be an image chosen from the current Flash movie, or any document created in Macromedia Flash, Freehand, Adobe Illustrator, or any program that supports Flash (SWF) files.
Because there is no print preview available for Flash content, it is recommended that you label your Flash print button very clearly with what happens if it is clicked. This is especially true if there is a large discrepancy between what you see on the screen and what will come out of the printer (such as a banner ad that prints a 12-page brochure).
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Appendix A: HTML Elements and Attributes
Inhaltsvorschau
This appendix contains an alphabetical listing of all elements and attributes in the HTML 4.01 and XHTML Recommendations, as well as a few nonstandard elements that are well-supported by current browsers. Elements and attributes marked as "Deprecated" have been removed from the (X)HTML Strict DTDs and are discouraged from use, usually in favor of Cascading Style Sheets. Attributes marked as "Required" must be included in the element for the markup to be valid.

Section A.1: Common Attributes and Events

Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Common Attributes and Events
Inhaltsvorschau
A number of attributes in the HTML 4.01 and XHTML Recommendations are shared by nearly all elements. To save space, they have been abbreviated in this appendix as they are in the Recommendations. This section explains each attribute's shorthand and serves as a reference for the remainder of the appendix.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Appendix B: CSS 2.1 Properties
Inhaltsvorschau
This Appendix provides an alphabetical listing of all the properties and values included in the Cascading Style Sheets 2.1 specification. It is organized into properties pertaining to visual, paged, and aural media. For updated information, see the World Wide Web Consortium (W3C) site at www.w3.org/Style/CSS.

Section B.1: Visual Media

Section B.2: Paged Media

Section B.3: Aural Styles

Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Visual Media
Inhaltsvorschau
background
Shorthand property for specifying all aspects of an element background.
Values:

[<'background-color'>||<'background-image'>||

<'background-repeat'>||<'background-attachment'>||

<'background-position'>]|inherit

Initial value:
See individual properties.
Applies to:
All elements.
Inherited:
No.
Percentages:
Allowed on background-position.
Computed value:
See individual properties.
background-attachment
Specifies whether the background image scrolls with the document or is fixed in the viewport (typically the browser window).
Values:

scroll | fixed | inherit

Initial value:

scroll

Applies to:
All elements.
Inherited:
No.
Computed value:
As specified.
background-color
Specifies a solid background color for the element that appears behind its content area, padding, and border.
Values:
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Paged Media
Inhaltsvorschau
orphans
Specifies the minimum number of lines of a paragraph that must be left at the bottom of a page.
Values:

<integer> | inherit

Initial value:

2

Applies to:
Block-level elements.
Inherited:
Yes.
Computed value:
As specified.
page-break-after
Specifies whether page breaks should be placed after an element.
Values:

auto | always | avoid | left | right | inherit

Initial value:

auto

Applies to:
Block-level elements.
Inherited:
No.
Computed value:
As specified.
page-break-before
Specifies whether page breaks should be placed before an element.
Values:

auto | always | avoid | left | right | inherit

Initial value:

auto

Applies to:
Block-level elements.
Inherited:
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Aural Styles
Inhaltsvorschau
Note that aural styles are only "informative" in CSS 2.1.
azimuth
Specifies the horizontal angle from which a sound should seem to emanate.
Values:

<angle> | [[ left-side | far-left | left | center-left | center | center-right | right |

far-right | right-side ] || behind ] | leftwards | rightwards | inherit

Initial value:

center

Applies to:
All elements.
Inherited:
Yes.
Computed value:
Normalized angle.
cue
Shorthand property for specifying cue-before and cue-after.
Values:

[ <'cue-before'> || <'cue-after'> ] | inherit

Initial value:
See individual properties.
Applies to:
All elements.
Inherited:
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Appendix C: Character Entities
Inhaltsvorschau
This appendix lists the Numeric Character References (both decimal and hexadecimal) and predefined character entities as defined in the HTML 4.01 and XHTML Recommendations.

Section C.1: ASCII Character Set

Section C.2: Nonstandard Entities (&#130;-&#159;)

Section C.3: Latin-1 (ISO-8859-1)

Section C.4: Latin Extended-A

Section C.5: Latin Extended-B

Section C.6: Spacing Modifier Letters

Section C.7: Greek

Section C.8: General Punctuation

Section C.9: Letter-like Symbols

Section C.10: Arrows

Section C.11: Mathematical Operators

Section C.12: Miscellaneous Technical Symbols

Section C.13: Geometric Shapes

Section C.14: Miscellaneous Symbols

Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
ASCII Character Set
Inhaltsvorschau
HTML and XHTML documents use the standard 7-bit ASCII character set in their source. The first 31 characters in ASCII (not listed) are such device controls as backspace (&#08;) and carriage return (&#13;) and are not appropriate for use in HTML documents.
HTML 4.01 defines only four entities in this character range: less than (<, &lt;), greater than (<, &gt;), ampersand (&, &amp;), and quotation mark (", &quot;), that are necessary for escaping characters that may be interpreted as markup. XHTML also includes the &apos; entity that is included in every XML language. In XHTML documents, the ampersand symbol (&) must always be escaped in attribute values. For better compatibility with XML parsers, authors should use numerical character references instead of named character references for all other character entities.
Decimal
Hex
Entity
Symbol
Description
&#032;
&#x20;
Space
&#033;
&#x21;
!
Exclamation point
&#034;
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Nonstandard Entities (&#130;-&#159;)
Inhaltsvorschau
The character references numbered 130 through 159 are not defined in HTML and therefore are invalid characters that should be avoided.
Some nonstandard numerical entities in this range are supported by browsers (such as &151; for an em dash), however, they all have standard equivalents listed in the "General Punctuation." section of this appendix. If you need an em dash, use &8212; or &mdash; instead.
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Latin-1 (ISO-8859-1)
Inhaltsvorschau
Decimal
Hex
Entity
Symbol
Description
&#160;
&#xA0;
&nbsp;
Nonbreaking space
&#161;
&#xA1;
&iexcl;
¡
Inverted exclamation mark
&#162;
&#xA2;
&cent;
¢
Cent sign
&#163;
&#xA3;
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Latin Extended-A
Inhaltsvorschau
Decimal
Hex
Entity
Symbol
Description
&#338;
&#x152;
&OElig;
?
Capital ligature OE
&#339;
&#x153;
&oelig;
?
Small ligature oe
&#352;
&#x160;
&Scaron;
Š
Capital S, caron
&#353;
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Latin Extended-B
Inhaltsvorschau
Decimal
Hex
Entity
Symbol
Description
&#402;
&#x192;
&fnof;
f
Small f with hook
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Spacing Modifier Letters
Inhaltsvorschau
Decimal
Hex
Entity
Symbol
Description
&#710;
&#x2C6;
&circ;
^
Circumflex accent
&#732;
&#x2DC;
&tilde;
~
Tilde
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Greek
Inhaltsvorschau
Decimal
Hex
Entity
Symbol
Description
&#913;
&#x391;
&Alpha;
A
Greek capital alpha
&#914;
&#x392;
&Beta;
B
Greek capital beta
&#915;
&#x393;
&Gamma;
Γ
Greek capital gamma
&#916;
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
General Punctuation
Inhaltsvorschau
Decimal
Hex
Entity
Symbol
Description
&#8194;
&#x2002;
&ensp;
En space
&#8195;
&#x2003;
&emsp;
Em space
&#8201;
&#x2009;
&thinsp;
Thin space
&#8204;
&#x200C;
&zwnj;
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Letter-like Symbols
Inhaltsvorschau
Decimal
Hex
Entity
Symbol
Description
&#8465;
&#x2111;
&image;
Blackletter capital I, imaginary part
&#8472;
&#x2118;
&weierp;
Script capital P, power set
&#8476;
&#x211C;
&real;
Blackletter capital R, real part
&#8482;
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Arrows
Inhaltsvorschau
Decimal
Hex
Entity
Symbol
Description
&#8592;
&#x2190;
&larr;
Left arrow
&#8593;
&#x2191;
&uarr;
Up arrow
&#8594;
&#x2192;
&rarr;
Right arrow
&#8595;
&#x2193;
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Mathematical Operators
Inhaltsvorschau
Decimal
Hex
Entity
Symbol
Description
&#8704;
&#x2200;
&forall;
For all
&#8706;
&#x2202;
&part;
Partial differential
&#8707;
&#x2203;
&exist;
There exists
&#8709;
&#x2205;
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Miscellaneous Technical Symbols
Inhaltsvorschau
Decimal
Hex
Entity
Symbol
Description
&#8968;
&#x2308;
&lceil;
Left ceiling
&#8969;
&#x2309;
&rceil;
Right ceiling
&#8970;
&#x230A;
&lfloor;
Left floor
&#8971;
&#x230B;
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Geometric Shapes
Inhaltsvorschau
Decimal
Hex
Entity
Symbol
Description
&#9674;
&#x25CA;
&loz;
Lozenge
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Miscellaneous Symbols
Inhaltsvorschau
Decimal
Hex
Entity
Symbol
Description
&#9824;
&#x2660;
&spades;
Black spade suit
&#9827;
&#x2663;
&clubs
Black club suit
&#9829;
&#x2665;
&hearts;
Black heart suit
&#9830;
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Appendix D: Specifying Color
Inhaltsvorschau
This appendix contains background information regarding specifying color that applies to both CSS properties and HTML attributes.
There are two methods for specifying colors in web documents: numeric RGB values and color names.

Section D.1: Specifying Color by RGB Values

Section D.2: Specifying Colors by Name

Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Specifying Color by RGB Values
Inhaltsvorschau
The most common and precise way to specify a color is by its numeric RGB (red, green, blue) values. Using RGB values, you can specify any color from the "true color" space (millions of colors). For an explanation of RGB color, see Chapter 28.
Using an image editing tool such as Adobe Photoshop, you can determine the RGB values (on a scale from 0 to 255) for a selected color. These are the RGB values for a particularly lovely spring green:
Red: 212
Green: 232
Blue: 119
Color values are most often provided in a two-digit hexadecimal (base-16) form, not decimal, although these values may be used as-is in one CSS color format. Hexadecimal numbering is discussed in more detail in the next section. The same RGB values for that spring green look like this when converted to hexadecimal:
Red: D4
Green: E8
Blue: 77
In the CSS and HTML document, the most common way of representing these values is in a six-character string, preceded by the # symbol:

#D4E877

The underlying syntax is this:

#RRGGBB

where RR stands for the hexadecimal red value, GG stands for the hexadecimal green value, and BB stands for the hexadecimal blue value. CSS has additional formats for RGB values, as listed in the upcoming See RGB Colors in CSS." section.
Fortunately, Adobe Photoshop makes the hexadecimal values for colors readily available at the bottom of the color picker next to the "#" symbol. The hex values can be copied from the color picker and pasted into a style sheet or HTML document.
If you are using an image tool that does not list hexadecimal values, you'll need to convert decimal to hexadecimal yourself. The next section tells you how.
The hexadecimal numbering system is base-16 (as compared to base-10 for decimal numbers). It uses the following 16 characters:
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Specifying Colors by Name
Inhaltsvorschau
Colors may also be identified by predefined color names. This technique is less common in everyday practice. The syntax for using color names is extremely straightforward.

color: green

 

<body link="navy">

In HTML 4.01, XHTML, CSS 1, and CSS 2, there are only 16 valid color names. They are listed in Table D-3 with their equivalent RGB values.
Table D-3: Valid color names and equivalent RGB values
Color name
RGB value
Color name
RGB value
black
#000000
green
#008000
silver
#C0C0C0
lime
#00FF00
gray
#808080
olive
#808000
white
#FFFFFF
yellow
#FFFF00
maroon
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Appendix E: Microformats: Extending (X)HTML
Inhaltsvorschau
by Tantek Çelik
XHTML stands for the Extensible HyperText Markup Language. HTML 4 was also designed to be extended, albeit much more subtly. In the past few years, there has been a resurging interest in extending HTML and XHTML. XHTML was originally designed to be extended with other XML elements, in other namespaces. In practice, such extensions have yet to meaningfully materialize on the Web.
Instead, using extension mechanisms introduced in HTML 4, such as the class, id, and rel attributes, web designers, developers, and technologists have been extending the semantics of their HTML and XHTML documents. In the past couple of years, common patterns and conventions have emerged for using these mechanisms. Microformats are an effort to standardize these conventions and are specifically designed for ease of use by web authors and to leverage existing interoperable standards. By doing so, microformats have enabled the simple sharing of even more semantic content on the Web without having to learn a new language or duplicate content (either in comments or separate files).
This appendix introduces a few of the open microformats standards being developed by the microformats community. To learn more, visit the microformats.org community site.

Section E.1: Extending HTML 4 and XHTML

Section E.2: Semantic Class Names

Section E.3: Link Relationships

Section E.4: More Microformats

Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Extending HTML 4 and XHTML
Inhaltsvorschau
By following many of the techniques recommended in this book, you may already be extending HTML for your own purposes without even knowing it. Chapter 10 discusses how to provide more semantic descriptions of your content using the class and id attributes. Every meaningful class name and ID extends the semantics expressed by your HTML documents.
HTML 4 has three built-in extension mechanisms. In addition to using semantic class and id attributes, web authors can create their own link relationships with the rel and rev attributes, and property names and values for use with the meta tag. Two of these mechanisms, class/id and rel/rev, are being leveraged into microformats. The third, meta, shows less promise, as is discussed in the sidebar "meta Names and Values.."
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Semantic Class Names
Inhaltsvorschau
HTML 4 has a limited set of built-in semantics. In 2004, a few web developers realized that by using carefully chosen sets of class names based on existing publishing behaviors and widely adopted Internet standards, they could extend HTML to meaningfully publish information about contacts, events, reviews, and other web data types. This section introduces microformats created for handling contact information and calendar events.
Most web sites publish contact information for the site's author or company, for example:

<div>

 <div>O'Reilly</div>

 <div>1005 Gravenstein Highway North</div>

 <div>Sebastopol, CA 95472</div>

 <div>USA</div>

 <div>T: (707) 827-7000</div>

 <div>F: (707) 829-0104</div>

 <div><a href="http://www.oreilly.com">www.oreilly.com</a></div>

</div>

By marking it up with the hCard microformat (which is based on the widely support vCard Internet contact information standard, hence the vcard class name), visitors to the site can easily add the site's contact info to their address book application using an hCard-to-vCard proxy service.

<div class="vcard">

 <div class="fn org">O'Reilly</div>

 <div class="adr">

  <div class="street-address">1005 Gravenstein Highway North</div>

  <span class="locality">Sebastopol</span>, <span class="region">CA</span>

  <span class="postal-code">95472</span>

  <div class="country-name">USA</div>

 </div>

 <div class="tel"><abbr class="type" title="work">T:</abbr> (707) 827-7000</div>

 <div class="tel"><abbr class="type" title="fax">F:</abbr> (707) 829-0104</div>

 <div><a class="url" href="http://www.oreilly.com">www.oreilly.com</a></div>

</div>

This is an hCard because it uses specific class names established as part of the hCard microformat . The specific elements are not relevant with the exception of the use of the abbr element to abbreviate the type of each phone number, and the addition of a few
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
Link Relationships
Inhaltsvorschau
The most common use of link relationships in HTML is to link to a style sheet (as explained in Chapter 16). In doing so, the author uses the rel attribute to communicate that the resource "over there" (referenced by the href attribute) is a "style sheet" for the current document. HTML 4 specifically allows for web authors to create and use their own link relationship values, and suggests using a profile to define them. Several popular new link relationship values have emerged to describe, for example, social network relationships between people, licenses for documents, and "tags" for blog posts. Many of these are quickly becoming de facto standards and have been documented as microformats.
Since the previous edition of this book, blogs and the larger blogging phenomenon have taken the Web by storm. As of this writing, there were approximately 22.6 million blogs according to real-time search engine Technorati (technorati.com). Many of these bloggers publish lists of links to blogs they themselves read, called blogrolls . Some indicate the relationship to the people in their blogrolls using symbols, such as asterisks (*) next to people they have met. Typical blogrolls are published as a list of hyperlinks:

<ul>

 <li><a href="http://molly.example.com">Molly*</a></li>

 <li><a href="http://jeff.example.com">Jeff*</a></li>

</ul>

In 2003, a few web developers proposed a standard called the XHTML Friends Network (XFN) for explicitly indicating social relationships using new rel attribute values on blogroll links. In the above example, to indicate that Molly is a colleague you have met and Jeff is a friend you have also met, simply add XFN values to rel attributes:

<ul>

 <li><a rel="colleague met" href="http://molly.example.com">Molly</a></li>

 <li><a rel="friend met" href="http://jeff.example.com">Jeff</a></li>

</ul>

For a full list of XFN relationship values and more information on using XFN, see the XFN home page at
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
More Microformats
Inhaltsvorschau
The microformats.org site has a comprehensive listing of well-established microformats that are broadly adopted, as well as nascent microformat efforts that are being designed. Table E-1 provides a summary of several types of content and the microformats that have been developed to represent them.
Table E-1: Examples of microformats
Microformat
Content
hCard
People, organizations, contacts
adr, geo
Address and latitude/longitude location
hCalendar
Calendars and events
hReview
Reviews, ratings
XOXO
Lists and outlines
XFN
Social network relationships
rel-license
Licenses
rel-tag
Tags, topics, categories
xFolk
Tagged links
rel-directory
Directory inclusion
Ende der Inhaltsvorschau. Der weiterere Inhalt dieses Abschnitts ist hier nicht einsehbar.
	

Zurück zu Web Design in a Nutshell