Web Design
Launch a career as a web designer by learning HTML5, CSS3, responsive design, Sass and more!

1.Publishing Web Content

Before learning the intricacies of HTML (Hypertext Markup Language), CSS (Cascading Style Sheets), and JavaScript, it is important that you gain a solid understanding of the technologies that help transform these plain- text files to the rich multimedia displays you see on your computer or handheld device when browsing the World Wide Web. For example, a file containing markup and client-side code HTML and CSS is useless without a web browser to view it, and no one besides yourself will see your content unless a web server is involved. Web servers make your content available to others who, in turn, use their web browsers to navigate to an address and wait for the server to send information to them. You will be intimately involved in this publishing process because you must create files and then put them on a server to make them available in the first place, and you must ensure that your content will appear to the end user as you intended.

A Brief History of HTML and the World Wide Web

Once upon a time, back when there weren’t any footprints on the moon, some farsighted folks decided to see whether they could connect several major computer networks together. I’ll spare you the names and stories (there are plenty of both), but the eventual result was the “mother of all networks,” which we call the Internet.

Until 1990, accessing information through the Internet was a rather technical affair. It was so hard, in fact, that even Ph.D. – holding physicists were often frustrated when trying to swap data. One such physicist, the now- famous (and knighted) Sir Tim Berners-Lee, cooked up a way to easily cross-reference text on the Internet through hypertext links.

This wasn’t a new idea, but his simple HTML managed to thrive while more ambitious hypertext projects floundered. Hypertext originally meant text stored in electronic form with cross-reference links between pages. It is now a broader term that refers to just about any object (text, images, files, and so on) that can be linked to other objects. Hypertext Markup Language is a language for describing how text, graphics, and files containing other information are organized and linked together.

By 1993, only 100 or so computers throughout the world were equipped to serve up HTML pages. Those interlinked pages were dubbed the World Wide Web (WWW), and several web browser programs had been written to allow people to view web pages. Because of the growing popularity of the Web, a few programmers soon wrote web browsers that could view graphical images along with text. From that point forward, the continued development of web browser software and the standardization of the HTML— and XHTML—languages has led us to the world we live in today, one in which more than 110 million web servers answer requests for more than 25 billion text and multimedia files.

These few paragraphs really are a brief history of what has been a remark- able period. Today’s college freshmen have never known a time in which the Web didn’t exist, and the idea of always-on information and ubiquitous computing will shape all aspects of our lives moving forward. Instead of seeing web content creation and management as a set of skills possessed only by a few technically oriented folks (okay, call them geeks if you will), by the end of this book, you will see that these are skills that anyone can master, regardless of inherent geekiness.

Creating Web Content

You might have noticed the use of the term web content rather than web pages—that was intentional. Although we talk of “visiting a web page,” what we really mean is something like “looking at all the text and the images at one address on our computer.” The text that we read, and the images that we see, are rendered by our web browsers, which are given certain instructions found in individual files.

Those files contain text that is marked up, or surrounded by, HTML codes that tell the browser how to display the text as a heading, as a paragraph, in a red font, and so on. Some HTML markup tells the browser to display an image or video file rather than plain text, which brings me back to the point: Different types of content are sent to your web browser, so simply saying web page doesn’t begin to cover it. Here we use the term web content instead, to cover the full range of text, image, audio, video, and other media found online.

In later chapters, you will learn the basics of linking to or creating the vari- ous types of multimedia web content found in websites. All you need to remember at this point is that you are in control of the content a user sees when visiting your website. Beginning with the file that contains text to display or codes that tell the server to send a graphic along to the user’s web browser, you have to plan, design, and implement all the pieces that will eventually make up your web presence. As you will learn throughout this book, it is not a difficult process as long as you understand all the little steps along the way.

In its most fundamental form, web content begins with a simple text file containing HTML or XHTML markup. XHTML is another flavor of HTML; the “X” stands for extensible, and you will learn more about it as you continue through the chapters. The most important thing to know from the outset is that all the examples in this book are HTML 4 and XHTML compatible, meaning that they will be rendered similarly both now and in the future by any newer generations of web browsers. That is one of the bene- fits of writing standards-compliant code: You do not have to worry about going back to your code sometime in the future and changing it because it doesn’t work. Your code will likely always work for as long as web browsers adhere to standards (hopefully a long time).

Understanding Web Content Delivery

Several processes occur, in many different locations, to eventually produce web content that you can see. These processes occur very quickly—on the order of milliseconds—and occur behind the scenes. In other words, although we might think all we are doing is opening a web browser, typ- ing in a web address, and instantaneously seeing the content we requested, technology in the background is working hard on our behalf. Figure 1.1 shows the basic interaction between a browser and a server.

FIGURE 1.1
A browser request and a server response.

However, there are several steps in the process—and potentially several trips between the browser and server—before you see the entire content of the site you requested. Suppose you want to do a Google search, so you dutifully type http://www.google.com in the address bar or select the Google bookmark from your bookmarks list. Almost immediately, your browser will show you something like what’s shown in Figure 1.2.

FIGURE 1.2
Visiting www.google.com.

Figure 1.2 shows a website that contains text plus one image (the Google logo). A simple version of the processes that occurred to retrieve that text and image from a web server and display it on your screen is as follows:

  1. Your web browser sends a request for the index.html file located at the http://www.google.com/ address. The index.html file does not have to be part of the address that you type in the address bar; you’ll learn more about the index.html file further along in this chapter.
  2. After receiving the request for a specific file, the web server process looks in its directory contents for the specific file, opens it, and sends the content of that file back to your web browser.
  3. The web browser receives the content of the index.html file, which is text marked up with HTML codes, and renders the content based on these HTML codes. While rendering the content, the browser hap- pens upon the HTML code for the Google logo, which you can see in Figure 1.2. The HTML code looks like this:

    <img src=”/logos/logo.gif” width=”384” height=”121” border=”0” alt=”Google”/>

    The tag provides attributes that tell the browser the file source loca- tion (src), width (width), height (height), border type (border), and alternative text (alt) necessary to display the logo. You will learn more about attributes throughout later chapters.
  4. The browser looks at the src attribute in the <img/> tag to find the source location. In this case, the image logo.gif can be found in the logos directory at the same web address (www.google.com) from which the browser retrieved the HTML file.
  5. The browser requests the file at the http://www.google.com/logos/logo.gif web address.
  6. The web server interprets that request, finds the file, and sends the contents of that file to the web browser that requested it.
  7. The web browser displays the image on your monitor.

As you can see in the description of the web content delivery process, web browsers do more than simply act as picture frames through which you can view content. Browsers assemble the web content components and arrange those parts according to the HTML commands in the file.

You can also view web content locally, or on your own hard drive, without the need for a web server. The process of content retrieval and display is the same as the process listed in the previous steps in that a browser looks for and interprets the codes and content of an HTML file, but the trip is shorter; the browser looks for files on your own computer’s hard drive rather than on a remote machine. A web server is needed to interpret any server-based programming language embedded in the files, but that is out- side the scope of this book. In fact, you could work through all the chap- ters in this book without having a web server to call your own, but then nobody but you could view your masterpieces.

Selecting a Web Hosting Provider

Despite just telling you that you can work through all the chapters in this book without having a web server, having a web server is the recommend- ed method for continuing on. Don’t worry—obtaining a hosting provider is usually a quick, painless, and relatively inexpensive process. In fact, you can get your own domain name and a year of web hosting for just slightly more than the cost of the book you are reading now.

If you type web hosting provider in your search engine of choice, you will get millions of hits and an endless list of sponsored search results (also known as ads). There are not this many web hosting providers in the world, although it might seem like there are. Even if you are looking at a managed list of hosting providers, it can be overwhelming—especially if all you are looking for is a place to host a simple website for yourself or your company or organization.

You’ll want to narrow your search when looking for a provider and choose one that best meets your needs. Some selection criteria for a web hosting provider include the following.”

  • . Reliability/server “uptime”—If you have an online presence, you want to make sure people can actually get there consistently.
  • . Customer service—Look for multiple methods for contacting cus- tomer service (phone, email, and chat) as well as online documenta- tion for common issues.
  • . Server space—Does the hosting package include enough server space to hold all the multimedia files (images, audio, and video) you plan to include in your website (if any)?
  • . Bandwidth—Does the hosting package include enough bandwidth so that all the people visiting your site and downloading files can do so without you having to pay extra?
  • . Domain name purchase and management—Does the package include a custom domain name, or must you purchase and maintain your domain name separately from your hosting account?
  • . Price—Do not overpay for hosting. You will see a wide range of prices offered and should immediately wonder “what’s the difference?” Often the difference has little to do with the quality of the service and everything to do with company overhead and what the company thinks they can get away with charging people. A good rule of thumb is that if you are paying more than $75 per year for a basic hosting package and domain name, you are probably paying too much.

Here are three reliable web hosting providers whose basic packages con- tain plenty of server space and bandwidth (as well as domain names and extra benefits) at a relatively low cost. If you don’t go with any of these web hosting providers, you can at least use their basic package descrip- tions as a guideline as you shop around.

  • A Small Orange —The “Tiny” and “Small” hosting packages are perfect starting places for the new web content publisher.
  • DailyRazor —Even its Rookie hosting package is full featured and reliable.
  • LunarPages —The Basic hosting pack- age is suitable for many personal and small business websites.

One feature of a good hosting provider is that it provides a “control panel” for you to manage aspects of your account. Figure 1.3 shows the control panel for my own hosting account at Daily Razor. Many web hosting providers offer this particular control panel software, or some control panel that is similar in design—clearly labeled icons leading to tasks you can perform to configure and manage your account.

FIGURE 1.3
A sample control panel.

You might never need to use your control panel but having it available to you simplifies the installation of databases and other software, the viewing of web statistics, and the addition of email addresses (among many other features). If you can follow instructions, you can manage your own web server no special training required.

Testing with Multiple Web Browsers

Having just discussed the process of web content delivery and the acquisition of a web server, it might seem a little strange to step back and talk about testing your websites with multiple web browsers. However, before you go off and learn all about creating websites with HTML and CSS, do so with this very important statement in mind: Every visitor to your website will potentially use hardware and software configurations that are different than your own. Their device types (desktop, laptop, netbook, smartphone, or iPhone), their screen resolutions, their browser types, their browser window sizes, and their speed of connections will be different remember that you cannot control any aspect of what your visitors use when they view your site. So, just as you’re setting up your web hosting environment and getting ready to work, think about downloading several different web browsers so that you have a local test suite of tools available to you. Let me explain why this is important.

Although all web browsers process and handle information in the same general way, there are some specific differences among them that result in things not always looking the same in different browsers. Even users of the same version of the same web browser can alter how a page appears by choosing different display options or changing the size of their viewing windows. All the major web browsers allow users to override the back- ground and fonts specified by the web page author with those of their own choosing. Screen resolution, window size, and optional toolbars can also change how much of a page someone sees when it first appears on their screens. You can ensure only that you write standards-compliant HTML and CSS.

Do not, under any circumstances, spend hours on end designing something that looks perfect on your own computer—unless you are willing to be disappointed when you look at it on your friend’s computer, on your tablet, or on your iPhone.

You should always test your websites with as many of these web browsers as possible:

  • Apple Safari for Mac and Windows
  • .  Google Chrome for Windows
  • . Mozilla Firefox for Mac, Windows, and Linux
  • . Microsoft Internet Explorer for Windows
  • . Opera for Mac, Windows, and Linux/UNIX

Now that you have a development environment set up, or at least some idea of the type you’d like to set up in the future, let’s move on to creating a test file.

Creating a Sample File

Before we begin, take a look at Listing 1.1. This listing represents a simple piece of web content—a few lines of HTML that print “Hello World!

Welcome to My Web Server.” in large, bold letters on two lines centered within the browser window.

LISTING 1.1        Our Sample HTML File

<html>
<head>
<title>Hello World!</title>
</head>
<body>
<h1 style=”text-align: center”>Hello World!<br/>Welcome to My Web
➥Server.</h1>
</body>
</html>

To make use of this content, open a text editor of your choice, such as Notepad (on Windows) or TextEdit (on a Mac). Do not use WordPad, Microsoft Word, or other full-featured word-processing software because those programs create different sorts of files than the plain-text files we use for web content.

Type the content that you see in Listing 1.1, and then save the file using sample.html as the filename. The .html extension tells the web server that your file is, indeed, full of HTML. When the file contents are sent to the web browser that requests it, the browser will also know that it is HTML and will render it appropriately.

Now that you have a sample HTML file to use—and hopefully somewhere to put it, such as a web hosting account—let’s get to publishing your web content.

Using FTP to Transfer Files

As you’ve learned so far, you have to put your web content on a web serv- er to make it accessible to others. This process typically occurs by using File Transfer Protocol (FTP). To use FTP, you need an FTP client—a program used to transfer files from your computer to a web server. FTP clients require three pieces of information to connect to your web serv- er; this information will have been sent to you by your hosting provider after you set up your account:

  • The hostname, or address, to which you will connect.
  • Your account username.
  • Your account password

After you have this information, you are ready to use an FTP client to transfer content to your web server.

Selecting an FTP Client

Regardless of the FTP client you use, FTP clients generally use the same type of interface. Figure 1.4 shows an example of FireFTP, which is an FTP client used with the Firefox web browser. The directory listing of the local machine (your computer) appears on the left of your screen and the directory listing of the remote machine (the web server) appears on the right. Typically, you will see right-arrow and left-arrow buttons as shown in Figure 1.4. The right arrow sends selected files from your computer to your web server; the left arrow sends files from the web server to your computer. Many FTP clients also enable you to simply select files, and then drag and drop those files to the target machines.

There are many FTP clients freely available to you, but you can also trans- fer files via the web-based File Manager tool that is likely part of your web server’s control panel. However, that method of file transfer typically introduces more steps into the process and isn’t nearly as streamlined (or simple) as installing an FTP client on your own machine.

FIGURE 1.4
The FireFTP interface.

Here are some popular free FTP clients:

  • Classic FTP for Mac and Windows
  • . Cyberduck for Mac
  • . Fetch for Mac
  • . FileZilla for all platforms
  • . FireFTP Firefox extension for all platforms

When you have selected an FTP client and installed it on your computer, you are ready to upload and download files from your web server. In the next section, you’ll see how this process works using the sample file in Listing 1.1.

Using an FTP Client

The following steps show how to use Classic FTP to connect to your web server and transfer a file. However, all FTP clients use similar, if not exact, interfaces. If you understand the following steps, you should be able to use any FTP client. Remember, you first need the hostname, the account username, and the account password.

  1. Start the Classic FTP program and click the Connect button. You will be prompted to fill out information for the site to which you want to connect, as shown in Figure 1.5.
FIGURE 1.5
Connecting to a new site in Classic FTP.

2. Fill in each of the items shown in Figure 1.5 as follows:

  • The site Label is the name you’ll use to refer to your own site. Nobody else will see this name, so enter whatever you want.
  • . The FTP Server is the FTP address of the web server to which you need to send your web pages. This address will have been given to you by your hosting provider. It will probably be yourdomain.com, but check the information you received when you signed up for service.
  • . The User Name field and the Password field should also be completed using information given to you by your hosting provider. . Don’t change the values for Initial Remote Directory on First Connection and Initial Local Directory on First Connection until you are used to using the client and have established a workflow.

3. When you’re finished with the settings, click OK to save the settings and establish a connection with the web server.
You will see a dialog box indicating that Classic FTP is attempting to connect to the web server. Upon successful connection, you will see an interface similar to Figure 1.6, showing the contents of the local directory on the left and the contents of your web server on the right.

FIGURE 1.6
A successful connection to a remote web server via Classic FTP.

4. You are now almost ready to transfer files to your web server. All that remains is to change directories to what is called the document root of your web server. The document root of your web server is the directo- ry that is designated as the top-level directory for your web content— the starting point of the directory structure, which you will learn more about later in this chapter. Often, this directory will be named public_html (as shown in Figure 1.6), www (also shown in Figure 1.6, as www has been created as an alias for public_html), or htdocs. This is not a directory that you will have to create because your hosting provider will have created it for you.
Double-click the document root directory name to open it. The dis- play shown on the right of the FTP client interface should change to show the contents of this directory. (It will probably be empty at this point, unless your web hosting provider has put placeholder files in that directory on your behalf.)

5. The goal is to transfer the sample.html file you created earlier from your computer to the web server. Find the file in the directory listing on the left of the FTP client interface (navigate around if you have to) and click it once to highlight the filename.

6. Click the right-arrow button in the middle of the client interface to send the file to the web server. After the file transfer is completed, the right side of the client interface should refresh to show you that the file has made it to its destination.

7. Click the Disconnect button to close the connection, and then exit out of the Classic FTP program.

These steps are conceptually similar to the steps you will take anytime you want to send files to your web server via FTP. You can also use your FTP client to create subdirectories on the remote web server. To create a subdi- rectory using Classic FTP, click the Remote menu, and then click New Folder. Different FTP clients will have different interface options to achieve the same goal.

Understanding Where to Place Files on the Web Server

An important aspect of maintaining web content is determining how you will organize that content—not only for the user to find, but also for you to maintain on your server. Putting files in directories will help you to man- age those files.

Naming and organizing directories on your web server, and developing rules for file maintenance, is completely up to you. However, maintaining a well-organized server simply makes your management of its content more efficient in the long run.

Basic File Management

As you browse the Web, you might have noticed that URLs change as you navigate through websites. For instance, if you’re looking at a company’s website and you click on graphical navigation leading to the company’s products or services, the URL will probably change from

http://www.companyname.com/

to

http://www.companyname.com/products/

or

http://www.companyname.com/services/

In the previous section, I used the term document root without really explaining what that is all about. The document root of a web server is essentially the trailing slash in the full URL. For instance, if your domain is yourdomain.com and your URL is http://www.yourdomain.com/, the document root is the directory represented by the trailing slash (/). The document root is the starting point of the directory structure you create on your web server; it is the place where the web server begins looking for files requested by the web browser.

If you put the sample.html file in your document root as previously direct- ed, you will be able to access it via a web browser at the following URL:

http://www.yourdomain.com/sample.html If you were to enter this URL into your web browser, you would see the rendered sample.html file, as shown in Figure 1.7.

However, if you created a new directory within the document root and put the sample.html file in that directory, the file would be accessed at this URL:

http://www.yourdomain.com/newdirectory/sample.html If you put the sample.html file in the directory you originally saw upon connecting to your server—that is, you did not change directories and place the file in the document root—the sample.html file would not be accessible from your web server at any URL. The file will still be on the machine that you know as your web server, but because the file is not in the document root—where the server software knows to start looking for files—it will never be accessible to anyone via a web browser.

The bottom line? Always navigate to the document root of your web server before you start transferring files.

This is especially true with graphics and other multimedia files. A common directory on web servers is called images, where, as you can imagine, all the image assets are placed for retrieval. Other popular directories include css for stylesheet files (if you are using more than one) and js for external JavaScript files. Or, if you know you will have an area on your website where visitors can download many different types of files, you might simply call that directory downloads.

Whether it’s a ZIP file containing your art portfolio or an Excel spreadsheet with sales numbers, it’s often useful to publish files on the Internet that aren’t simply web pages. To make a file available on the Web that isn’t an HTML file, just upload the file to your website as if it were an HTML file, following the instructions provided earlier in this chapter for uploading.

After the file is uploaded to the web server, you can create a link to it (as you’ll learn in later chapters). In other words, your web server can serve much more than HTML.

Here’s a sample of the HTML code that you will learn more about later in this book. The following code would be used for a file named artfolio.zip, located in the downloads directory of your website, and link text that reads “Download my art portfolio!”:

<a href=”/downloads/artfolio.zip”>Download my art portfolio!</a>

Using an Index Page

When you think of an index, you probably think of the section in the back of a book that tells you where to look for various keywords and topics. The index file in a web server directory can serve that purpose—if you design it that way. In fact, that’s where the name originates.

The index.html file (or just index file, as it’s usually referred to) is the name you give to the page you want people to see as the default file when they navigate to a specific directory in your website. If you’ve created that page with usability in mind, your users will be able to get to all content in that section from the index page.

For example, Figure 1.8 shows the drop-down navigation and left-side navigation both contain links to three pages: Solutions Overview (the section index page itself), Connection Management, and Cost Management.

The content of the page itself called index.html and located within the solutions directory—also has links to those two additional pages in the solutions section. When users arrive at the index page of the “solutions” section in this particular website (at least at the time of the snapshot), they can reach any other page in that section (and in three different ways!).

FIGURE 1.8
Showing a good section index page.

Another function of the index page is that when users visit a directory on your site that has an index page, but they do not specify that page, they will still land on the main page for that section of your site—or for the site itself.

For instance, in the previous example, a user could have typed either of the following URLs and landed on the main page of the solutions section of that website:

http://www.ipass.com/solutions/

http://www.ipass.com/solutions/index.html

Had there been no index.html page in the solutions directory, the results would depend on the configuration of the web server. If the server is con- figured to disallow directory browsing, the user would have seen a “Directory Listing Denied” message when attempting to access the URL without a specified page name. However, if the server is configured to allow directory browsing, the user would have seen a list of the files in that directory.

These server configuration options will have already been determined for you by your hosting provider. If your hosting provider enables you to modify server settings via a control panel, you can change these settings so that your server responds to requests based on your own requirements.

Not only is the index file used in subdirectories, it’s used in the top-level directory (or document root) of your website as well. The first page of your website—or home page or main page, or however you like to refer to the web content you want users to see when they first visit your domain—should be named index.html and placed in the document root of your web server. This will ensure that when users type http://www.yourdomain.com/ into their web browsers, the server will respond with content you intended them to see (rather than “Directory Listing Denied” or some other unintended consequence).

Distributing Content Without a Web Server

Publishing HTML and multimedia files online is obviously the primary reason to learn HTML and create web content. However, there are also situations in which other forms of publishing simply aren’t viable. For example, you might want to distribute CD-ROMs, DVD-ROMs, or USB drives at a trade show with marketing materials designed as web content—that is, hyperlinked text viewable through a web browser, but without a web serv- er involved. You might also want to include HTML-based instructional manuals on removable media for students at a training seminar. These are just two examples of how HTML pages can be used in publishing scenarios that don’t involve the Internet.

This process is also called creating local sites; even though there’s no web server involved, these bundles of hypertext content are still called sites. The local term comes into play because your files are accessed locally and not remotely (via a web server).

Publishing Content Locally

Let’s assume you need to create a local site that you want to distribute on a USB drive. Even the cheapest USB drives hold so much data these days— and basic hypertext files are quite small—that you can distribute an entire site and a fully functioning web browser all on one little drive.

Simply think of the directory structure of your USB drive just as you would the directory structure of your web server. The top-level of the USB drive directory structure can be your document root. Or if you are distributing a web browser along with the content, you might have two directories—for example, one named browser and one named content. In that case, the content directory would be your document root. Within the document root, you could have additional subfolders in which you place content and other multimedia assets.

It’s as important to maintain good organization with a local site as it is with a remote website so that you avoid broken links in your HTML files. You will learn more about the specifics of linking together files in a later chapter.

Publishing Content on a Blog

You might have a blog hosted by a third-party, such as Blogger or WordPress (among others), and thus have already published content with- out having a dedicated web server or even knowing any HTML. These services offer visual editors in addition to source editors, meaning that you can type your words and add visual formatting such as bold, italics, or font colors without knowing the HTML for these actions. But still, the content becomes actual HTML when you click the Publish button in these editors.

However, with the knowledge you will acquire throughout this book, your blogging will be enhanced because you will able to use the source editor for your blog post content and blog templates, thus affording you more control over the look and feel of that content. These actions occur differently from the process you learned for creating an HTML file and uploading it via FTP to your own dedicated web server, but I would be remiss if I did not note that blogging is, in fact, a form of web publishing.

Tips for Testing Web Content

Whenever you transfer files to your web server or place them on remov- able media for local browsing, you should immediately test every page thoroughly. The following checklist will help ensure that your web content behaves the way you expected. Note that some of the terms might be unfamiliar to you at this point, but come back to this checklist as you progress through this book and create larger projects:

  • Before you transfer your files, test them locally on your machine to ensure that the links work and the content reflects the visual design you intended. After you transfer the pages to a web server or remov- able device, test them all again.
  • . Perform these tests with as many browsers that you can—Chrome, Firefox, Internet Explorer, Opera, and Safari is a good list—and on both Mac and Windows platforms. If possible, check at low resolu- tion (800´600) and high resolution (1600´1200).
  • . Turn off auto image loading in your web browser before you start testing so that you can see what each page looks like without the graphics. Check your alt tag messages, and then turn image loading back on to load the graphics and review the page carefully again.
  • . Use your browser’s font size settings to look at each page in various font sizes to ensure that your layout doesn’t fall to pieces if users override your font specifications with their own.
  • . Wait for each page to completely finish loading, and then scroll all the way down to make sure that all images appear where they should.
  • . Time how long it takes each page to load. Does it take more than a few seconds to load? If so, is the information on that page valuable enough to keep users from going elsewhere before the page finishes loading? Granted, broadband connections are common, but that doesn’t mean you should load up your pages with 1MB images.

If your pages pass all those tests, you can rest easy; your site is ready for public viewing.

Summary

This chapter introduced you to the concept of using HTML to mark-up text files to produce web content. You also learned that there is more to web content than just the “page”—web content also includes image, audio, and video files. All of this content lives on a web server—a remote machine often far away from your own computer. On your computer or other device, you use a web browser to request, retrieve, and eventually display web content on your screen.

You learned the criteria you should consider when determining if a web hosting provider fits your needs. After you have a web hosting provider, you can begin to transfer files to your web server using an FTP client. You also learned a little bit about web server directory structures and file man- agement, as well as the very important purpose of the index.html file in a given web server directory. You discovered that you can distribute web content on removable media, and how to go about structuring the files and directories to achieve the goal of viewing content without using a remote web server. Finally, you learned the importance of testing your work in multiple browsers after you’ve placed it on a web server. Writing valid, standards-compliant HTML and CSS will help ensure your site looks reasonably similar for all visitors, but you still shouldn’t design without receiving input from potential users outside your development team—it is even more important to get input from others when you are a design team of one!

Q & A

Q. I’ve looked at the HTML source of some web pages on the Internet and it looks frighteningly difficult to learn. Do I have to think like a computer programmer to learn this stuff?

A. Although complex HTML pages can indeed look daunting, learning HTML is much easier than learning actual software programming languages (such as C++ or Java). HTML is a markup language rather than a pro- gramming language; you mark-up text so that the text can be rendered a certain way by the browser. That’s a completely different set of thought processes than developing a computer program. You really don’t need any experience or skill as a computer programmer to be a successful web content author.

One of the reasons the HTML behind many commercial websites looks complicated is because it was likely created by a visual web design tool—a “what you see is what you get” or “WYSIWYG” editor that will use whatever markup its software developer told it to use in certain cir- cumstances—as opposed to being hand-coded, in which you are com- pletely in control of the resulting markup. In this book, you are taught fundamental coding from the ground up, which typically results in clean, easy-to-read source code. Visual web design tools have a knack for making code difficult to read and for producing code that is convoluted and non-standards compliant.

Q. All the tests you recommend would take longer than creating my pages! Can’t I get away with less testing?

A. If your pages aren’t intended to make money or provide an important service, it’s probably not a big deal if they look funny to some users or produce errors once in a while. In that case, just test each page with a couple of different browsers and call it a day. However, if you need to project a professional image, there is no substitute for rigorous testing.

Q. Seriously, who cares how I organize my web content?

A. Believe it or not, the organization of your web content does matter to search engines and potential visitors to your site—you’ll learn more about this in Chapter 28, “Helping People Find Your Web Pages.” But overall, having an organized web server directory structure will help you keep track of content that you are likely to update frequently. For instance, if you have a dedicated directory for images or multimedia, you will know exactly where to look for a file you want to update—no need to hunt through directories containing other content.

Workshop

The workshop contains quiz questions and exercises to help you solidify your understanding of the material covered. Try to answer all questions before looking at the “Answers” section that follows.

Quiz

  1. How many files would you need to store on a web server to produce a single web page with some text and two images on it?
  2. What are some of the features to look for in a web hosting provider?
  3. What three pieces of information do you need to connect to your web server via FTP?
  4. What is the purpose of the index.html file?
  5. Does your website have to include a directory structure?

Answers

  1. You would need three: one for the web page itself, which includes the text and the HTML markup, and one for each of the two images.
  2. Look for reliability, customer service, web space and bandwidth, domain name service, site management extras, and price.
  3. The hostname, your account username, and your account password.
  4. The index.html file is typically the default file for a directory within a web server. It allows users to access http://www.yourdomain.com/ somedirectory/ without using a trailing file name and still end up in the appropriate place.
  5. No. Using a directory structure for file organization is completely up to you, although it is highly recommended to use one because it simplifies content maintenance.

Exercises

. Get your web hosting in order—are you going to go through the chap- ters in this book by viewing files locally on your own computer, or are you going to use a web hosting provider? Note that most web hosting providers will have you up and running the same day you purchase your hosting plan.

. If you are using an external hosting provider, and then using your FTP client, create a subdirectory within the document root of your website. Paste the contents of the sample.html file into another file named index.html, change the text between the <title> and </title> tags to something new, and change the text between the <h1> and </h1> tags to something new. Save the file and upload it to the new subdirectory. Use your web browser to navigate to the new directory on your web server and see that the content in the index.html file appears. Then, using your FTP client, delete the index.html file from the remote subdi- rectory. Return to that URL with your web browser, reload the page, and see how the server responds without the index.html file in place.

.  Using the same set of files created in the previous exercise, place these files on a removable media device—a CD-ROM or a USB drive, for example. Use your browser to navigate this local version of your sample website, and think about the instructions you would have to distribute with this removable media so that others could use it.

2.Understanding HTML
and
XHTML Connections

The first chapter gave you a basic idea of the process behind creating web content and viewing it online (or locally, if you do not yet have a web hosting provider). In this chapter, we’ll get down to the business of explaining the various elements that must appear in an HTML file so that it is dis- played appropriately in your web browser.

By the end of the chapter, you’ll learn how HTML differs from XHTML and why there are two different languages designed to do the same thing create web content. In general, this chapter provides a quick summary of HTML and XHTML basics and gives some practical tips to make the most of your time as a web page author and publisher. It’s not all theory, however; you do get to see a real web page and the HTML code behind it.

Getting Prepared

Here’s a review of what you need to do before you’re ready to use the rest of this book:

  1. Get a computer. I used a computer running Ubuntu (Linux) to test the sample web content and capture the figures in this book, but you can use any Windows, Macintosh, or Linux/UNIX machine to create and view your web content.
  2. Get a connection to the Internet. Whether you have a dial-up, wire- less, or broadband connection doesn’t matter for the creation and viewing of your web content, but the faster the connection, the better for the overall experience. The Internet service provider (ISP), school, or business that provides your Internet connection can help you with the details of setting it up properly. Additionally, many public spaces such as coffee shops, bookstores, and libraries offer free wireless Internet service that you can use if you have a laptop computer with Wi-Fi network support.
  3. Get web browser software. This is the software your computer needs to retrieve and display web content. As you learned in the first chap- ter, the most popular browser software (in alphabetical order) is Apple Safari, Google Chrome, Microsoft Internet Explorer, Mozilla Firefox, and Opera. It’s a good idea to install several of these browsers so that you can experiment and make sure that your con- tent looks consistent across them all; you can’t make assumptions about the browsers other people are using.
  4. Explore! Use a web browser to look around the Internet for websites that are similar in content or appearance to those you’d like to create. Note what frustrates you about some pages, what attracts you and keeps you reading others, and what makes you come back to some pages over and over again. If there is a particular topic that interests you, consider searching for it using a popular search engine.

Getting Started with a Simple Web Page

In the first chapter, you learned that a web page is just a text file that is marked up by (or surrounded by) HTML codes that tell the browser how to display the text. To create these text files, use a text editor such as Notepad (on Windows) or TextEdit (on a Mac)—do not use WordPad, Microsoft Word, or other full-featured word-processing software because those create different sorts of files than the plain-text files we use for web content.

Before you begin working, you should start with some text that you want to put on a web page:

  1. Find (or write) a few paragraphs of text about yourself, your family, your company, your softball team, or some other subject in which you’re interested.
  2. Save this text as plain, standard ASCII text. Notepad and most simple text editors always save files as plain text, but if you’re using another program, you might need to choose this file type as an option (after selecting File, Save As).

As you go through this chapter, you will add HTML markup (called tags) to the text file, thus making it into web content.

When you save files containing HTML tags, always give them a name ending in .html. This is important: If you forget to type the .html at the end of the filename when you save the file, most text editors will give it some other extension (such as .txt). If that happens, you might not be able to find the file when you try to look at it with a web browser; if you find it, it certainly won’t display properly. In other words, web browsers expect a web page file to have a file extension of .html.

When visiting websites, you might also encounter pages with a file extension of .htm, which is also an acceptable file extension to use. You might find other file extensions used on the Web, such as .jsp (Java Server Pages),

.asp (Microsoft Active Server Pages), or .php (PHP: Hypertext Preprocessor), but these file types use server-side technologies that are beyond the scope of HTML and the chapters throughout this book.

However, these files also contain HTML in addition to the programming language; although the programming code in those files is compiled on the server side and all you would see on the client side is the HTML output, if you were to look at the source files, you would likely see some intricate weaving of programming and markup codes.

Listing 2.1 shows an example of text you can type and save to create a simple HTML page. If you opened this file with Firefox, you would see the page shown in Figure 2.1. Every web page you create must include the <html></html>, <head></head>, <title></title>, and <body></body> tag pairs.

LISTING 2.1     The <html>, <head>, <title>, and <body> Tags

<?xml version=”1.0” encoding=”UTF-8”?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
“http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en”>
<head>
<title>The First Web Page</title>
</head>

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

In Listing 2.1, as in every HTML page, the words starting with < and ending with > are actually coded commands. These coded commands are called HTML tags because they “tag” pieces of text and tell the web brows- er what kind of text it is. This allows the web browser to display the text appropriately.

The first few lines of code in the web page serve as standard boilerplate code that you will include in all of your pages. This code actually identifies the page as a valid XHTML 1.1 document, which means that, technically, the web page is an XHTML page. All the pages developed throughout the book are XHTML 1.1 pages. Because XHTML is a more structured version of HTML, it’s still okay to generally refer to all the pages in the book as HTML pages. By targeting XHTML 1.1 with your code, you are developing web pages that adhere to the very latest web standards. This is a good thing! If you have obtained a web hosting account, you could use FTP at this point to transfer the firstpage.html file to the web server. In fact, from this chapter forward, the instructions will assume you have a hosting provider and are comfortable sending files back and forth via FTP; if that is not the case, please review the first chapter before moving on. Or, if you are consciously choosing to work with files locally (without a web host), be pre- pared to adjust the instructions to suit your particular needs (such as ignoring the commands “transfer the files” and “type in the URL”).

HTML Tags Every XHTML Web Page Must Have

The time has come for the secret language of HTML tags to be revealed to you. When you understand this language, you will have creative powers far beyond those of other humans. Don’t tell the other humans, but it’s really pretty easy.

Before you get into the HTML tags, let’s first address the messy-looking code at the top of Listing 2.1. The first line indicates that the HTML document is, in fact, an XML document:

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

The version of XML is set to 1.0, which is fairly standard, as is the type of character encoding (UTF-8).

The second and third lines of code in Listing 2.1 are even more complicated looking:

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”

“http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>

Again, the specifics of this code aren’t terribly important as long as you remember to include the code at the start of your pages. This code identifies the document as being XHTML 1.1, which then allows web browsers to make sure the code meets all the requirements of XHTML 1.1.

Most HTML tags have two parts: an opening tag, which indicates where a piece of text begins, and a closing tag, which indicates where the piece of text ends. Closing tags start with a / (forward slash) just after the < symbol.

Another type of tag is the empty tag, which is unique in that it doesn’t include a pair of matching opening and closing tags. Instead, an empty tag consists of a single tag that starts with a < and ends with a / just before the

> symbol.

Following is a quick summary of these three tags just to make sure you understand the role each plays:

• An opening tag is an HTML tag that indicates the start of an HTML command; the text affected by the command appears after the opening tag. Opening tags always begin with < and end with >, as in

<html>.

• A closing tag is an HTML tag that indicates the end of an HTML command; the text affected by the command appears before the closing tag. Closing tags always begin with </ and end with >, as in </html>.

• An empty tag is an HTML tag that issues an HTML command with- out enclosing any text in the page. Empty tags always begin with < and end with />, as in <br /> and <img />.

For example, the <body> tag in Listing 2.1 tells the web browser where the actual body text of the page begins, and </body> indicates where it ends. Everything between the <body> and </body> tags will appear in the main display area of the web browser window, as shown in Figure 2.1.

The very top of the browser window (refer to Figure 2.1) shows title text, which is any text that is located between <title> and </title>. The title text is also used to identify the page on the browser’s Bookmarks or Favorites menu, depending on which browser you use. It’s important to provide titles for your pages so that visitors to the page can properly book- mark them for future reference.

You will use the <body> and <title> tag pairs in every HTML page you create because every web page needs a title and body text. You will also use the <html> and <head> tag pairs, which are the other two tags shown in Listing 2.1. Putting <html> at the very beginning of a document simply indicates that the document is a web page. The </html> at the end indicates that the web page is over.

Within a page, there is a head section and a body section. Each section is identified by <head> and <body> tags. The idea is that information in the head of the page somehow describes the page but isn’t actually displayed by a web browser. Information placed in the body, however, is displayed by a web browser. The <head> tag always appears near the beginning of the HTML code for a page, just after the opening <html> tag.

The <title> tag pair used to identify the title of a page appears within the head of the page, which means it is placed after the opening <head> tag and before the closing </head> tag. In upcoming chapters, you’ll learn about some other advanced header information that can go between

<head> and </head>, such as style sheet rules that are used to format the page, as well as the JavaScript you’ll learn to write and embed.

The <p> tag used in Listing 2.1 encloses a paragraph of text. You should enclose your chunks of text in the appropriate container tags whenever possible.

Organizing a Page with Paragraphs and Line Breaks

When a web browser displays HTML pages, it pays no attention to line endings or the number of spaces between words. For example, the top ver- sion of the poem shown in Figure 2.2 appears with a single space between all words, even though that’s not how it’s entered in Listing 2.2. This is because extra whitespace in HTML code is automatically reduced to a single space. Additionally, when the text reaches the edge of the browser window, it automatically wraps to the next line, no matter where the line breaks were in the original HTML file.

FIGURE 2.2
When the HTML in Listing 2.2 is viewed as a web page, line and paragraph breaks only appear where there are <br /> and <p> tags

LISTING 2.2     HTML Containing Paragraph and Line Breaks                   

<?xml version=”1.0” encoding=”UTF-8”?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
“http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en”>
<head>
<title>The Advertising Agency Song</title>
</head>

<body>
<p>
When your client’s	hopping mad, 
put his picture in the ad.

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

</p>

<hr />

<p>
When your client’s hopping mad,<br /> 
put his picture in the ad.
</p>
<p>
If he still should prove refractory,<br /> 
add a picture of his factory.
</p>
</body>
</html>

You must use HTML tags if you want to control where line and paragraph breaks actually appear. When text is enclosed within the <p></p> container tags, a line break will be assumed after the closing tag. In later chapters, you will learn to control the height of the line break using CSS. The <br /> tag forces a line break within a paragraph. Unlike the other tags you’ve seen so far, <br /> doesn’t require a closing </br> tag—this is one of those empty tags discussed earlier. Although HTML 4 does not require the / in empty tags, XHTML does and future standards will, so it’s important for you to stick to the latest standards and create web pages that are coded properly. Always code empty tags so that they end with />.

The poem in Listing 2.2 and Figure 2.2 shows the <br /> and <p> tags being used to separate the lines and verses of an advertising agency song. You might have also noticed the <hr /> tag in the listing, which causes a horizontal rule line to appear on the page (see Figure 2.2). Inserting a horizontal rule with the <hr /> tag also causes a line break, even if you don’t include a <br /> tag along with it. Like <br />, the <hr /> horizontal rule tag is an empty tag and therefore never gets a closing </hr> tag.

Organizing Your Content with Headings

When you browse through web pages on the Internet, you’ll notice that many of them have a heading at the top that appears larger and bolder than the rest of the text. Listing 2.3 is sample code and text for a simple web page containing an example of a heading as compared to normal paragraph text. Any text between <h1> and </h1> tags will appear as a large heading. Additionally, <h2> and <h3> make progressively smaller headings, and so on as far down as <h6>.

LISTING 2.3        Heading Tags

<?xml version=”1.0” encoding=”UTF-8”?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
“http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en”>
<head>
<title>My Widgets</title>
</head>

<body>
<h1>My Widgets</h1>
<p>My widgets are the best in the land. Continue reading to learn more about my widgets.</p>

<h2>Widget Features</h2>
<p>If I had any features to discuss, you can bet I’d do it here.</p>

<h3>Pricing</h3>
<p>Here, I would talk about my widget pricing.</p>
<h3>Comparisons</h3>
<p>Here, I would talk about how my widgets compare to my competitor’s widgets.</p>

</body>
</html>


FIGURE 2.3

As you can see in Figure 2.3, the HTML that creates headings couldn’t be simpler. In this example, the phrase “My Widgets” is prominently dis- played using the <h1> tag. To create the biggest (level 1) heading, just put an <h1> tag at the beginning and a </h1> tag at the end of the text you want to use as a heading. For a slightly smaller (level 2) heading—for information that is of lesser importance than the title— use the <h2> and

</h2> tags around your text. For content that should appear even less prominently than a level 2 heading, use the <h3> and </h3> tags around your text.

However, bear in mind that your headings should follow a content hierarchy; use only one level 1 heading, have one (or more) level 2 headings after the level 1 heading, use level 3 headings directly after level 2 headings,

and so on. Do not fall into the trap of assigning headings to content just to make that content display a certain way. Instead, ensure that you are categorizing your content appropriately (as a main heading, a secondary heading, and so on), while using display styles to make that text render a particular way in a web browser.

Theoretically, you can also use <h4>, <h5>, and <h6> tags to make progressively less important headings, but these aren’t used very often. Web browsers seldom show a noticeable difference between these headings and the <h3> headings anyway, and content usually isn’t displayed in such a manner as to need six levels of headings to show the content hierarchy.

It’s important to remember the difference between a title and a heading. These two words are often interchangeable in day-to-day English, but when you’re talking HTML, <title> gives the entire page an identifying name that isn’t displayed on the page itself; it’s displayed only on the browser window’s title bar. The heading tags, on the other hand, cause some text on the page to be displayed with visual emphasis. There can be only one <title> per page and it must appear within the <head> and

</head> tags, whereas you can have as many <h1>, <h2>, and <h3> headings as you want, in any order that suits your fancy. However, as I mentioned before, you should use the heading tags to keep tight control over content hierarchy; do not use headings as a way to achieve a particular look because that’s what CSS is for.

You’ll learn to take complete control over the appearance of text on your web pages in Parts II and III of this book. Short of taking exacting control of the size, family, and color of fonts, headings provide the easiest and most popular way to draw extra attention to important text.

Validating Your Web Content

FIGURE 2.4
The W3C Markup Validation Service enables you to validate an HTML (XHTML) docu- ment to ensure it has been coded accurately

In the first chapter, I discussed ways to test your pages; one very important way to test your pages is to validate them. Think of it this way: It’s one thing to design and draw a beautiful set of house plans, but it’s quite another for an architect to stamp it as a safe structure suitable for construction. Validating your web pages is a similar process; in this case, however, the architect is an application—not a person.

In brief, validation is the process of testing your pages with a special application that searches for errors and makes sure your pages follow the strict XHTML standard. Validation is simple. In fact, the standards body responsible for developing web standards—the World Wide Web Consortium (W3C)—offers an online validation tool you can use. To validate a page, follow this URL: http://validator.w3.org/. The W3C Markup Validation Service is shown in Figure 2.4.

If you’ve already published a page online, you can use the Validate by URI tab. Use the Validate by File Upload tab to validate files stored on your local computer file system. The Validate by Direct Input tab enables you to paste the contents of a file from your text editor. If all goes well, your page will get a passing report (see Figure 2.5).

If the W3C Markup Validation Service encounters an error in your web page, it will provide specific details (including the line numbers of the offending code). This is a great way to hunt down problems and rid your pages of buggy code. Validation not only informs you whether your pages are constructed properly, it also assists you in finding and fixing problems before you post pages for the world to see.

FIGURE 2.5
If a page passes the W3C Markup Validation Service, you know it is ready for prime time.

The Scoop on HTML, XML, XHTML, and HTML5

In its early days, HTML was great because it allowed scientists to share information over the Internet in an efficient and relatively structured manner. It wasn’t until later that graphical web browsers were created, and HTML started being used to code more than scientific papers. HTML quickly went from a tidy little markup language for researchers to an online publishing language. After it was established, that HTML could be jazzed up for graphical browsing, the creators of web browsers went crazy by adding lots of nifty features to the language. Although these new features were neat at first, they compromised the original design of HTML and introduced inconsistencies when it came to how browsers displayed web pages; new features worked on only one browser or another, and you were out of luck if you happened to be running the wrong browser. HTML started to resemble a bad remodeling job of a house—a job done by too many contractors and without proper planning. As it turns out, some of the browser-specific features created during this time have now been adopted as standards whereas others have been dropped completely.

As with most revolutions, the birth of the Web was very chaotic, and the modifications to HTML reflected that chaos. Over the years, a significant

effort has been made to reel in the inconsistencies of HTML and restore some order to the language. The problem with disorder in HTML is that it results in web browsers having to guess at how a page is to be displayed, which is not a good thing. Ideally, a web page designer should be able to define exactly how a page is to look and have it look the same regardless of what kind of browser or operating system someone is using. Better still, a designer should be able to define exactly what a page means and have that page look consistent across different browsers and platforms. This utopia is still off in the future somewhere, but a markup language called XML (Extensible Markup Language) began to play a significant role in leading us toward it.

XML is a general language used to create specific languages, such as HTML. It might sound a little strange, but it really just means that XML provides a basic structure and set of rules to which any markup language must adhere. Using XML, you can create a unique markup language to describe just about any kind of information, including web pages.

Knowing that XML is a language for creating other markup languages, you could create your own version of HTML using XML. You could even create a markup language called BCCML (Bottle Cap Collection Markup Language), for example, which you could use to create and manage your extensive collection of rare bottle caps. The point is that XML lays the ground rules for organizing information in a consistent manner, and that information can be anything from web pages to bottle caps.

You might be thinking that bottle caps don’t have anything to do with the Web, so why mention them? The reason is that XML is not entirely about web pages. XML is actually broader than the Web in that it can be used to represent any kind of information on any kind of computer. If you can visualize all the information whizzing around the globe among computers, mobile phones, handheld computers, televisions, and radios, you can start to understand why XML has much broader applications than just cleaning up web pages. However, one of the first applications of XML is to restore some order to the Web, which is why XML is relevant to learning HTML. If XML describes data better than HTML, does it mean that XML is set to upstage HTML as the markup language of choice for the Web? No. XML is not a replacement for HTML; it’s not even a competitor of HTML. XML’s impact on HTML has to do with cleaning up HTML. HTML is a relatively unstructured language that benefits from the rules of XML. The natural merger of the two technologies resulted in HTML’s adherence to the rules and structure of XML. To accomplish this merger, a new version of HTML was

formulated that follows the stricter rules of XML. The new XML-compliant version of HTML is known as XHTML. Fortunately for you, you’ll actually be learning XHTML throughout this book because it is really just a cleaner version of HTML.

You might have heard about HTML5, which is touted as the next web standard. It will be, but not quite yet. When it does become a web standard, it will not render XHTML useless—HTML5 is not a replacement for XHTML, but instead is a major revision of HTML 4. In other words, XHTML and HTML5 can coexist on the Web, and web browsers that currently support XHTML will also (one day) support HTML5 as well.

The goal of this book is to guide you through the basics of web publishing, using XHTML and CSS as the core languages of those pages. However, whenever possible, I will note elements of the languages that are not present in HTML5, should you want to design your content for even further sustainability. If you gain a solid understanding of web publishing and the ways in which CSS works with the overall markup language of the page (be it XHTML or HTML5), you will be in a good position if you decide you want to move from XHTML to HTML5.

Summary

This chapter introduced the basics of what web pages are and how they work, including the history and differences between HTML and XHTML. You learned that coded HTML commands are included in a text file, and that typing HTML text yourself is better than using a graphical editor to create HTML commands for you—especially when you’re learning HTML.

You were introduced to the most basic and important HTML tags. By adding these coded commands to any plain-text document, you can quick- ly transform it into a bona fide web page. You learned that the first step in creating a web page is to put a few obligatory HTML tags at the beginning and end, including a title for the page. You then mark where paragraphs and lines end and add horizontal rules and headings if you want them.

Table 2.1 summarizes all the tags introduced in this chapter.
TagFunction
<html>…</html>Encloses the entire HTML document.
<head>…</head> Encloses the head of the HTML document. Used with-
in the <html> tag pair.
<title>…</title>Indicates the title of the document. Used within the
<head> tag pair.
<body>…</body>Encloses the body of the HTML document. Used with-
in the <html> tag pair.
<p>…</p>A paragraph; skips a line between paragraphs.
<br />A line break.
<hr />A horizontal rule line.
<h1>…</h1>A first-level heading.
<h2>…</h2>A second-level heading.
<h3>…</h3>A third-level heading.
<h4>…</h4>A fourth-level heading (seldom used).
<h5>…</h5>A fifth-level heading (seldom used).
<h6>…</h6>A sixth-level heading (seldom used).

Finally, you learned about XML and XHTML, how they relate to HTML, and what HTML5 means in relation to what it is you’re learning here.

Q&A

Q. I’ve created a web page, but when I open the file in my web browser, I see all the text including the HTML tags. Sometimes I even see weird gobbledygook characters at the top of the page! What did I do wrong?

A. You didn’t save the file as plain text. Try saving the file again, being careful to save it as Text Only or ASCII Text. If you can’t quite figure out how to get your word processor to do that, don’t stress. Just type your HTML files in Notepad or TextEdit instead and everything should work just fine. (Also, always make sure that the filename of your web page ends in .html or .htm.)

Q. I’ve seen web pages on the Internet that don’t have <html> tags at the beginning. You said pages always have to start with <html>. What’s the deal?

A. Many web browsers will forgive you if you forget to include the <html> tag and will display the page correctly anyway. However, it’s a very good idea to include it because some software does need it to identify the page as valid HTML. Besides, you want your pages to be bona fide XHTML pages so that they conform to the latest web standards.

Workshop

The workshop contains quiz questions and exercises to help you solidify your understanding of the material covered. Try to answer all questions before looking at the “Answers” section that follows.

Quiz

  1. What four tags are required in every HTML page?
  2. What HTML tags and text would you use to produce the following web content:
    .• A small heading with the words We are Proud to Present
    • A horizontal rule across the page
    • A large heading with the one word Orbit
    • A medium-sized heading with the words The Geometric Juggler
    • Another horizontal rule
  3. What code would you use to create a complete HTML web page with the title Foo Bar, a heading at the top that reads Happy Hour at the Foo Bar, followed by the words Come on down! in regular type?

Answers

  1. <html>, <head>, <title>, and <body> (along with their closing tags,

</html>, </head>, </title>, and </body>).

  • Your code would look like this:

<h3>We are Proud to Present</h3>

<hr />

<h1>Orbit</h1>

<h2>The Geometric Juggler</h2>

<hr />

  • Your code would look like this:

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

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”

“http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>

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

<head>

<title>Foo Bar</title>

</head>

<body>

<h1>Happy Hour at the Foo Bar</h1>

<p>Come on Down!</p>

</body> </html>

Exercises

• Even if your main goal in reading this book is to create web content for your business, you might want to make a personal web page just for practice. Type a few paragraphs to introduce yourself to the world and use the HTML tags you’ve learned in this chapter to make them into a web page.

• Throughout the book, you’ll be following along with the code examples and making pages of your own. Take a moment now to set up a basic document template containing the XML declaration, doctype declara- tion, and tags for the core HTML document structure. That way, you can be ready to copy and paste that information whenever you need it.

3. Understanding Cascading Style Sheets

In the previous chapter, you learned the basics of HTML and XHTML, including how to set up a skeletal HTML template for all your web con- tent. In this chapter, you will learn how to fine-tune the display of your web content using Cascading Style Sheets (CSS).

The concept behind style sheets is simple: You create a style sheet document that specifies the fonts, colors, spacing, and other characteristics that establish a unique look for a website. You then link every page that should have that look to the style sheet, instead of specifying all those styles repeatedly in each separate document. Therefore, when you decide to change your official corporate typeface or color scheme, you can modify all your web pages at once just by changing one or two entries in your style sheet rather than changing them in all of your static web files. So, a style sheet is a grouping of formatting instructions that controls the appearance of several HTML pages at once.

Style sheets enable you to set a great number of formatting characteristics, including exacting typeface controls, letter and line spacing, and margins and page borders, just to name a few. Style sheets also enable sizes and other measurements to be specified in familiar units, such as inches, millimeters, points, and picas. You can also use style sheets to precisely position graphics and text anywhere on a web page, either at specific coordinates or relative to other items on the page.

In short, style sheets bring a sophisticated level of display to the Web. And they do so—you’ll pardon the expression—with style.

How CSS Works

The technology behind style sheets is called CSS, which stands for Cascading Style Sheets. CSS is a language that defines style constructs such as fonts, colors, and positioning, which are used to describe how information on a web page is formatted and displayed. CSS styles can be stored directly in an HTML web page or in a separate style sheet file. Either way, style sheets contain style rules that apply styles to elements of a given type. When used externally, style sheet rules are placed in an external style sheet document with the file extension .css.

A style rule is a formatting instruction that can be applied to an element on a web page, such as a paragraph of text or a link. Style rules consist of one or more style properties and their associated values. An internal style sheet is placed directly within a web page, whereas an external style sheet exists in a separate document and is simply linked to a web page via a special tag— more on this tag in a moment.

The cascading part of the name CSS refers to the manner in which style sheet rules are applied to elements in an HTML document. More specifically, styles in a CSS style sheet form a hierarchy in which more specific styles override more general styles. It is the responsibility of CSS to determine the precedence of style rules according to this hierarchy, which establishes a cascading effect. If that sounds a bit confusing, just think of the cascading mechanism in CSS as being similar to genetic inheritance, in which general traits are passed from parents to a child, but more specific traits are entirely unique to the child. Base style rules are applied throughout a style sheet but can be overridden by more specific style rules.

A quick example should clear things up. Take a look at the following code to see whether you can tell what’s going on with the color of the text:

<div style=”color:green”> This text is green.

<p style=”color:blue”>This text is blue.</p>

<p>This text is still green.</p>

</div> In the previous example, the color green is applied to the <div> tag via the color style property. Therefore, the text in the <div> tag is colored green. Because both <p> tags are children of the <div> tag, the green text style cascades down to them. However, the first <p> tag overrides the color style and changes it to blue. The end result is that the first line (not surrounded by a paragraph tag) is green, the first official paragraph is blue, and the second official paragraph retains the cascaded green color.

If you made it through that description on your own, congratulations. If you understood it after I explained it in the text, congratulations to you as well. Understanding CSS isn’t like understanding rocket science, although many people will try to convince you that it is (so that they can charge high consultation fees, most likely!).

Like many web technologies, CSS has evolved over the years. The original version of CSS, known as Cascading Style Sheets Level 1 (CSS1) was created in 1996. The later CSS 2 standard was created in 1998, and CSS 2 is still in use today. All modern web browsers support CSS 2, and you can safely use CSS 2 style sheets without too much concern. So, when I talk about CSS throughout the book, I’m referring to CSS 2. You’ll find a complete reference guide to CSS at http://www.w3.org/Style/CSS/. The rest of this chapter explains how to put CSS to good use.

A Basic Style Sheet

Despite their intimidating power, style sheets can be simple to create. Consider the web pages shown in Figure 3.1 and Figure 3.2. These pages share several visual properties that could be put into a common style sheet:

  • They use a large, bold Verdana font for the headings and a normal size and weight Verdana font for the body text.
  • They use an image named logo.gif floating within the content and on the right side of the page.
  • All text is black except for subheadings, which are purple.
  • They have margins on the left side and at the top.
  • There is vertical space between lines of text. . The footnotes are centered and in small print.
FIGURE 3.1
This page uses a style sheet to fine-tune the appearance and spacing of the text and images.
FIGURE 3.2
This page uses the same style sheet as the one shown in Figure 3.1, thus maintaining a consistent look and feel.

LISTING 3.1     A Single External Style Sheet                  

body {
font-size: 10pt;
font-family: Verdana, Geneva, Arial, Helvetica, sans-serif; color: black;
line-height: 14pt; padding-left: 5pt; padding-right: 5pt; padding-top: 5pt;
}

h1 {
font: 14pt Verdana, Geneva, Arial, Helvetica, sans-serif; font-weight: bold;
line-height: 20pt;
}

p.subheader {
font-weight: bold; color: #593d87;
}

img {
padding: 3pt; float: right;
}

a {
text-decoration: none;
}

a:link, a:visited { color: #8094d6;
}

a:hover, a:active { color: #FF9933;
}

div.footer { font-size: 9pt;
font-style: italic; line-height: 12pt; text-align: center; padding-top: 30pt;
}

This might initially appear to be a lot of code, but if you look closely, you’ll see that there isn’t a lot of information on each line of code. It’s fairly standard to place individual style rules on their own line to help make style sheets more readable, but that is a personal preference; you could put all the rules on one line as long as you kept using the semicolon to separate each rule (more on that in a bit). Speaking of code readability, perhaps the first thing you noticed about this style sheet code is that it doesn’t look anything like normal HTML code. CSS uses a language all its own to specify style sheets.

Of course, the listing includes some familiar HTML tags. As you might guess, body, h1, p, img, a, and div in the style sheet refer to the corresponding tags in the HTML documents to which the style sheet will be applied. The curly braces after each tag name contain the specifications for how all content within that tag should appear.

In this case, the style sheet says that all body text should be rendered at a size of 10 points, in the Verdana font (if possible), with the color black, and 14 points between lines. If the user does not have the Verdana font installed, the list of fonts in the style sheet represents the order in which the browser should search for fonts to use: Geneva, then Arial, and then Helvetica. If the user has none of those fonts, the browser will use whatever default sans serif font is available. Additionally, the page should have left, right, and top margins of 5 points each.

Any text within an <h1> tag should be rendered in boldface Verdana at a size of 14 points. Moving on, any paragraph that uses only the <p> tag will inherit all the styles indicated by the body element. However, if the <p> tag uses a special class named sub header, the text will appear bold and, in the color, #593d87 (a purple color).

The pt after each measurement in Listing 3.1 means points (there are 72 points in an inch). If you prefer, you can specify any style sheet measurement in inches (in), centimeters (cm), pixels (px), or widths-of-a-letter-m, which are called ems (em).

You might have noticed that each style rule in the listing ends with a semicolon (;). Semicolons are used to separate style rules from each other. It is therefore customary to end each style rule with a semicolon, so you can easily add another style rule after it.

To link this style sheet to HTML documents, include a <link /> tag in the

<head> section of each document. Listing 3.2 shows the HTML code for the page shown in Figure 3.1. It contains the following <link /> tag: <link rel=”stylesheet” type=”text/css” href=”styles.css” />

This assumes that the style sheet is stored under the name styles.css in the same folder as the HTML document. As long as the web browser supports style sheets—and all modern browsers do support style sheets—the properties specified in the style sheet will apply to the content in the page without the need for any special HTML formatting code. This confirms the ultimate goal of XHTML, which is to provide a separation between the content in a web page and the specific formatting required to display that content.

LISTING 3.2     HTML Code for the Page Shown in Figure 3.1 

<?xml version=”1.0” encoding=”UTF-8”?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
“http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en”>
<head>
<title>About BAWSI</title>
<link rel=”stylesheet” type=”text/css” href=”styles.css” />
</head>
<body>
<h1>About BAWSI</h1>
<p><img src=”logo.gif” alt=”BAWSI logo”/>The Bay Area Women’s Sports Initiative (BAWSI) is a public benefit, nonprofit corporation with a mission to create programs and partnerships through which women athletes bring health, hope and wholeness to our community. Founded in 2005 by Olympic and World Cup soccer stars Brandi Chastain and Julie Foudy and Marlene Bjornsrud, former general manager of the San Jose CyberRays women’s professional soccer team, BAWSI provides a meaningful path for women athletes to become a more visible and valued part of the Bay Area sports culture.</p>
<p class=”subheader”>BAWSI’s History</p>
<p>The concept of BAWSI was inspired by one of the most spectacular achievements in women’s sports history and born out of one its biggest disappointments... </p>
<p><a href=”secondpage.html”>[continue reading]</a></p>
<div class=”footer”>Copyright &copy; 2005-2009 BAWSI (www.bawsi.org). All rights reserved. Used with permission.</div>
</body>
</html>

The code in Listing 3.2 is interesting because it contains no formatting of any kind. In other words, there is nothing in the HTML code that dictates how the text and images are to be displayed—no colors, no fonts, nothing. Yet the page is carefully formatted and rendered to the screen, thanks to the link to the external style sheet, styles.css. The real benefit to this approach is that you can easily create a site with multiple pages that maintains a consistent look and feel. And you have the benefit of isolating the visual style of the page to a single document (the style sheet) so that one change impacts all pages.

A CSS Style Primer

You now have a basic knowledge of CSS style sheets and how they are based on style rules that describe the appearance of information in web pages. The next few sections of this chapter provide a quick overview of some of the most important style properties and allow you to get started using CSS in your own style sheets. CSS includes various style properties that are used to control fonts, colors, alignment, and margins, to name just a few. The style properties in CSS can be generally grouped into two major categories:

  • Layout properties—Consist of properties that affect the positioning of elements on a web page, such as margins, padding, alignment, and so on
  • Formatting properties—Consist of properties that affect the visual display of elements within a website, such as the font type, size, color, and so on

Layout Properties

CSS layout properties are used to determine how content is placed on a web page. One of the most important layout properties is the display property, which describes how an element is displayed with respect to other elements. There are four possible values for the display property:

  • block—The element is displayed on a new line, as in a new paragraph.
  • list-item—The element is displayed on a new line with a list-item mark (bullet) next to it.
  • inline—The element is displayed inline with the current paragraph.
  • none—The element is not displayed; it is hidden.

It’s easier to understand the display property if you visualize each element on a web page occupying a rectangular area when displayed—the display property controls the manner in which this rectangular area is displayed. For example, the block value results in the element being placed on a new line by itself, whereas the inline value places the element next to the content just before it. The display property is one of the few style properties that can be applied in most style rules. Following is an example of how to set the display property:

display:block;

You control the size of the rectangular area for an element with the width and height properties. Like many size-related CSS properties, width and height property values can be specified in several different units of measurement:

  • in—Inches
  • cm—Centimeters
  • mm—Millimeters
  • px—Pixels
  • pt—Points

You can mix and match units however you choose within a style sheet, but it’s generally a good idea to be consistent across a set of similar style properties. For example, you might want to stick with points for font properties or pixels for dimensions. Following is an example of setting the width of an element using pixel units:

width: 200px;

Formatting Properties

CSS formatting properties are used to control the appearance of content on a web page, as opposed to controlling the physical positioning of the content. One of the most popular formatting properties is the border property, which is used to establish a visible boundary around an element with a box or partial box. The following border properties provide a means of describing the borders of an element:

  • border-width—The width of the border edge
  • border-color—The color of the border edge
  • border-style—The style of the border edge
  • border-left—The left side of the border
  • border-right—The right side of the border
  • border-top—The top of the border
  • border-bottom—The bottom of the border
  • border—All the border sides

The border-width property is used to establish the width of the border edge. It is often expressed in pixels, as the following code demonstrates:
border-width:5px;
Not surprisingly, the border-color and border-style properties are used to set the border color and style. Following is an example of how these two properties are set:
border-color:blue; border-style:dotted; The border-style property can be set to any of the following values:

  • solid—A single-line border
  • double—A double-line border
  • dashed—A dashed border
  • dotted—A dotted border
  • groove—A border with a groove appearance
  • ridge—A border with a ridge appearance
  • inset—A border with an inset appearance
  • outset—A border with an outset appearance . none—No border

The default value of the border-style property is none, which is why elements don’t have a border unless you set the border property to a different style. The most common border styles are the solid and double styles.

The border-left, border-right, border-top, and border-bottom properties enable you to set the border for each side of an element individually. If you want a border to appear the same on all four sides, you can use the single border property by itself, which expects the following styles separated by a space: border-width, border-style, and border-color.

Following is an example of using the border property to set a border that consists of two (double) red lines that are a total of 10 pixels in width:

border:10px double red;

Whereas the color of an element’s border is set with the border-color property, the color of the inner region of an element is set using the color and background-color properties. The color property sets the color of text in an element (foreground) and the background-color property sets the color of the background behind the text. Following is an example of setting both color properties to predefined colors:

color:black;

background-color:orange;

You can also assign custom colors to these properties by specifying the colors in hexadecimal (covered in more detail in Chapter 8, “Working with Colors, Images, and Multimedia”) or as RGB (Red, Green, Blue) decimal values, just as you do in HTML:

background-color:#999999; color:rgb(0,0,255);

You can also control the alignment and indentation of web page content without too much trouble. This is accomplished with the text-align and text-indent properties, as the following code demonstrates:

text-align:center; text-indent:12px;

After you have an element properly aligned and indented, you might be interested in setting its font. The following font properties are used to set the various parameters associated with fonts:

  • font-family—The family of the font
  • font-size—The size of the font
  • font-style—The style of the font (normal or italic)
  • font-weight—The weight of the font (light, medium, bold, and so on)

The font-family property specifies a prioritized list of font family names. A prioritized list is used instead of a single value to provide alternatives in case a font isn’t available on a given system. The font-size property specifies the size of the font using a unit of measurement, usually points.

Finally, the font-style property sets the style of the font and the font- weight property sets the weight of the font. Following is an example of setting these font properties:

font-family: Arial, sans-serif; font-size: 36pt;

font-style: italic; font-weight: medium;

Now that you know a whole lot more about style properties and how they work, refer back at Listing 3.1 and see whether it makes a bit more sense. Here’s a recap of the style properties used in that style sheet, which you can use as a guide for understanding how it works:

  • font—Lets you set many font properties at once. You can specify a list of font names separated by commas; if the first is not available, the next is tried, and so on. You can also include the words bold and/or italic and a font size. Each of these font properties can be specified separately with font-family, font-size, font-weight, and font-style if you prefer.
  • line-height—Also known in the publishing world as leading. This sets the height of each line of text, usually in points.
  • color—Sets the text color using the standard color names or hexa- decimal color codes (see Chapter 8 for more details).
  • text-decoration—Useful for turning link underlining off—simply set it to none. The values of underline, italic, and line-through are also supported. The application of styles to links is covered in more detail in Chapter 7, “Using External and Internal Links.”
  • text-align—Aligns text to the left, right, or center, along with justifying the text with a value of justify.
  • padding—Adds padding to the left, right, top, and bottom of an element; this padding can be in measurement units or a percentage of the page width. Use padding-left and padding-right if you want to add padding to the left and right of the element independently. Use padding-top or padding-bottom to add padding to the top or bottom of the element, as appropriate. You’ll learn more about these style proper- ties in Chapters 9, “Working with Margins, Padding, Alignment, and Floating,” and 10, “Understanding the CSS Box Model and Positioning.”

Using Style Classes

This is a “teach yourself” book, so you don’t have to go to a single class to learn how to give your pages great style, although you do need to learn what a style class is. Whenever you want some of the text on your pages to look different from the other text, you can create what amounts to a custom- built HTML tag. Each type of specially formatted text you define is called a style class. A style class is a custom set of formatting specifications that can be applied to any element in a web page.

Before showing you a style class, I need to take a quick step back and clarify some CSS terminology. First off, a CSS style property is a specific style that can be assigned a value, such as color or font-size. You associate a style property and its respective value with elements on a web page by using a selector. A selector is used to identify tags on a page to which you apply styles. Following is an example of a selector, a property, and a value all included in a basic style rule:

h1 { font: 36pt Courier; }

In this code, h1 is the selector, font is the style property, and 36pt Courier is the value. The selector is important because it means that the font setting will be applied to all h1 elements in the web page. But maybe you want to differentiate between some of the h1 elements—what then? The answer lies in style classes.

Suppose you want two different kinds of <h1> headings for use in your documents. You would create a style class for each one by putting the following CSS code in a style sheet:

h1.silly { font: 36pt Comic Sans; } h1.serious { font: 36pt Arial; }

Notice that these selectors include a period (.) after h1, followed by a descriptive class name. To choose between the two style classes, use the class attribute, like this:

<h1 class=”silly”>Marvin’s Munchies Inc. </h1> <p>Text about Marvin’s Munchies goes here. </p>

Or you could use this:

<h1 class=”serious”>MMI Investor Information</h1>

<p>Text for business investors goes here.</p>

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

What if you want to create a style class that could be applied to any ele- ment, rather than just headings or some other particular tag? You can asso- ciate a style class with the <div> tag, as in Listing 3.2, which is used to enclose any text in a block that is somewhat similar to a paragraph of text; the <div> tag is another useful container element.

You can essentially create your own custom HTML tag by using the div selector followed by a period (.) followed by any style class name you make up and any style specifications you choose. That tag can control any number of font, spacing, and margin settings all at once. Wherever you want to apply your custom tag in a page, use a <div> tag with the class attribute followed by the class name you created.

For example, the style sheet in Listing 3.1 includes the following style class specification:

div.footer { font-size: 9pt;

font-style: italic; line-height: 12pt; text-align: center; padding-top: 30pt;

}

This style class is applied in Listing 3.2 with the following tag:

<div class=”footer”>

Everything between that tag and the closing </div> tag in Listing 3.2 appears in 9-point, centered, italic text with 12-point vertical line spacing and 30 points of padding at the top of the element. What makes style classes so valuable is how they isolate style code from web pages, effectively allowing you to focus your HTML code on the actual content in a page, not how it is going to appear on the screen. Then you can focus on how the content is rendered to the screen by fine-tuning the style sheet. You might be surprised by how a relatively small amount of code in a style sheet can have significant effects across an entire website. This makes your pages much easier to maintain and manipulate.

Using Style IDs

When you create custom style classes, you can use those classes as many times as you would like—they are not unique. However, there will be some instances when you want to have precise control over unique elements for layout or formatting purposes (or both). In such instances, look to IDs instead of classes.

A style ID is a custom set of formatting specifications that can be applied only to one element in a web page. You can use IDs across a set of pages but only once per time within each page.

For example, suppose you have a title within the body of all your pages. Each page has only one title, but all the pages themselves include one instance of that title. Following is an example of a selector with an ID indicated, plus a property and a value:

p#title {font: 24pt Verdana, Geneva, Arial, sans-serif}

Notice that this selector includes a hash mark, or pound sign (#), after p, followed by a descriptive ID name. When referencing a style ID in HTML code, simply specify the ID name in the id attribute of an element, like so:

<p id=”title”>Some Title Goes Here</p> Everything between the opening and closing <p> tags will appear in 24- point Verdana text—but only once on any given page. You will often see style IDs used to define specific parts of a page for layout purposes, such as a header area, footer area, main body area, and so on. These types of areas in a page will appear only once per page, so using an ID rather than a class is the appropriate choice.

Internal Style Sheets and Inline Styles

In some situations, you might want to specify styles that will be used in only one web page, in which case you can enclose a style sheet between

<style> and </style> tags and include it directly in an HTML document.

Style sheets used in this manner must appear in the <head> of an HTML document. No <link /> tag is needed, and you cannot refer to that style sheet from any other page (unless you copy it into the beginning of that document, too). This kind of style sheet is known as an internal style sheet, as you learned earlier in the chapter.

Listing 3.3 shows an example of how you might specify an internal style sheet.

LISTING 3.3     A Web Page with an Internal Style Sheet                          

<?xml version=”1.0” encoding=”UTF-8”?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
“http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en”>
<head>
<title>Some Page</title>

<style type=”text/css”> div.footer {
font-size: 9pt; line-height: 12pt; text-align: center;
}
</style>
</head>
<body>
...
<div class=”footer”>
Copyright 2009 Acme Products, Inc.
</div>
</body>
</html>

In the listing code, the div.footer style class is specified in an internal style sheet that appears in the head of the page. The style class is now available for use within the body of this page. And, in fact, it is used in the body of the page to style the copyright notice.

Internal style sheets are handy if you want to create a style rule that is used multiple times within a single page. However, in some instances you might need to apply a unique style to one particular element. This calls for an inline style rule, which allows you to specify a style for only a small part of a page, such as an individual element. For example, you can create and apply a style rule within a <p>, <div>, or <span> tag via the style attribute. This type of style is known as an inline style because it is specified right there in the middle of the HTML code.

Here’s how a sample style attribute might look:
<p style=”color:green”>
This text is green, but <span style=”color:red”>this text is red.</span>
Back to green again, but…
</p>
<p>…now the green is over, and we’re back to the default color for this page.
</p>

This code makes use of the <span> tag to show how to apply the color style property in an inline style rule. In fact, both the <p> tag and the <span> tag in this example use the color property as an inline style. What’s important to understand is that the color:red style property over- rides the color:green style property for the text appearing between the <span> and </span> tags. Then in the second paragraph, neither of the color styles applies because it is a completely new paragraph that adheres to the default color of the entire page.

FIGURE 3.3
The W3C CSS Validator shows there are no errors in the style sheet contents of Listing 3.1.

Summary

In this chapter, you learned that a style sheet can control the appearance of many HTML pages at once. It can also give you extremely precise control over the typography, spacing, and positioning of HTML elements. You also discovered that by adding a style attribute to almost any HTML tag, you can control the style of any part of an HTML page without referring to a separate style sheet document.

You learned about three main approaches to including style sheets in your website: a separate style sheet file with the extension .css that is linked to in the <head> of your documents, a collection of style rules placed in the head of the document within the <style> tag, and as rules placed directly in an HTML tag via the style attribute.

Table 3.1 summarizes the tags discussed in this chapter. Refer to the CSS 2 style sheet standards at http://www.w3c.org for details on what options can be included after the <style> tag or the style attribute.

TABLE 3.1    HTML Tags and Attributes Covered in Chapter 3.

Tag/AttributesFunction
<style>…</style>Allows an internal style sheet to be included within a document. Used between <head> and </head>.
Attribute
type=”contenttype”The Internet content type. (Always “text/css” for a CSS style sheet.)
<link />Links to an external style sheet (or other document type). Used in the <head> section of the document.
Attribute
href=”url”The address of the style sheet
type=”contenttype”The Internet content type. (Always “text/css” for a CSS style sheet.)
rel=”stylesheet”The link type. (Always “stylesheet” for style sheets.)
<span>…</span>Does nothing but provide a place to put style or other attributes. (Similar to <div>…</div> but does not cause a line break.)
Attribute
style=”style”Includes inline style specifications. (Can be used in <span>, <div>, <body>, and most other HTML tags.)

Q&A

Q. Say I link a style sheet to my page that says all text should be blue, but there’s a <span style=”font-color:red”> tag in the page some- where. Will that text display as blue or will it display as red?

A. Red. Local inline styles always take precedence over external style sheets. Any style specifications you put between <style> and

</style> tags at the top of a page will also take precedence over external style sheets (but not over inline styles later in the same page). This is the cascading effect of style sheets that I mentioned earlier in the chapter. You can think of cascading style effects as starting with an external style sheet, which is overridden by an internal style sheet, which is overridden by inline styles.

Q. Can I link more than one style sheet to a single page?

A. Sure. For example, you might have a sheet for formatting (text, fonts, colors, and so on) and another one for layout (margins, padding, alignment, and so on)—just include a <link /> for both. Technically speaking, the CSS standard requires web browsers to give the user the option to choose between style sheets when multiple sheets are presented via multiple <link /> tags. However, in practice, all major web browsers simply include every style sheet. The preferred technique for linking in multiple style sheets involves using the special @import command. Following is an example of importing multiple style sheets with @import:

@import url(styles1.css); @import url(styles2.css);

Similar to the <link /> tag, the @import command must be placed in the head of a web page. You learn more about this handy little command in Chapter 25, “Creating Print-Friendly Web Pages,” when you learn how to create a style sheet specifically for printing web pages.

Workshop

The workshop contains quiz questions and exercises to help you solidify your understanding of the material covered. Try to answer all questions before looking at the “Answers” section that follows.

Quiz

  1. What code would you use to create a style sheet to specify 30-point blue Arial headings and all other text in double-spaced, 10-point blue Times Roman (or the default browser font)?
  2. If you saved the style sheet you made for Question 1 as corporate.css, how would you apply it to a web page named intro.html?
  3. How many different ways are there to ensure style rules can be applied to your content?

Answers

  1. Your style sheet would include the following:

h1 { font: 30pt blue Arial; } body { font: 10pt blue; }

  • Put the following tag between the <head> and </head> tags of the

intro.html document:

<link rel=”stylesheet” type=”text/css” href=”corporate.css” />

  • Three: externally, internally, and inline.

Exercises

. Using the style sheet you created earlier in this chapter, add some style classes to your style sheet. To see the fruits of your labor, apply those classes to the HTML page you created as well. Use classes with your

<h1> and <p> tags to get the feel for things.

. Develop a standard style sheet for your website and link it into all your pages. (Use internal style sheets and/or inline styles for pages that need to deviate from it.) If you work for a corporation, chances are it has already developed font and style specifications for printed materials. Get a copy of those specifications and follow them for company web pages, too.

. Be sure to explore the official style sheet specs at http://www.w3.org/ Style/CSS/ and try some of the more esoteric style properties not covered in this chapter.

4.Understanding JavaScript

The World Wide Web (WWW) began as a text-only medium—the first browsers didn’t even support images within web pages. The Web has come a long way since those early days, as today’s websites include a wealth of visual and interactive features in addition to useful content: graphics, sounds, animation, and video. Web scripting languages, such as JavaScript, are one of the easiest ways to spice up a web page and to inter- act with users in new ways.

The first part of this chapter introduces the concept of Web scripting and the JavaScript language. As the chapter moves ahead, you’ll learn how to include JavaScript commands directly in your HTML documents and how your scripts will be executed when the page is viewed in a browser. You will work with a simple script, edit it, and test it in your browser, all the while learning the basic tasks involved in creating and using JavaScript scripts.

Learning Web Scripting Basics

In the world of science fiction movies (and many other movies that have no excuse), computers are often seen obeying commands in English.
Although this might indeed happen in the near future, computers currently find it easier to understand languages such as BASIC, C, and Java.

You already know how to use one type of computer language: HTML. You use HTML tags to describe how you want your document formatted, and the browser obeys your commands and shows the formatted document to the user. But because HTML is a simple text markup language, it can’t respond to the user, make decisions, or automate repetitive tasks. Interactive tasks such as these require a more sophisticated language: a programming language, or a scripting language.

Although many programming languages are complex, scripting languages are generally simple. They have a simple syntax, can perform tasks with a minimum of commands, and are easy to learn. Web scripting languages enable you to combine scripting with HTML to create interactive web pages.

Scripts and Programs

A movie or a play follows a script—a list of actions (or lines) for the actors to perform. A web script provides the same type of instructions for the web browser. A script in JavaScript can range from a single line to a full-scale application. (In either case, JavaScript scripts usually run within a browser.)

Some programming languages must be compiled, or translated, into machine code before they can be executed. JavaScript, on the other hand, is an interpreted language: The browser executes each line of script as it comes to it.

There is one main advantage to interpreted languages: Writing or changing a script is very simple. Changing a JavaScript script is as easy as changing a typical HTML document, and the change is enacted as soon as you reload the document in the browser.

Introducing JavaScript

JavaScript was developed by Netscape Communications Corporation, the maker of the Netscape web browser. JavaScript was the first web scripting language to be supported by browsers, and it is still by far the most popular.

JavaScript is almost as easy to learn as HTML, and it can be included directly in HTML documents. Here are a few of the things you can do with JavaScript:

  • Display messages to the user as part of a web page, in the browser’s status line, or in alert boxes
  • Validate the contents of a form and make calculations (for example, an order form can automatically display a running total as you enter item quantities)
  • Animate images or create images that change when you move the mouse over them.
  • Create ad banners that interact with the user, rather than simply displaying a graphic.
  • Detect the browser in use or its features and perform advanced functions only on browsers that support them.
  • Detect installed plug-ins and notify the user if a plug-in is required.
  • Modify all or part of a web page without requiring the user to reload it.
  • Display or interact with data retrieved from a remote server.

You can do all this and more with JavaScript, including creating entire applications. We’ll explore the uses of JavaScript throughout this book.

How JavaScript Fits into a Web Page

Using the <script> tag, you can add a short script (in this case, just one line) to a web document, as shown in Listing 4.1. The <script> tag tells the browser to start treating the text as a script, and the closing </script> tag tells the browser to return to HTML mode. In most cases, you can’t use JavaScript statements in an HTML document except within <script> tags. The exception is event handlers, described later in this chapter.

LISTING 4.1        A Simple HTML Document with a Simple Script

<?xml version=”1.0” encoding=”UTF-8”?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
“http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en”>
<head>
<title>The American Eggplant Society</title>
</head>

<body>
<h1>The American Eggplant Society</h1>
<p>Welcome to our site. Unfortunately, it is still under construction.</p>
<p>We last worked on it on this date:
<script type=”text/javascript”>
<!-- Hide the script from old browsers document.write(document.lastModified);
// Stop hiding the script -->
</script>
</p>
</body>
</html>

JavaScript’s document.write statement, which you’ll learn more about later, sends output as part of the web document. In this case, it displays the modification date of the document, as shown in Figure 4.1

FIGURE 4.1
Using document.write to display a last-modified date.

In this example, we placed the script within the body of the HTML document. There are actually four different places where you might use scripts:

  • In the body of the page—In this case, the script’s output is displayed as part of the HTML document when the browser loads the page.
  • In the header of the page between the <head> tags—Scripts in the header can’t create output within the HTML document, but can be referred to by other scripts. The header is often used for functions— groups of JavaScript statements that can be used as a single unit. You will learn more about functions in Chapter 14, “Getting Started with JavaScript Programming.”
  • Within an HTML tag, such as <body> or <form>—This is called an event handler and enables the script to work with HTML elements. When using JavaScript in event handlers, you don’t need to use the <script> tag. You’ll learn more about event handlers in Chapter 14.
  • In a separate file entirely—JavaScript supports the use of files with the .js extension containing scripts; these can be included by specifying a file in the <script> tag.

Using Separate JavaScript Files

When you create more complicated scripts, you’ll quickly find your HTML documents become large and confusing. To avoid this, you can use one or more external JavaScript files. These are files with the .js extension that contain JavaScript statements.

External scripts are supported by all modern browsers. To use an external script, you specify its filename in the <script> tag:

<script type=”text/javascript” src=”filename.js”></script>

Because you’ll be placing the JavaScript statements in a separate file, you don’t need anything between the opening and closing <script> tags—in fact, anything between them will be ignored by the browser.

You can create the .js file using a text editor. It should contain one or more JavaScript commands and only JavaScript—don’t include <script> tags, other HTML tags, or HTML comments. Save the .js file in the same directo- ry as the HTML documents that refer to it.

Understanding JavaScript Events

Many of the useful things you can do with JavaScript involve interacting with the user and that means responding to events—for example, a link or a button being clicked. You can define event handlers within HTML tags to tell the browser how to respond to an event. For example, Listing 4.2 defines a button that displays a message when clicked.

LISTING 4.2     A Simple Event Handler                                                 

<?xml version=”1.0” encoding=”UTF-8”?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
“http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en”>
<head>
<title>Event Test</title>
</head>

<body>
<h1>Event Test</h1>
<button type=”button”
onclick=”alert(‘You clicked the button.’)”> Click Me!</button>
</body>
</html>

In various places throughout this book, you’ll learn more about JavaScript’s event model and how to create simple and complex event handlers.

Exploring JavaScript’s Capabilities

If you’ve spent any time browsing the Web, you’ve undoubtedly seen lots of examples of JavaScript in action. Here are some brief descriptions of typical applications for JavaScript, all of which you’ll explore further, later in this book.

Improving Navigation

Some of the most common uses of JavaScript are in navigation systems for websites. You can use JavaScript to create a navigation tool—for example, a drop-down menu to select the next page to read or a submenu that pops up when you hover over a navigation link.

When it’s done right, this kind of JavaScript interactivity can make a site easier to use, while remaining usable for browsers that don’t support JavaScript.

Validating Forms

Form validation is another common use of JavaScript. A simple script can read values the user types into a form and can make sure they’re in the right format, such as with ZIP Codes or phone numbers. This allows users to notice common errors and fix them without waiting for a response from the web server. You’ll learn how to work with form data in Chapter 26, “Working with Web-Based Forms.”

Special Effects

One of the earliest and most annoying uses of JavaScript was to create attention-getting special effects—for example, scrolling a message in the browser’s status line or flashing the background color of a page. These techniques have fortunately fallen out of style, but thanks to the W3C DOM and the latest browsers, some more impressive effects are possible with JavaScript—for example, creating objects that can be dragged and dropped on a page or creating fading transitions between images in a slideshow.

Remote Scripting (AJAX)

For a long time, the biggest limitation of JavaScript was that there was no way for it to communicate with a web server. For example, you could use it to verify that a phone number had the right number of digits, but not to look up the user’s location in a database based on the number.

Now that some of JavaScript’s advanced features are supported by most browsers, this is no longer the case. Your scripts can get data from a server without loading a page or send data back to be saved. These features are collectively known as AJAX (Asynchronous JavaScript and XML), or remote scripting. You’ll learn how to develop AJAX scripts in Chapter 24, “AJAX: Remote Scripting.”

You’ve seen AJAX in action if you’ve used Google’s Gmail mail application or recent versions of Yahoo! Mail or Microsoft Hotmail. All of these use remote scripting to present you with a responsive user interface that works with a server in the background.

Displaying Time with JavaScript

One common and easy use for JavaScript is to display dates and times. Because JavaScript runs on the browser, the times it displays will be in the user’s current time zone. However, you can also use JavaScript to calculate “universal” (UTC) time.

As a basic introduction to JavaScript, you will now create a simple script that displays the current time and the UTC time within a web page, starting with the next section.

Beginning the Script

Your script, like most JavaScript programs, begins with the HTML

<script> tag. As you learned earlier in this chapter, you use the <script>

and </script> tags to enclose a script within the HTML document.

To begin creating the script, open your favorite text editor and type the beginning and ending <script> tags as shown. <script type=”text/javascript”></script>

Adding JavaScript Statements

Your script now needs to determine the local and UTC times, and then dis- play them to the browser. Fortunately, all the hard parts, such as convert- ing between date formats, are built in to the JavaScript interpreter.

Storing Data in Variables

To begin the script, you will use a variable to store the current date. You will learn more about variables in Chapter 16, “Using JavaScript Variables, Strings, and Arrays.” A variable is a container that can hold a value—a number, some text, or in this case, a date.

To start writing the script, add the following line after the first <script> tag. Be sure to use the same combination of capital and lowercase letters in your version because JavaScript commands and variable names are case sensitive.
now = new Date();

This statement creates a variable called now and stores the current date and time in it. This statement and the others you will use in this script use JavaScript’s built-in Date object, which enables you to conveniently handle dates and times. You’ll learn more about working with dates in Chapter 17, “Using JavaScript Functions and Objects.”

Calculating the Results

Internally, JavaScript stores dates as the number of milliseconds since January 1, 1970. Fortunately, JavaScript includes a number of functions to convert dates and times in various ways, so you don’t have to figure out how to convert milliseconds to day, date, and time.

To continue your script, add the following two statements before the final

</script> tag:

localtime = now.toString(); utctime = now.toGMTString(); These statements create two new variables: localtime, containing the cur- rent time and date in a nice readable format, and utctime, containing the UTC equivalent.

Creating Output

You now have two variables—localtime and utctime—which contain the results we want from our script. Of course, these variables don’t do us much good unless we can see them. JavaScript includes a number of ways to display information, and one of the simplest is the document.write statement.

The document.write statement displays a text string, a number, or any- thing else you throw at it. Because your JavaScript program will be used within a web page, the output will be displayed as part of the page. To dis- play the result, add these statements before the final </script> tag:

document.write(“<strong>Local time:</strong> “ + localtime + “<br/>”); document.write(“<strong>UTC time:</strong> “ + utctime);

These statements tell the browser to add some text to the web page containing your script. The output will include some brief strings introducing the results and the contents of the localtime and utctime variables.

Notice the HTML tags, such as <strong>, within the quotation marks— because JavaScript’s output appears within a web page, it needs to be for- matted using HTML. The <br/> tag in the first line ensures that the two times will be displayed on separate lines.

Adding the Script to a Web Page

You should now have a complete script that calculates a result and dis- plays it. Your listing should match Listing 4.3.

LISTING 4.3        The Complete Date and Time Script

<script type=”text/javascript”> now = new Date();
localtime = now.toString(); 
utctime = now.toGMTString();
document.write(“<strong>Local time:</strong> “ + localtime + “<br/>”); 
document.write(“<strong>UTC time:</strong> “ + utctime);
</script>

To use your script, you’ll need to add it to an HTML document. If you use the general template you’ve seen in the chapters so far, you should end up with something like Listing 4.4.

LISTING 4.4        The Date and Time Script in an HTML Document

<?xml version=”1.0” encoding=”UTF-8”?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
“http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en”>
<head>
<title>Displaying Times and Dates</title>
</head>

<body>
<h1>Current Date and Time</h1>
<script type=”text/javascript”> now = new Date();
localtime = now.toString(); utctime = now.toGMTString();
document.write(“<strong>Local time:</strong> “
 + localtime + “<br/>”); 
document.write(“<strong>UTC time:</strong> “ + utctime);
</script>
</body>
</html>

Now that you have a complete HTML document, save it with the .htm or .html extension.

Testing the Script

To test your script, you simply need to load the HTML document you created in a web browser. If you typed the script correctly, your browser should display the result of the script, as shown in Figure 4.2. (Of course, your result won’t be the same as mine, but it should be the same as the set- ting of your computer’s clock.)
A note about Internet Explorer 6.0 and above: Depending on your security settings, the script might not execute, and a yellow highlighted bar on the top of the browser might display a security warning. In this case, click the yellow bar and select Allow Blocked Content to allow your script to run. (This happens because the default security settings allow JavaScript in online documents, but not in local files.)

Modifying the Script

Although the current script does indeed display the current date and time, its display isn’t nearly as attractive as the clock on your wall or desk. To remedy that, you can use some additional JavaScript features and a bit of HTML to display a large clock.

FIGURE 4.2
Firefox displays the results of the Date and Time script.

To display a large clock, we need the hours, minutes, and seconds in separate variables. Once again, JavaScript has built-in functions to do most of the work:

hours = now.getHours(); mins = now.getMinutes(); secs = now.getSeconds();

These statements load the hours, mins, and secs variables with the compo- nents of the time using JavaScript’s built-in date functions.

After the hours, minutes, and seconds are in separate variables, you can create document.write statements to display them:

document.write(“<h1>”);

document.write(hours + “:” + mins + “:” + secs); document.write(“</h1>”);

The first statement displays an HTML <h1> header tag to display the clock in a large typeface. The second statement displays the hours, mins, and secs variables, separated by colons, and the third adds the closing </h1> tag.

You can add the preceding statements to the original date and time script to add the large clock display. Listing 4.5 shows the complete modified version of the script.

LISTING 4.5     The Date and Time Script with Large Clock Display

<?xml version=”1.0” encoding=”UTF-8”?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
“http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en”>
<head>
<title>Displaying Times and Dates</title>
</head>

<body>
<h1>Current Date and Time</h1>
<script type=”text/javascript”> now = new Date();
localtime = now.toString(); utctime = now.toGMTString();
document.write(“<strong>Local time:</strong> “
+ localtime + “<br/>”);
document.write(“<strong>UTC time:</strong> “ + utctime); 
hours = now.getHours();
mins = now.getMinutes(); secs = now.getSeconds(); 
document.write(“<h1>”);
document.write(hours + “:” + mins + “:” + secs);
document.write(“</h1>”);
</script>
</body>
</html>

Now that you have modified the script, save the HTML file and open the modified file in your browser. If you left the browser running, you can simply use the Reload button to load the new version of the script. Try it and verify that the same time is displayed in both the upper portion of the window and the new large clock. Figure 4.3 shows the results.

Dealing with JavaScript Errors

As you develop more complex JavaScript applications, you’re going to run into errors from time to time. JavaScript errors are usually caused by mistyped JavaScript statements.

To see an example of a JavaScript error message, modify the statement you added in the previous section. We’ll use a common error: omitting one of the parentheses. Change the last document.write statement in Listing 4.5 to read:

document.write(“</h1>”;

FIGURE 4.3
Firefox displays the modified Date and Time script.

Save your HTML document again and load the document into the browser. Depending on the browser version you’re using, one of two things will happen: Either an error message will be displayed, or the script will simply fail to execute.

If an error message is displayed, you’re halfway to fixing the problem by adding the missing parenthesis. If no error was displayed, you should con- figure your browser to display error messages so that you can diagnose future problems:

• In Firefox, you can also select Tools, JavaScript Console from the menu. The console is shown in Figure 4.4, displaying the error mes- sage you created in this example.

• In Chrome, select Tools, JavaScript Console from the Customizations (Options) menu. A console will display in the bottom of the browser window.

• In Internet Explorer, select Tools, Internet Options. On the Advanced page, uncheck the Disable Script Debugging box and check the Display a Notification About Every Script Error box. (If this is dis- abled, a yellow icon in the status bar will still notify you of errors.)

The error we get in this case is missing ) after argument list (Firefox) or Expected ‘)’ (Internet Explorer), which turns out to be exactly the problem. Be warned, however, that error messages aren’t always this enlightening.

FIGURE 4.4
Firefox’s JavaScript Console displays an error message.

Although Internet Explorer displays error dialog boxes for each error, Firefox’s JavaScript Console displays a single list of errors and enables you to test commands. For this reason, you might find it useful to install Firefox for debugging and testing JavaScript, even if Internet Explorer is your primary browser.

Summary

During this chapter, you’ve learned what web scripting is and what JavaScript is. You’ve also learned how to insert a script into an HTML document or refer to an external JavaScript file, what sorts of things JavaScript can do, and how JavaScript differs from other web languages. You also wrote a simple JavaScript program and tested it using a web browser. You discovered how to modify and test scripts and what happens when a JavaScript program runs into an error.

In the process of writing this script, you have used some of JavaScript’s basic features: variables, the document.write statement, and functions for working with dates and times. Now that you’ve learned a bit of JavaScript syntax, you’re ready to continue on to learn all manner and sorts of things about web development before settling in to write interactive websites using client-side scripting.

Q&A

Q. Do I need to test my JavaScript on more than one browser?

A. In an ideal world, any script you write that follows the standards for JavaScript will work in all browsers, and 93% of the time (give or take) that’s true in the real world. But browsers do have their quirks, and you should test your scripts on Internet Explorer and Firefox at a minimum.

Q. If I plan to learn PHP or some other server-side programming lan- guage anyway, will I have any use for JavaScript?

A. Certainly. JavaScript is the ideal language for many parts of a web- based application, such as form validation. Although PHP and other server-side languages have their uses, they can’t interact directly with the user on the client-side.

Q. When I try to run my script, the browser displays the actual script in the browser window instead of executing it. What did I do wrong?

A. This is most likely caused by one of three errors. First, you might be missing the beginning or ending <script> tags. Check them, and verify that the first reads <script type=”text/javascript”>. Second, your file might have been saved with a .txt extension, causing the browser to treat it as a text file. Rename it to .htm or .html to fix the problem. Third, make sure your browser supports JavaScript and that it is not disabled in the Preferences dialog.

Q. Why are the <strong> and <br /> tags allowed in the statements to print the time? I thought HTML tags weren’t allowed within the

<script> tags.

A. Because this particular tag is inside quotation marks, it’s considered a valid part of the script. The script’s output, including any HTML tags, is interpreted and displayed by the browser. You can use other HTML tags within quotation marks to add formatting, such as the <h1> tags we added for the large clock display.

Workshop

The workshop contains quiz questions and exercises to help you solidify your understanding of the material covered. Try to answer all questions before looking at the “Answers” section that follows.

Quiz

  1. When a user views a page containing a JavaScript program, which machine actually executes the script?
    1. The user’s machine running a web browser
    1. The web server
    1. A central machine deep within Netscape’s corporate offices
  • What software do you use to create and edit JavaScript programs?
    • A browser
    • A text editor
    • A pencil and a piece of paper
  • What are variables used for in JavaScript programs?
    • Storing numbers, dates, or other values
    • Varying randomly
    • Causing high school algebra flashbacks
  • What should appear at the very end of a JavaScript script embedded in an HTML file?
    • The <script type=”text/javascript”> tag
    • The </script> tag
    • The END statement

Answers

  1. a. JavaScript programs execute on the web browser. (There is actually a server-side version of JavaScript, but that’s another story.)
  2. b. Any text editor can be used to create scripts. You can also use a word processor if you’re careful to save the document as a text file with the .html or .htm extension.
  3. a. Variables are used to store numbers, dates, or other values.
  4. b. Your script should end with the </script> tag.

Exercises

Add a millisecond field to the large clock. You can use the getMilliseconds function, which works just like getSeconds but returns milliseconds.

Modify the script to display the time, including milliseconds, twice. Notice whether any time passes between the two time displays when you load the page.

5. Working with
Fonts, Text Blocks,
and Lists

In the early days of the Web, text was displayed in only one font and in one size. However, a combination of HTML and CSS now makes it possible to control the appearance of text (font type, size, or color) and how it is aligned and displayed on a web page. In this chapter, you’ll learn how to change the visual display of the font—its font family, size, and weight— and how to incorporate boldface, italics, superscripts, subscripts, and strikethrough text into your pages. You will also learn how to change type- faces and font sizes. Then, after becoming conversant in these textual aspects, you’ll learn the basics of text alignment and some advanced text tips and tricks, such as the use of lists. Because lists are so common, HTML provides tags that automatically indent text and add numbers, bullets, or other symbols in front of each listed item. You’ll learn how to format different types of lists, which are part of the many ways to display content in your website.

Boldface, Italics, and Special Text Formatting

Way back in the age of the typewriter, we were content with a plain-text display and with using an occasional underline to show emphasis. Today, boldface and italic text have become de rigueur in all paper communication. Naturally, you can add bold and italic text to your web content as well. There are several tags and style rules that make text formatting possible.

The old school approach to adding bold and italic formatting to text involves the <b></b> and <i></i> tag pairs. For boldface text, put the <b> tag at the beginning of the text and </b> at the end. Similarly, you can make any text italic by enclosing it between <i> and </i> tags. Although this approach still works fine in browsers and is supported by XHTML, it isn’t as flexible or powerful as the CSS style rules for text formatting.

Although you’ll learn much more about CSS style rules in Part III, “Advanced Web Page Design with CSS,” it’s worth a little foreshadowing just so that you understand the text formatting options. The font-weight style rule enables you to set the weight, or boldness, of a font using a style rule. Standard settings for font-weight include normal, bold, bolder, and lighter (with normal being the default). Italic text is controlled via the font-style rule, which can be set to normal, italic, or oblique. Style rules can be specified together if you want to apply more than one, as the following example demonstrates:

<p style=”font-weight:bold; font-style:italic”>This paragraph is bold and italic!</p>

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

<p> tag. The key to using multiple style rules is that they must be separated by a semicolon (;).

You aren’t limited to using font styles in paragraphs, however. The following code shows how to italicize text in a bulleted list:

<ul>

<li style=”font-style:italic”>Important Stuff</li>

<li style=”font-style:italic”>Critical Information</li>

<li style=”font-style:italic”>Highly Sensitive Material</li>

<li>Nothing All That Useful</li>

</ul>

You can also use the font-weight style rule within headings, but a heavier font usually doesn’t have an effect on headings because they are already bold by default.

Although using CSS enables you to apply richer formatting, there are a few other HTML tags that are good for adding special formatting to text when you don’t necessarily need to be as specific as CSS allows you to be. Following are some of these tags. Listing 5.1 and Figure 5.1 demonstrate each tag in action.

. <small></small>—Small text

. <big></big>—Big text; not present in HTML5 because text size is better controlled by CSS

. <sup></sup>—Superscript text

. <sub></sub>—Subscript text

. <em></em> or <i></i>—Emphasized (italic) text

. <strong></strong> or <b></b>—Strong (boldface) text

Although you’ll learn much more about CSS style rules in Part III, “Advanced Web Page Design with CSS,” it’s worth a little foreshadowing just so that you understand the text formatting options. The font-weight style rule enables you to set the weight, or boldness, of a font using a style rule. Standard settings for font-weight include normal, bold, bolder, and lighter (with normal being the default). Italic text is controlled via the font-style rule, which can be set to normal, italic, or oblique. Style rules can be specified together if you want to apply more than one, as the following example demonstrates:

<p style=”font-weight:bold; font-style:italic”>This paragraph is bold and italic!</p>

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

<p> tag. The key to using multiple style rules is that they must be separat- ed by a semicolon (;).

You aren’t limited to using font styles in paragraphs, however. The following code shows how to italicize text in a bulleted list:

<ul>

<li style=”font-style:italic”>Important Stuff</li>

<li style=”font-style:italic”>Critical Information</li>

<li style=”font-style:italic”>Highly Sensitive Material</li>

<li>Nothing All That Useful</li>

</ul>

You can also use the font-weight style rule within headings, but a heavier font usually doesn’t have an effect on headings because they are already bold by default.

Although using CSS enables you to apply richer formatting, there are a few other HTML tags that are good for adding special formatting to text when you don’t necessarily need to be as specific as CSS allows you to be. Following are some of these tags. Listing 5.1 and Figure 5.1 demonstrate each tag in action.

  • <small></small>—Small text
  • <big></big>—Big text; not present in HTML5 because text size is better controlled by CSS
  • <sup></sup>—Superscript text
  • <sub></sub>—Subscript text
  • <em></em> or <i></i>—Emphasized (italic) text
  • <strong></strong> or <b></b>—Strong (boldface) text<tt></tt>—Monospaced text (typewriter font) not present in HTML5 because font appearance is better controlled by CSS . <pre></pre>—Monospaced text, preserving spaces and line breaks
FIGURE 5.1
Here’s what the character formatting from Listing 5.1 looks like.

LISTING 5.1        Special Formatting Tags

<?xml version=”1.0” encoding=”UTF-8”?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
“http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en”>
<head>
<title>The Miracle Product</title>
</head>

<body>
<p>
New <sup>Super</sup><strong>Strength</strong> H<sub>2</sub>O
<em>plus</em> will knock out any stain, <big>big</big> or
<small>small</small>.<br /> Look for new
<sup>Super</sup><b>Strength</b> H<sub>2</sub>O <i>plus</i> in a stream near you.
</p>
<p>
<tt>NUTRITION INFORMATION</tt> (void where prohibited)
</p>
<pre>
           Calories	  Grams	            USRDA
           /Serving       of Fat            Moisture
Regular	        3	    4	             100%
Unleaded	3	    2	             100%
Organic  	2	    3	             99%
Sugar Free	0	    1	             110%
</pre>
</body>
</html>

The <tt> tag usually changes the typeface to Courier New, a monospaced font. (Monospaced means that all the letters and spaces are the same width.) However, web browsers let users change the monospaced <tt> font to the typeface of their choice (look on the Options menu of your browser). The monospaced font might not even be monospaced for some users, although the vast majority of users stick with the standard fonts that their browsers show by default.

The <pre> tag causes text to appear in the monospaced font, but it also does something else unique and useful. As you learned in Chapter 2, “Understanding HTML and XHTML Connections,” multiple spaces and line breaks are normally ignored in HTML files, but <pre> causes exact spacing and line breaks to be preserved. For example, without <pre>, the text at the end of Figure 5.1 would look like the following:

calories grams usrda /serving of fat moisture regular

3 4 100% unleaded 3 2 100% organic 2 3 99% sugar free 0 1 110%

Even if you added <br /> tags at the end of every line, the columns wouldn’t line up properly. However, when you put <pre> at the beginning and </pre> at the end, the columns line up properly because the exact spaces are kept—no <br /> tags are needed. The <pre> tag gives you a quick and easy way to preserve the alignment of any monospaced text files you might want to transfer to a web page with minimum effort.

CSS provides you with more robust methods for lining up text (and doing anything with text, actually), and you’ll learn more about them throughout Part III.

Tweaking the Font

The <big>, <small>, and <tt> tags give you some rudimentary control over the size and appearance of the text on your pages. However, there might be times when you’d just like a bit more control over the size and appearance of your text. Before I get into the appropriate way to tinker with the font in XHTML code, let’s briefly look at how things were done prior to CSS because you might still find examples of this method when you look at the source code for other websites. Remember, just because these older methods are in use doesn’t mean you should follow suit.

Before style sheets entered the picture, the now phased-out <font> tag was used to control the fonts in web page text. For example, the following HTML will change the size and color of some text on a page:

<font size=”5” color=”purple”>this text will be big and purple.</font>

As you can see, the size and color attributes of the <font> tag made it possible to alter the font of the text without too much effort. Although this approach worked fine, it was replaced with a far superior approach to font formatting, thanks to CSS style rules. Following are a few of the main style rules used to control fonts:

. font-family—Sets the family (typeface) of the font

. font-size—Sets the size of the font

. color—Sets the color of the font

The font-family style rule enables you to set the typeface used to display text. You can and usually should specify more than one value for this style (separated by commas) so that if the first font isn’t available on a user’s system, the browser can try an alternative. You’ve already seen this in previous chapters.

Providing alternative font families is important because each user potentially has a different set of fonts installed, at least beyond a core set of common basic fonts (Arial, Times New Roman, and so forth). By providing a list of alternative fonts, you have a better chance of your pages gracefully falling back on a known font when your ideal font isn’t found. Following is an example of the font-family style used to set the typeface for a para- graph of text:

<p style=”font-family:arial, sans-serif, ‘times roman’”>

There are several interesting things about this example. First, arial is specified as the primary font. Capitalization does not affect the font family, so arial is no different from Arial or ARIAL. Another interesting thing about this code is how single quotes are used around the Times Roman font name because it has a space in it. However, because ’times roman’ appears after the generic specification of sans-serif, it is unlikely that ‘times roman’ would be used. Because sans-serif is in the second position, it says to the browser “if Arial is not on this machine, use the default sans-serif font.”

The font-size and color style rules are also commonly used to control the size and color of fonts. The font-size style can be set to a predefined size (such as small, medium, or large) or you can set it to a specific point size (such as 12pt or 14pt). The color style can be set to a predefined color (such as white, black, blue, red, or green), or you can set it to a specific hexadecimal color (such as #FFB499). Following is the previous paragraph example with the font size and color specified:

<p style=”font-family:arial, sans-serif, ‘times roman’; font-size:14pt; color:green”>

The sample web content in Listing 5.2 and shown in Figure 5.2 uses some font style rules to create the beginning of a basic online résumé

LISTING 5.2     Using Font Style Rules to Create a Basic Résumé

<?xml version=”1.0” encoding=”UTF-8”?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
“http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en”>
<head>
<title>R&eacute;sum&eacute; for Jane Doe</title>

<style type=”text/css”> body {
font-family: Verdana, sans-serif; font-size: 12px;
}

h1 {
font-family:Georgia, serif; font-size:28px;
text-align:center;
}

p.contactinfo { font-size:14px; text-align:center;
}

p.categorylabel { font-size:12px; font-weight:bold;
text-transform:uppercase;
}

div.indented { margin-left: 25px;
}
</style>
</head>
<body>
<h1>Jane Doe</h1>
<p class=”contactinfo”>1234 Main Street, Sometown, CA 93829<br/>
tel: 555-555-1212, e-mail: jane@doe.com</p>

<p class=”categorylabel”>Summary of Qualifications</p>
<ul>
<li>Highly skilled and dedicated professional offering a solid background in whatever it is you need.</li>
<li>Provide comprehensive direction for whatever it is that will get me a job.</li>
<li>Computer proficient in a wide range of industry-related computer programs and equipment. Any industry.</li>
</ul>

<p class=”categorylabel”>Professional Experience</p>
<div class=”indented”>
<p><span style=”font-weight:bold;”>Operations Manager, Super Awesome Company, Some City, CA [Sept 2002 – present]</span></p>
<ul>
<li>Direct all departmental operations</li>
<li>Coordinate work with internal and external resources</li>
<li>Generally in charge of everything</li>
</ul>
<p><span style=”font-weight:bold;”>Project Manager,
Less Awesome Company, Some City, CA [May 2000 - Sept 2002]</span></p>
<ul>
<li>Direct all departmental operations</li>
<li>Coordinate work with internal and external resources</li>
<li>Generally in charge of everything</li>
</ul>
</div>

<p class=”categorylabel”>Education</p>
<ul>
<li>MBA, MyState University, May 2002</li>
<li>B.A, Business Administration, MyState University, May 2000</li>
</ul>

<p class=”categorylabel”>References</p>
<ul>
<li>Available upon request.</li>
</ul>
</body>
</html>

Using CSS, which organizes sets of styles into classes—as you learned in Chapter 3, “Understanding Cascading Style Sheets”—you can see how text formatting is applied to different areas of this content. If you look closely at the definition of the div.indented class, you will see the use of the margin-left style. This style, which you will learn more about in Part III, applies a certain amount of space (25 pixels, in this example) to the left of the element. That space accounts for the indentation shown in Figure 5.2.

FIGURE 5.2
Here’s what the code used in Listing 5.2 looks like.

Working with Special Characters

Most fonts now include special characters for European languages, such as the accented é in Café. There are also a few mathematical symbols and spe- cial punctuation marks, such as the circular bullet •.

You can insert these special characters at any point in an HTML document using the appropriate codes, as shown in Table 5.1. You’ll find an even more extensive list of codes for multiple character sets at http://www.webstandards.org/learn/reference/named_entities.html.

For example, the word café could be written using either of the following methods: caf&eacute; café

TABLE 5.1    Commonly Used English Language Special Characters         

CharacterNumeric CodeCode NameDescription
&quot;Quotation mark
&&&amp;Ampersand
<<&lt;Less than
>>&gt;Greater than
¢¢&cent;Cent sign
££&pound;Pound sterling
|¦&brvbar; or
&brkbar;
Broken vertical bar
§§&sect;Section sign
©©&copy;Copyright
®®&reg;Registered trademark
°°&deg;Degree sign
+–±&plusmn;Plus or minus
²²&sup2;Superscript two
³³&sup3;Superscript three
··&middot;Middle dot
¹¹&sup1;Superscript one
¼¼&frac14;Fraction one-fourth
½½&frac12;Fraction one-half
¾¾&frac34;Fraction three-fourths
ÆÆ&AElig;Capital AE ligature
ææ&aelig;Small ae ligature

Although you can specify character entities by number, each symbol also has a mnemonic name that is often easier to remember.

HTML/XHTML uses a special code known as a character entity to represent special characters such as © and ®. Character entities are always specified starting with & and ending with; Table 5.1 lists the most commonly used character entities, although HTML supports many more.

Table 5.1 includes codes for the angle brackets, quotation, and ampersand. You must use those codes if you want these symbols to appear on your pages; otherwise, the web browser interprets them as HTML commands. In Listing 5.3 and Figure 5.3, several of the symbols from Table 5.1 are shown in use.

LISTING 5.3        Special Character Codes

<?xml version=”1.0” encoding=”UTF-8”?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
“http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en”>
<head>
<title>Punctuation Lines</title>
</head>

<body>
<p>
Q: What should you do when a British banker picks a fight with you?<br />
A: &pound; some &cent;&cent; into him.
<hr />
Q: What do you call it when a judge takes part of a law off the books?<br />
A: &sect; violence.
<hr />
Q: What did the football coach get from the locker room vending machine in the middle of the game?<br />
A: A &frac14; back at &frac12; time.
<hr />
Q: How hot did it get when the police detective interrogated the mathematician?<br />
A: x&sup3;&deg;
<hr />
Q: What does a punctilious plagiarist do?<br /> A: &copy;
<hr />
</p>
</body>
</html>
FIGURE 5.3
This is how the HTML page in Listing 5.3 looks in most web browsers.

Aligning Text on a Page

Now that you’ve seen how to change the appearance of your content at the text level, it’s time to take it a step further and modify the blocks of text that appear on the page. It’s easy to take for granted the fact that most paragraphs are automatically aligned to the left when you’re reading information on the Web. However, there certainly are situations in which you might choose to align content to the right or even the center of a page. HTML gives you the option to align a single HTML block-level element, such as text contained within a <p></p> or <div></div> tag pair. Before we get into the details of aligning block elements, however, let’s briefly note how attributes work.

Using Attributes

Attributes are used to provide additional information related to an HTML tag. Attributes are special code words used inside an HTML tag to control exactly what the tag does. They are very important in even the simplest bit of web content, so it’s important that you are comfortable using them.

Attributes invoke the use of styles, classes, or IDs that are applied to particular tags. If you define a particular class or ID in a style sheet—as you learned in Chapter 3, “Understanding Cascading Style Sheets” then you can invoke that class or ID using class=”someclass” or id=”someid” with- in the tag itself. When the browser renders the content for display, it will look to the style sheet to determine exactly how the content will appear according to the associated style definitions. Similarly, you can use the style attribute to include style information for a particular element with- out connecting the element to an actual style sheet. For example, when you begin a paragraph with the <p> tag, you can specify whether the text in that particular paragraph should be aligned to the left margin, the right margin, or to the center of the page by setting the style attribute. If you want to associate that particular paragraph with an existing class or ID, you set the class or id attribute.

In the following example, each paragraph could be left-aligned:

<p style=”text-align: left;”>Text goes here.</p>

<p class=”leftAlignStyle”>Text goes here.</p>

<p id=”firstLeftAlign”>Text goes here.</p>

In the first paragraph, the style appears directly in the style attribute. In the second paragraph, the paragraph will be left-aligned if the style sheet entry for the leftAlignStyle class includes the text-align statement.

Similarly, the third paragraph will be left-aligned if the style sheet entry for the firstLeftAlign class includes the text-align statement.

In the previous example, you might have noticed the use of lowercase for tags, attributes, and styles. The exacting XHTML standard requires tags and attributes to be lowercase; the XHTML standard also requires quotation marks around attribute values.

For example, the following code will be rendered by most popular web browsers:

<P STYLE=TEXT-ALIGN:CENTER>

However, this code does not conform to XHTML standards because the tag is uppercase, the style attribute and its value (text-align:center) is uppercase, and the value isn’t in quotation marks. If you want to stay compatible with the latest standards and software, you should always use the following instead:

<p style=”text-align:center”>

Aligning Block-Level Elements

To align a block-level element such as <p> to the right margin without creating a separate class or ID in a style sheet, simply place style=

”text-align:right” inside the <p> tag at the beginning of the paragraph. Similarly, to center the element, use <p style=”text-align:center”>. To align a paragraph to the left, use <p style=”text-align:left”>.

The text-align part of the style attribute is referred to as a style rule, which means that it is setting a particular style aspect of an HTML element. There are many style rules you can use to carefully control the for- matting of web content.

The text-align style rule is not reserved for just the <p> tag. In fact, you can use the text-align style rule with any block-level element, which includes

<h1>, <h2>, the other heading tags, and the <div> tag, among others. The

<div> tag is especially handy because it can encompass other block-level elements and thus enable you to control the alignment of large portions of your web content all at once. The div in the <div> tag is for division.

Listing 5.4 demonstrates the style attribute and text-align style rule with both the <p> and the <div> tags. The results are shown in Figure 5.4. You’ll learn many more advanced uses of the <div> tag in Part III.

LISTING 5.4  The text-align Style Rule Used with the style Attribute

<?xml version=”1.0” encoding=”UTF-8”?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
“http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en”>
<head>
<title>Bohemia</title>
</head>

<body>
<div style=”text-align:center”>
<h1>Bohemia</h1>
<h2>by Dorothy Parker</h2>
</div>
<p style=”text-align:left”>
Authors and actors and artists and such<br /> Never know nothing, and never know much.<br />
Sculptors and singers and those of their kidney<br /> Tell their affairs from Seattle to Sydney.
</p>
<p style=”text-align:center”>
Playwrights and poets and such horses’ necks<br /> Start off from anywhere, end up at sex.<br /> Diarists, critics, and similar roe<br />
Never say nothing, and never say no.
</p>
<p style=”text-align:right”>
People Who Do Things exceed my endurance;<br /> God, for a man that solicits insurance!
</p>
</body>
</html>
FIGURE 5.4
The results of using the text align- ment in Listing 5.4.

The use of <div style=”text-align:center”> ensures that the content area, including the two headings, are centered. However, the text align- ment of the individual paragraphs within the <div> override the setting and ensure that the text of the first paragraph is left-aligned, the second paragraph is centered, and the third paragraph is right-aligned.

The Three Types of HTML Lists

For clarity, it’s often useful to present information on a web page as a list of items. There are three basic types of HTML lists. All three are shown in Figure 5.5, and Listing 5.5 reveals the HTML used to construct them.

. Ordered list—An indented list that has numbers or letters before each list item. The ordered list begins with the <ol> tag and ends with a closing </ol> tag. List items are enclosed in the <li></li> tag pair, and line breaks appear automatically at each opening <li> tag. The entire list is indented.

. Unordered list—An indented list that has a bullet or other symbol before each list item. The unordered list begins with the <ul> tag and closes with </ul>. Like the ordered list, its list items are enclosed in the <li></li> tag pair. A line break and symbol appear at each opening <li> tag, and the entire list is indented.

. Definition list—A list of terms and their meanings. This type of list, which has no special number, letter, or symbol before each item, begins with <dl> and ends with </dl>. The <dt></dt> tag pair encloses each term and the <dd></dd> tag pair encloses each definition. Line breaks and indentations appear automatically.

LISTING 5.5         Unordered Lists, Ordered Lists, and Definition Lists

<?xml version=”1.0” encoding=”UTF-8”?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
“http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en”>
<head>
<title>How to Be Proper</title>
</head>

<body>
<h1>How to Be Proper</h1>
<h2>Basic Etiquette for a Gentlemen Greeting a Lady Aquaintance</h2>
<ul>
<li>Wait for her acknowledging bow before tipping your hat.</li>
<li>Use the hand farthest from her to raise the hat.</li>
<li>Walk with her if she expresses a wish to converse; Never make a lady stand talking in the street.</li>
<li>When walking, the lady must always have the wall.</li>
</ul>
<h2>Recourse for a Lady Toward Unpleasant Men Who Persist in Bowing</h2>
<ol>
<li>A simple stare of iciness should suffice in most instances.</li>
<li>A cold bow discourages familiarity without offering insult.</li>
<li>As a last resort: “Sir, I have not the honour of your aquaintance.”</li>
</ol>
<h2>Proper Address of Royalty</h2>
<dl>
<dt>Your Majesty</dt>
<dd>To the king or queen.</dd>
<dt>Your Royal Highness</dt>
<dd>To the monarch’s spouse, children, and siblings.</dd>
<dt>Your Highness</dt>
<dd>To nephews, nieces, and cousins of the sovereign.</dd>
</dl>
</body>
</html>
FIGURE 5.5
The three basic types of HTML lists.

Placing Lists Within Lists

Although definition lists are officially supposed to be used for defining terms, many web page authors use them anywhere they’d like to see some indentation. In practice, you can indent any text simply by putting <dl><dd> at the beginning of it and </dd></dl> at the end and skipping over the

<dt></dt> tag pair. However, a better approach to indenting text is to use the <blockquote></blockquote> tag pair, which indents content without the presumption of a definition and allows for much more clear styling. With one set of attributes, you can set the width, height, background color, border type and color of your element area, and other visual effects.

Because of the level of control over the display of your items that you have when using CSS, there is no need to use nested lists to achieve the visual appearance of indentation. Reserve your use of nested lists for when the content warrants it. In other words, use nested lists to show a hierarchy of information, such as in Listing 5.6.

Ordered and unordered lists can be nested inside one another, down to as many levels as you want. In Listing 5.6, a complex indented outline is con- structed from several unordered lists. You’ll notice in Figure 5.6 that Firefox automatically uses a different type of bullet for each of the first three levels of indentation, making the list very easy to read. This is common in modern browsers.

LISTING 5.6        Using Lists to Build Outlines

<?xml version=”1.0” encoding=”UTF-8”?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
“http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en”>
<head>
<title>Vertebrates</title>
</head>

<body>
<h1>Vertebrates</h1>
<ul>
<li><span style=”font-weight:bold”>Fish</span>
<ul>
<li>Barramundi</li>
<li>Kissing Gourami</li>
<li>Mummichog</li>
</ul>
</li>
<li><span style=”font-weight:bold”>Amphibians</span>
<ul>
<li>Anura
<ul>
<li>Goliath Frog</li>
<li>Poison Dart Frog</li>
<li>Purple Frog</li>
</ul>
</li>
<li>Caudata
<ul>
<li>Hellbender</li>
<li>Mudpuppy</li>
</ul>
</li>
</ul>
</li>
<li><span style=”font-weight:bold”>Reptiles</span>
<ul>
<li>Nile Crocodile</li>
<li>King Cobra</li>
<li>Common Snapping Turtle</li>
</ul>
</li>
</ul>
</body>
</html>

As shown in Figure 5.6, a web browser will normally use a solid disc for the first-level bullet, a hollow circle for the second-level bullet, and a solid square for all deeper levels. However, you can explicitly choose which type of bullet to use for any level by using <ul style=”list-style-type:disc”>,

<ul style=”list-style-type:circle”>, or

<ul style=”list-style-type:square”> instead of <ul>.

FIGURE 5.6
In Firefox, multilevel unordered lists are neatly indented and bulleted for improved readability.

You can even change the bullet for any single point within an unordered list by using the list-style-type style rule in the <li> tag. For example, the following codes displays a hollow circle in front of the words extra and super and a solid square in front of the word special:

<ul style=”list-style-type:circle”>

<li>extra</li>

<li>super</li>

<li style=”list-style-type:square”>special</li>

</ul>

The list-style-type style rule also works with ordered lists, but instead of choosing a type of bullet, you choose the type of numbers or letters to place in front of each item. Listing 5.7 shows how to use Roman numerals (list-style-type:upper-roman), capital letters (list-style-type:upper- alpha), lowercase letters (list-style-type:lower-alpha), and ordinary numbers in a multilevel list. Figure 5.7 shows the resulting outline, which is nicely formatted.

Although Listing 5.7 uses the list-style-type style rule only with the

<ol> tag, you can also use it for specific <li> tags within a list (although it’s hard to imagine a situation in which you would want to do this). You can also explicitly specify ordinary numbering with list-style-type:decimal, and you can make lowercase Roman numerals with

list-style-type:lower-roman.

LISTING 5.7     Using the list-style-type Style Rule with the style Attribute in Multitiered Lists

<?xml version=”1.0” encoding=”UTF-8”?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
“http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en”>
<head>
<title>Advice from the Golf Guru</title>
</head>

<body>
<h1>How to Win at Golf</h1>
<ol style=”list-style-type:upper-roman”>
<li>Training
<ol>
<li>Mental prep
<ol style=”list-style-type:upper-alpha”>
<li>Watch golf on TV religiously</li>
<li>Get that computer game with Tiger whatsisname</li>
<li>Rent “personal victory” subliminal tapes</li>
</ol>
</li>
<li>Equipment
<ol style=”list-style-type:upper-alpha”>
<li>Make sure your putter has a pro autograph on it</li>
<li>Pick up a bargain bag of tees-n-balls at Costco</li>
</ol>
</li>
<li>Diet
<ol style=”list-style-type:upper-alpha”>
<li>Avoid junk food
<ol style=”list-style-type:lower-alpha”>
<li>No hotdogs</li>
</ol>
</li>
<li>Drink wine and mixed drinks only, no beer</li>
</ol>
</li>
</ol>
</li>
<li>Pre-game
<ol>
<li>Dress
<ol style=”list-style-type:upper-alpha”>
<li>Put on shorts, even if it’s freezing</li>
<li>Buy a new hat if you lost last time</li>
</ol>
</li>
<li>Location and Scheduling
<ol style=”list-style-type:upper-alpha”>
<li>Select a course where your spouse or boss won’t find you</li>
<li>To save on fees, play where your buddy works</li>
</ol>
</li>
<li>Opponent
<ol style=”list-style-type:upper-alpha”>
<li>Look for: overconfidence, inexperience</li>
<li>Buy opponent as many pre-game drinks as possible</li>
</ol>
</li>
</ol>
</li>
<li>On the Course
<ol>
<li>Tee off first, then develop severe hayfever</li>
<li>Drive cart over opponent’s ball to degrade aerodynamics</li>
<li>Say “fore” just before ball makes contact with opponent</li>
<li>Always replace divots when putting</li>
<li>Water cooler holes are a good time to correct any errors in ball
placement</li>
</ol>
</li>
</ol>
</body>
</html>
FIGURE 5.7
A well-formatted outline can make almost any plan look more plausible.

Summary

In this chapter, you learned how to make text appear as boldface or italic and how to code superscripts, subscripts, special symbols, and accented let- ters. You saw how to make the text line up properly in preformatted pas- sages of monospaced text and how to control the size, color, and typeface of any section of text on a web page. You also learned that attributes are used to specify options and special behavior of many HTML tags and how to use the style attribute with CSS style rules to align text. You also discovered how to create and combine three basic types of HTML lists: ordered lists, unordered lists, and definition lists. Lists can be placed within other lists to create outlines and other complex arrangements of text.

Table 5.2 summarizes the tags and attributes discussed in this chapter. Don’t feel like you have to memorize all these tags, by the way!

TABLE 5.2             HTML Tags and Attributes Covered in Chapter 5

TagFunction
<i>…</i>Italic text.
<tt>…</tt>Typewriter (monospaced) font.
<pre>…</pre>Preformatted text (exact line endings and spacing will
be preserved—usually rendered in a monospaced font).
<big>…</big>Text is slightly larger than normal.
<small>…</small>Text is slightly smaller than normal.
<sub>…</sub>Subscript.
<sup>…</sup>Superscript.
<div>…</div>A region of text to be formatted.
<dl>…</dl>A definition list.
<dt>…</dt>A definition term, as part of a definition list.
<dd>…</dd>The corresponding definition to a definition term, as
part of a definition list.
<ol>…</ol>An ordered (numbered) list.
<ul>…</ul>An unordered (bulleted) list.
<li>…</li>A list item for use with <ol> or <ul>.
AttributesFunction
style=”font-family:typeface”The typeface (family) of the font, which is the name of a font, such as Arial. (Can also be used with
<p>, <h1>, <h2>, <h3>, and so on.)
style=”font-size:size”The size of the font, which can be set to small, medium, or large, as well as x-small, x-large, and
so on. Can also be set to a specific point size (such as 12 pt).
style=”color:color”Changes the color of the text.
style=”text-align:alignment”Align text to center, left, or right. (Can also be used with <p>, <h1>, <h2>, <h3>, and so on.)
style=”list-style-The type of numerals used to label the list. Possible The type of numerals used to label the list. Possible values are decimal, lower-roman, upper-roman,
style=”list-style-numtype
style=”list-style-
style=”list-style-

Q&A

Q. How do I find out the exact name for a font I have on my computer?

A. On a Windows or Macintosh computer, open the Control Panel and click the Fonts folder—the fonts on your system are listed. (Vista users might have to switch to “Classic View” in your Control Panel.) When specifying fonts in the font-family style rule, use the exact spelling of font names. Font names are not case-sensitive, however.

Q. How do I put Kanji, Arabic, Chinese, and other non-European charac- ters on my pages?

A. First of all, users who need to read these characters on your pages must have the appropriate language fonts installed. They must also have selected that language character set and its associated font for their web browsers. You can use the Character Map program in Windows (or a similar program in other operating systems) to get the numerical codes for each character in any language font. To find Character Map, click Start, All Programs, Accessories, and then System Tools. If the character you want has a code of 214, use Ö to place it on a web page. If you cannot find the Character Map program, use your operating system’s built-in Help function to find the specific location.

The best way to include a short message in an Asian language (such

as We Speak Tamil-Call Us!) is to include it as a graphics image. That way every user will see it, even if they use English as their primary lan- guage for web browsing. But even to use a language font in a graphic, you will likely have to download a specific language pack for your oper- ating system. Again, check your system’s Help function for specific instructions.

Q. I’ve seen web pages that use three-dimensional little balls or other special graphics for bullets. How do they do that?

A. That trick is a little bit beyond what this chapter covers. You’ll learn how to do it yourself in Chapter 8.

Q. How do I “full justify” text so that both the left and right margins are flush?

A. You can use text-align:justify in your style declaration.

Workshop

The workshop contains quiz questions and activities to help you solidify your understanding of the material covered. Try to answer all questions before looking at the “Answers” section that follows.

Quiz

  1. How would you create a paragraph in which the first three words are bold, using styles rather than the <b> or <strong> tags?
  2. How would you represent the chemical formula for water?
  3. How do you display “© 2010, Webwonks Inc.” on a web page?
  4. How would you center everything on an entire page?
  5. What would you use to create a definition list to show that the word glunch means “a look of disdain, anger, or displeasure” and that the word glumpy means “sullen, morose, or sulky”?

Answers

  1. You would use the following:

<p><span style=”font-weight: bold”>First three words</span> are bold.</p>

  • You would use H<sub>2</sub>O.
  • You would use either of the following:

&copy; 2010, Webwonks Inc. © 2010, Webwonks Inc.

  • If you thought about putting a <div style=”text-align:center”> immediately after the <body> tag at the top of the page, and </div> just before the </body> tag at the end of the page, then you’re correct. However, the text-align style is also supported directly in the <body> tag, which means you can forego the <div> tag and place the style=”text-align:center” style directly in the <body> tag. Presto, the entire page is centered!
  • You would use the following:

<dl>

<dt>glunch</dt><dd>a look of disdain, anger, or displeasure</dd>

<dt>glumpy</dt><dd>sullen, morose, or sulky</dd>

</dl>

Exercises

. Apply the font-level style attributes you learned about in this chapter to various block-level elements such as <p>, <div>, <ul>, and <li> items. Try nesting your elements to get a feel for how styles do or do not cas- cade through the content hierarchy.

. Use the text alignment style attributes to place blocks of text in various places on your web page. Try nesting your paragraphs and divisions (<p> and <div>) to get a feel for how styles do or do not cascade through the content hierarchy.

. Try producing an ordered list outlining the information you’d like to put on your web pages. This will give you practice formatting HTML lists and also give you a head start on thinking about the issues covered in later chapters of this book.

6.Using Tables
to Display Information

In this chapter, you learn how to build HTML tables you can use to control the spacing, layout, and appearance of tabular data in your web content. Although you can achieve similar results using CSS, there are definitely times when a table is the best way to present information, and you’ll find that tables are useful for arranging information into rows and columns. I will also explain how designers have used tables for page layout in the past and how that isn’t always the best idea. Before we begin, just remember a table is simply an orderly arrangement of content into vertical columns and horizontal rows.

Creating a Simple Table

A table consists of rows of information with individual cells inside. To make tables, you have to start with a <table> tag. Of course, you end your tables with the </table> tag. If you want the table to have a border, use a border attribute to specify the width of the border in pixels. A border size of 0 or none (or leaving the border attribute out entirely) will make the border invisible, which is handy if you find yourself using a table as a page layout tool (not recommended).

With the <table> tag in place, the next thing you need is the <tr> tag. The

<tr> tag creates a table row, which contains one or more cells of information before the closing </tr>. To create these individual cells, use the <td> tag (<td> stands for table data). Place the table information between the <td> and </td> tags. A cell is a rectangular region that can contain any text, images, and HTML tags. Each row in a table consists of at least one cell. Multiple cells within a row form column in a table.

There is one more basic tag involved in building tables. The <th> tag works exactly like a <td> tag except <th> indicates that the cell is part of the heading of the table. Most web browsers render the text in <th> cells as centered and boldface.

You can create as many cells as you want, but each row in a table should have the same number of columns as the other rows. The HTML code shown in Listing 6.1 creates a simple table using only the four table tags I’ve mentioned thus far. Figure 6.1 shows the resulting page as viewed in a web browser.

LISTING 6.1     Creating Tables with the <table>, <tr>, <td>, and <th> Tags.

<?xml version=”1.0” encoding=”UTF-8”?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
“http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en”>
<head>
<title>Baseball Standings</title>
</head>

<body>
<h1>Baseball Standings</h1>
<table>
<tr>
<th>Team</th>
<th>W</th>
<th>L</th>
<th>GB</th>
</tr>
<tr>
<td>Los Angeles Dodgers</td>
<td>62</td>
<td>38</td>
<td>—</td>
</tr>
<tr>
<td>San Francisco Giants</td>
<td>54</td>
<td>46</td>
<td>8.0</td>
</tr>
<tr>
<td>Colorado Rockies</td>
<td>54</td>
<td>46</td>
<td>8.0</td>
</tr>
<tr>
<td>Arizona Diamondbacks</td>
<td>43</td>
<td>58</td>
<td>19.5</td>
</tr>
<tr>
<td>San Diego Padres</td>
<td>39</td>
<td>62</td>
<td>23.5</td>
</tr>
</table>
</body>
</html>
FIGURE 6.1
The HTML code in Listing 6.1 creates a table with six rows and four columns.

The table in the example contains baseball standings, which are perfect for arranging in rows and columns—if not a little plain. You’ll learn to jazz things up a bit during this chapter. The headings in the table show the Team, Wins (W), Losses (L), and Games Behind (GB) in the standings.

Although we did not apply any styles to the HTML in Listing 6.1, you can use any text style in a table cell. However, styles or HTML tags used in one cell don’t carry over to other cells, and tags from outside the table don’t apply within the table. For example, consider the following table:

<p style=”font-weight:bold”>
<table>
<tr>
<td style=”font-style:italic”>hello</td>
<td>there</td>
</tr>
</table> </p>

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

<table style=”font-weight:bold”>
<tr>
<td style=”font-style:italic”>hello</td>
<td>there</td>
</tr>
</table

In this example, both words are in bold and the word hello is italicized as well. Of course, you don’t have to apply styles at the table level. The font- weight:bold style could just as easily be applied to each cell individually; you could repeat style=”font-weight:bold” in each cell or create a class in your style sheet and use class=”classname” in each cell—it’s your choice.

Controlling Table Sizes

When a table width is not specified, the size of a table and its individual cells automatically expand to fit the data you place into it. However, you can choose to control the exact size of the entire table by using width and/or height styles in the <table> tag. You can also control the size of each cell by putting width and height styles in the individual <td> tags. The width and height styles can be specified as either pixels or percent- ages. For example, the following code creates a table 500 pixels wide and 400 pixels high:

<table style=”width:500px; height:400px”>

To make the first cell of the table 20% of the total table width and the sec- ond cell 80% of the table width, type the following:

<table style=”width:100%”>
<tr>
<td style=”width:20%”>skinny cell</td>
<td style=”width:80%”>fat cell</td>
</tr>
</table>

Notice that the table is sized to 100%, which ensures the table fills the entire width of the browser window. When you use percentages instead of fixed pixel sizes, the table will resize automatically to fit any size browser window while maintaining the aesthetic balance you’re after. In this case, the two cells within the table are automatically resized to 20% and 80% of the total table width, respectively. In Listing 6.2, the simple table from Listing 6.1 is expanded to show specif- ic control over table cell widths.

LISTING 6.2        Specifying Table Cell Widths

<?xml version=”1.0” encoding=”UTF-8”?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
“http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en”>
<head>
<title>Baseball Standings</title>
</head>

<body>
<h1>Baseball Standings</h1>
<table>
<tr>
<th style=”width:35px;”></th>
<th style=”width:175px;”>Team</th>
<th style=”width:25px;”>W</th>
<th style=”width:25px;”>L</th>
<th style=”width:25px;”>GB</th>
</tr>
<tr>
<td><img src=”losangeles.gif” alt=”Los Angeles Dodgers” /></td>
<td>Los Angeles Dodgers</td>
<td>62</td>
<td>38</td>
<td>—</td>
</tr>
<tr>
<td><img src=”sanfrancisco.gif” alt=”San Francisco Giants” /></td>
<td>San Francisco Giants</td>
<td>54</td>
<td>46</td>
<td>8.0</td>
</tr>
<tr>
<td><img src=”colorado.gif” alt=”Colorado Rockies” /></td>
<td>Colorado Rockies</td>
<td>54</td>
<td>46</td>
<td>8.0</td>
</tr>
<tr>
<td><img src=”arizona.gif” alt=”Arizona Diamondbacks” /></td>
<td>Arizona Diamondbacks</td>
<td>43</td>
<td>58</td>
<td>19.5</td>
</tr>
<tr>
<td><img src=”sandiego.gif” alt=”San Diego Padres” /></td>
<td>San Diego Padres</td>
<td>39</td>
<td>62</td>
<td>23.5</td>
</tr>
</table>
</body>
</html>

You can see the consistent column widths in Figure 6.2.

FIGURE 6.2
The HTML code in Listing 6.2 creates a table with six rows and five columns, with specific widths used for each column.

There are two differences between the code from Listing 6.1 and the code used in Listing 6.2. First, an additional column has been added in Listing 6.2; this column does not have a heading, but the <th></th> tag pair is still present in the first table row. In rows two through six, this additional column contains an image (the <img /> tag). The second difference in Listing

6.2 is the addition of a specific width style for each <th> element in the first row. The first column is defined as 35px wide, the second 175px wide, and the third, fourth, and fifth columns are each 25px wide.

Also note that these widths are not repeated in the <td> elements in subsequent rows. Technically you must define only the widths in the first row; the remaining rows will follow suit because they are all part of the same table. However, if you used another formatting style (such as a style to change font size or color), that style must be repeated for each element that should have those display properties.

Alignment and Spanning Within Tables

By default, anything you place inside a table cell is aligned to the left and vertically centered. Figures 6.1 and 6.2 show this default alignment.

However, you can align the contents of table cells both horizontally and vertically with the text-align and vertical-align style properties.

You can apply these alignment attributes to any <tr>, <td>, or <th> tag. Alignment attributes assigned to a <tr> tag apply to all cells in that row. Depending on the size of your table, you can save yourself a considerable amount of time and effort by applying these attributes at the <tr> level and not in each <td> or <th> tag.

The HTML code in Listing 6.3 uses a combination of text alignment styles to apply a default alignment to a row, but it is overridden in a few individual cells. Figure 6.3 shows the result of the code in Listing 6.3.

Following are some of the more commonly used vertical-align style property values: top, middle, bottom, text-top, text-bottom, and baseline (for text). These property values give you plenty of flexibility in aligning table data vertically.

LISTING 6.3         Alignment, Cell Spacing, Borders, and Background Colors in Tables

<?xml version=”1.0” encoding=”UTF-8”?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
“http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en”>
<head>
<title>Things to Fear</title>
</head>

<body>
<h1>Things to Fear</h1>
<table border=”2” cellpadding=”4” cellspacing=”2” width=”100%”>
<tr style=”background-color:red;color:white”>
<th colspan=”2”>Description</th>
<th>Size</th>
<th>Weight</th>
<th>Speed</th>
</tr>
<tr style=”vertical-align:top”>
<td><img src=”handgun.gif” alt=”.38 Special”/></td>
<td style=”font-size: 14px;font-weight:bold;
vertical-align:middle;text-align:center”>.38 Special</td>
<td>Five-inch barrel.</td>
<td>Twenty ounces.</td>
<td>Six rounds in four seconds.</td>
</tr>
<tr style=”vertical-align:top”>
<td><img src=”rhino.gif” alt=”Rhinoceros” /></td>
<td style=”font-size: 14px;font-weight:bold;
vertical-align:middle;text-align:center”>Rhinoceros</td>
<td>Twelve feet, horn to tail.</td>
<td>Up to two tons.</td>
<td>Thirty-five miles per hour in bursts.</td>
</tr>
<tr style=”vertical-align:top”>
<td><img src=”axeman.gif” alt=”Broad Axe” /></td>
<td style=”font-size: 14px;font-weight:bold;
vertical-align:middle;text-align:center”>Broad Axe</td>
<td>Thirty-inch blade.</td>
<td>Twelve pounds.</td>
<td>Sixty miles per hour on impact.</td>
</tr>
</table>
</body>
</html>
FIGURE 6.3
The code in Listing 6.3 shows the use of the colspan attribute and alignment styles.

At the top of Figure 6.3, a single cell (Description) spans two columns. This is accomplished with the colspan attribute in the <th> tag for that cell. As you might guess, you can also use the rowspan attribute to create a cell that spans more than one row.

Spanning is the process of forcing a cell to stretch across more than one row or column of a table. The colspan attribute causes a cell to span across multiple columns; rowspan has the same effect on rows.

Additionally, text styles are used in the second cell within the Description column to create bold text that is both vertically aligned to the middle and horizontally aligned to the center of the cell.

There are a few tricks in Listing 6.3 that I haven’t explained yet. You can give an entire table—and each individual row or cell in a table—its own background, distinct from any background you might use on the web page itself. You can do this by placing the background-color or background-image style in the <table>, <tr>, <td>, or <th> tag exactly as you would in the <body> tag (see Chapter 8, “Working with Colors, Images, and Multimedia”). To give an entire table a yellow background, for example, you would use <table style=”background-color:yellow”> or the equivalent <table style=”background-color:#FFFF00”>. In Listing 6.3, only the top row has a background color; it uses <tr style=”background-color:red;color: white”> to apply a red background across the cells in that row. Additionally, the color style ensures that the text in that row is white.

Similar to the background-color style property is the background-image property (not shown in this example), which is used to set an image for a table background. If you wanted to set the image leaves.gif as the background for a table, you would use <table style=”background- image:url(leaves.gif)”>. Notice that the image file is placed within parentheses and preceded by the word url, which indicates that you are describing where the image file is located.

Tweaking tables goes beyond just using style properties. As shown in Listing 6.3, you can control the space around the borders of a table with the cellpadding and cellspacing attributes. The cellspacing attribute sets the amount of space (in pixels) between table borders and between table cells themselves. The cellpadding attribute sets the amount of space around the edges of information in the cells, also in pixels. Setting the cellpadding value to 0 causes all the information in the table to align as closely as possible to the table borders, possibly even touching the borders. The cellpadding and cellspacing attributes give you good overall control of the table’s appearance.

Page Layout with Tables

At the beginning of this chapter, I indicated that designers have used tables for page layout and to display tabular information. You will still find many examples of table-based layouts if you peek at another designer’s source code. This method of design grew out of the old (mid-1990s to early 2000s) inconsistencies in browser support for CSS. All browsers supported tables and in generally the same way, so web designers latched on to the table- based method of content creation to achieve the same visual page display across all browsers. However, now that support for CSS is relatively similar across all major browsers, designers can follow the long-standing stan- dards-based recommendation not to use tables for page layout.

The World Wide Web Consortium (W3C), the standards body that oversees the future of the Web, promotes style sheets as the proper way to lay out pages (instead of using tables). Style sheets are ultimately much more powerful than tables, which is why the bulk of this book teaches you how to use style sheets for page layout.

The main reasons for avoiding using tables for layout include the following:

  • Mixing presentation with content—One of the goals of CSS and standards-compliant web design is to separate the presentation layer from the content layer.
  • Creating unnecessarily difficult redesigns—To change a table-based layout, you would have to change the table-based layout on every single page of your site (unless it is part of a complicated, dynamically driven site, in which case you would have to undo all the dynamic pieces and remake them).
  • Accessibility issues—Screen reading software looks to tables for content and will often try to read your layout table as a content table.
  • Rendering on mobile devices—Table layouts are often not flexible enough to scale downward to small screens (see Chapter 12, “Creating Fixed or Liquid Layouts”).

These are but a few of the issues in table-based web design. For a closer look at some of these issues, see the popular presentation “Why Tables for Layout Is Stupid” at http://www.hotdesign.com/seybold/everything.html.

Summary

In this brief chapter, you learned to arrange text and images into organized arrangements of rows and columns called tables. You learned the three basic tags for creating tables and many optional attributes and styles for controlling the alignment, spacing, and appearance of tables. You also dis- covered that tables can be used together and nested within one another for an even wider variety of layout options.

Table 6.1 summarizes the tags and attributes covered in this chapter.

TABLE 6.1             HTML Tags and Attributes Covered in Chapter 6

Tag/AttributeFunction
<table>…</table>Creates a table that can contain any number of rows
(<tr> tags).
AttributesFunction
border=”width”Indicates the width in pixels of the table borders.
Using border=”0” or omitting the border attribute makes borders invisible.
cellspacing=
➥”spacing”
The amount of space between the cells in the table, in pixels.
cellpadding=
➥”padding”
The amount of space between the edges of the cell and its contents, in pixels.
style=
➥”width:width”
The width of the table on the page, either in exact pixel values or as a percentage of the page width.
style=
➥”height:height”
The height of the table on the page, either in exact pixel values or as a percentage of the page height.
style=”background-
➥color:color”
Background color of the table and individual table cells that don’t already have a background color.
style=
➥”backgroundimage:
➥url(imageurl)”
A background image to display within the table and individual table cells that don’t already have a background image. (If a background color is also specified, the color will show through transparent areas of the image.)
AttributesFunction
<tr>…</tr>Defines a table row containing one or more cells
(<td> tags).
AttributesFunction
style=”text-align:alignment”The horizontal alignment of the contents of the cell. Possible values are left, right, and center.
style=”vertical-align:alignment”The vertical alignment of the contents of the cell. Commonly used values are top, middle, and bottom.
rowspan=”numrows”The number of rows this cell will span.
colspan=”numcols”The number of columns this cell will span.
style=”width:width”The width of this column of cells, in exact pixel
values or as a percentage of the table width.
style=”height:height”The height of this row of cells, in exact pixel values or as a percentage of the table height.
style=”background-color:color”Background color of the cell.
style=”backgroundimage: url(imageurl)”Background image to display within the cell.

Q&A

Q. I made a big table and when I load the page, nothing appears on the page for a long time. Why the wait?

A. Complex tables can take a while to appear on the screen. The web browser has to figure out the size of everything in the table before it can display any part of it. You can speed things up a bit by always including width and height attributes for every graphics image within a table. Using width attributes in the <table> and <td> tags also helps.

Q. Can I put a table within a table?

A. Yes, you can nest tables within other table cells. However, nested tables—especially large ones—take time to load and render properly. Before you create a nested table, think about the content you are plac- ing on the page and ask yourself if it could be displayed using CSS. You might not know all the answers until you finish this book, but here’s a hint: In most cases, the answer will be yes.

Workshop

The workshop contains quiz questions and exercises to help you solidify your understanding of the material covered. Try to answer all questions before looking at the “Answers” section that follows.

Quiz

  1. How would you create a simple two-row, two-column table with a stan- dard border?
  2. Expanding on question 1, how would you add 30 pixels of space between the table border and the cells?
  3. Continuing with the table you’ve built in questions 1 and 2, how would you make the top-left cell green, the top-right cell red, the bottom-left cell yellow, and the bottom-right cell blue?

Answers

  1. Use the following HTML:
    <table border=”1”>
    <tr>
    <td>Top left…</td>
    <td>Top right…</td>
    </tr>
    <tr>
    <td>Bottom left…</td>
    <td>Bottom right…</td>
    </tr>
    </table>
  2. Add cellspacing=”30” to the <table> tag.
  3. Add style=”background-color:green” to the top left <td> tag, add style=”background-color:red” to the top right <td> tag, add style=”background-color:yellow” to the bottom left <td> tag, and add style=”background-color:blue” to the bottom right <td> tag.

Exercises

. Do you have any pages that have information visitors might be interest- ed in viewing as lists or tables? Use a table to present some tabular information. Make sure each column has its own heading (or perhaps its own graphic). Play around with the various types of alignment and spacing that you have learned in this chapter.

. You will often see alternating row colors in a table, with one row having a grey background and the next a white background. The goal of alternating colors in table rows is so that the individual rows are easier to discern when looking quickly at the table full of data. Create a table with alternating row colors and text colors (if necessary). Although the lesson on colors comes in Chapter 8, you have enough information in this lesson to begin trying out the process.

7. Using External
and
Internal Links

So far, you have learned how to use HTML tags to create some basic web pages. However, at this point, those pieces of content are islands unto themselves, with no connection to anything else (although it is true that in Chapter 3, “Understanding Cascading Style Sheets,” I sneaked a few page links into the examples). To turn your work into real web content, you need to connect it to the rest of the Web—or at least to your other pages within your own personal or corporate sites.

This chapter shows you how to create hypertext links to content within your own document and how to link to other external documents. Additionally, you will learn how to style hypertext links so that they dis- play in the color and decoration that you desire—not necessarily the default blue underlined display.

Using Web Addresses

The simplest way to store web content for an individual website is to place the files all in the same folder together. When files are stored together like this, you can link to them by simply providing the name of the file in the href attribute of the <a> tag. An attribute is an extra piece of information associated with a tag that pro- vides further details about the tag. For example, the href attribute of the <a> tag identifies the address of the page to which you are linking. After you have more than a few pages, or when you start to have an organization structure to the content in your site, you should put your files into directories (or folders, if you will) whose names reflect the content within them. For example, all your images could be in an “images” directory, corporate information could be in an “about” directory, and so on.

Regardless of how you organize your documents within your own web server, you can use relative addresses, which include only enough information to find one page from another.

A relative address describes the path from one web page to another, instead of a full (or absolute) Internet address.

If you recall from Chapter 1, the document root of your web server is the directory designated as the top-level directory for your web content. In web addresses, that document root is represented by the forward slash (/). All subsequent levels of directories are separated by the same type of for- ward slash. For example:

/directory/subdirectory/subsubdirectory/

Suppose you are creating a page named zoo.html in your document root and you want to include a link to pages named african.html and asian.html in the elephants subdirectory. The links would look like the following:

<a href=”/elephants/african.html”>Learn about African elephants.</a>

<a href=”/elephants/asian.html”>Learn about Asian elephants.</a>

These specific addresses are actually called relative-root addresses in that they are relative addresses that lack the entire domain name, but they are specifically relative to the document root specified by the forward slash.

Using a regular relative address, you can skip the initial forward slash. This type of address allows the links to become relative to whatever directory they are in—it could be the document root or it could be another directory one or more levels down from the document root:

<a href=”elephants/african.html”>Learn about African elephants.</a>

<a href=”elephants/asian.html”>Learn about Asian elephants.</a>

Your african.html and asian.html documents in the elephant’s subdirectory could link back to the main zoo.html page in either of these ways:

<a href=” http://www.yourdomain.com/zoo.html”>Return to the zoo. </a>

<a href=”/zoo.html”>Return to the zoo.</a>

<a href=”../zoo.html”>Return to the zoo.</a>

The first link is an absolute link. With an absolute link there is absolutely no doubt where the link should go because the full URL is provided domain name included. The second link is a relative-root link. It is relative to the domain you are currently browsing and therefore does not require the protocol type (for example, http://) and the domain name (for example, www.yourdomain. com), but the initial forward slash is provided to show that the address begins at the document root.

In the third link, the double dot (..) is a special command that indicates the folder that contains the current folder—in other words, the parent folder.

Anytime you see the double dot, just think to yourself “go up a level” in the directory structure.

If you use relative addressing consistently throughout your web pages, you can move the pages to another folder, disk drive, or web server without changing the links.

Relative addresses can span quite complex directory structures if necessary. Chapter 27, “Organizing and Managing a Website,” offers more detailed advice for organizing and linking large numbers of web pages.

Linking Within a Page Using Anchors

The <a> tag—the tag responsible for hyperlinks on the Web—got its name from the word “anchor,”and means a link serves as a designation for a spot in a web page. In examples shown throughout this book so far, you’ve learned how to use the <a> tag to link to somewhere else, but that’s only half of its usefulness. Let’s get started working with anchor links that link to content within the same page.

Identifying Locations in a Page with Anchors

The <a> tag can be used to mark a spot on a page as an anchor, enabling you to create a link that points to that exact spot. Listing 7.1, which is pre- sented a bit later in this chapter, demonstrates a link to an anchor within a page. To see how such links are made, let’s take a quick peek ahead at the first <a> tag in the listing: <a id=”top”></a>

The <a> tag normally uses the href attribute to specify a hyperlinked tar- get. The <a href> is what you click and <a id> is where you go when you click there. In this example, the <a> tag is still specifying a target but no actual link is created. Instead, the <a> tag gives a name to the specific point on the page where the tag occurs. The </a> tag must be included and a unique name must be assigned to the id attribute, but no text between <a> and </a> is necessary.

Linking to Anchor Locations

Listing 7.1 shows a site with various anchor points placed throughout a single page. Take a look at the last <a> tag in Listing 7.1 to see an example:

<a href=”#top”>Return to Index.</a> The # symbol means that the word top refers to a named anchor point within the current document, rather than to a separate page. When a user clicks Return to Index, the web browser displays the part of the page starting with the <a id=”top”> tag.

LISTING 7.1        Setting Anchor Points by Using the <a> Tag with an id Attribute

<?xml version=”1.0” encoding=”UTF-8”?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
“http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en”>
<head>
<title>Alphabetical Shakespeare</title>
</head>

 
<body>
<h1><a id=”top”></a>First Lines of Shakespearean Sonnets</h1>
<p>Don’t you just hate when you go a-courting, and you’re down
on one knee about to rattle off a totally romantic Shakespearean sonnet, and zap! You space it. <em>”Um... It was, uh... I think it started with a B...”</em></p>
<p>Well, appearest thou no longer the dork. Simply refer to this page, click on the first letter of the sonnet you want, and get an instant reminder of the first line to get you started. <em>”Beshrew that heart that makes my heart to groan...”</em></p>
<h2 style=”text-align:center”>Alphabetical Index</h2>
<h3 style=”text-align:center”>
<a href=”#A”>A</a> <a href=”#B”>B</a> <a href=”#C”>C</a>
<a href=”#D”>D</a> <a href=”#E”>E</a> <a href=”#F”>F</a>
<a href=”#G”>G</a> <a href=”#H”>H</a> <a href=”#I”>I</a>
<a href=”#J”>J</a> <a href=”#K”>K</a> <a href=”#L”>L</a>
<a href=”#M”>M</a> <a href=”#N”>N</a> <a href=”#O”>O</a>
<a href=”#P”>P</a> <a href=”#Q”>Q</a> <a href=”#R”>R</a>
<a href=”#S”>S</a> <a href=”#T”>T</a> <a href=”#U”>U</a>
<a href=”#V”>V</a> <a href=”#W”>W</a> <a href=”#X”>X</a>
<a href=”#Y”>Y</a> <a href=”#Z”>Z</a>
</h3>
<hr />
<h3><a id=”A”></a>A</h3>
<ul>
<li>A woman’s face with nature’s own hand painted,</li>
<li>Accuse me thus, that I have scanted all, </li>
<li>Against my love shall be as I am now</li>
<li>Against that time (if ever that time come) </li>
<li>Ah wherefore with infection should he live, </li>
<li>Alack what poverty my muse brings forth, </li>
<li>Alas ‘tis true, I have gone here and there, </li>
<li>As a decrepit father takes delight, </li>
<li>As an unperfect actor on the stage, </li>
<li>As fast as thou shalt wane so fast thou grow’st, </li>
</ul>
<p><a href=”#top”><em>Return to Index.</em></a></p>
<hr />
<!-- continue with the alphabet -->
<h3><a id=”Z”></a>Z</h3>
<p>(No sonnets start with Z.)</p>
<p><a href=”#top”><em>Return to Index.</em></a></p>
</body>
</html>

Each of the <a href> links in Listing 7.1 makes an underlined link leading to a corresponding <a id> anchor—or it would if I had filled in all the text. Only A and Z will work in this example because only the A and Z links have corresponding text to link to, but feel free to fill in the rest on your own! Clicking the letter Z under Alphabetical Index in Figure 7.1, for example, takes you to the part of the page shown in Figure 7.2.

FIGURE 7.1

The <a id> tags in Listing 7.1 don’t appear at all on the web page. The <a href> tags appear as underlined links.

FIGURE 7.2

Clicking the letter Z on the page shown in Figure 7.1 takes you to the appropriate section of the same page.

Having mastered the concept of linking to sections of text within a single page, you can now learn to link together other pieces of web content.

Linking Between Your Own Web Content

As you learned earlier in this chapter, you do not need to include http:// before each address specified in the href attribute when linking to content within your domain (or on the same computer, if you are viewing your site locally). When you create a link from one file to another file within the same domain or on the same computer, you don’t need to specify a com- plete Internet address. In fact, if the two files are stored in the same folder, you can simply use the name of the HTML file by itself:

<a href=”pagetwo.html”>Go to Page 2.</a>

As an example, Listing 7.2 and Figure 7.3 show a quiz page with a link to the answers page shown in Listing 7.3 and Figure 7.4. The answers page contains a link back to the quiz page. Because the page in Listing 7.2 links to another page in the same directory, the filename can be used in place of a complete address.

LISTING 7.2        The historyanswers.html file

<?xml version=”1.0” encoding=”UTF-8”?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
“http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en”>
<head>
<title>History Quiz</title>
</head>

<body>
<h1>History Quiz</h1>
<p>Complete the following rhymes. (Example: William the Conqueror Played cruel tricks on the Saxons in... ten sixty-six.)</p>
<ol>
<li>Columbus sailed the ocean blue in...</li>
<li>The Spanish Armada met its fate in...</li>
<li>London burnt like rotten sticks in...</li>
</ol>
<p style=”text-align: center;font-weight: bold;”>
<a href=”historyanswers.html”>Check Your Answers!</a>
</p>
</body>
</html>
FIGURE 7.3
This is the historyquiz.html file listed in Listing 7.2 and referred to by the link in Listing 7.3.

LISTING 7.3     The historyanswers.html File That historyquiz.html Links To

<?xml version=”1.0” encoding=”UTF-8”?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
“http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en”>
<head>
<title>History Quiz Answers</title>
</head>

<body>
<h1>History Quiz Answers</h1>
<ol>
<li>...fourteen hundred and ninety-two.</li>
<li>...fifteen hundred and eighty eight.</li>
<li>...sixteen hundred and sixty-six.</li>
</ol>
<p style=”text-align: center;font-weight: bold;”>
<a href=”historyquiz.html”>Return to the Questions</a>
</p>
</body>
</html>
FIGURE 7.4
The Check Your Answers! link in Figure 7.3 takes you to this answers page. The Return to the Questions link takes you back to what’s shown in Figure 7.3.

Using filenames instead of complete Internet addresses saves you a lot of typing. More important, the links between your pages will work properly no matter where the group of pages is stored. You can test the links while the files are still on your computer’s hard drive. You can then move them to a web server, a CD-ROM, a DVD, or a memory card, and all the links will still work correctly. There is nothing magic about this simplified approach to identifying web pages—it all has to do with web page addressing, as you’ve already learned.

Linking to External Web Content

The only difference between linking to pages within your own site and linking to external web content is that when linking outside your site, you need to include the full address to that bit of content. The full address includes the http:// before the domain name, and then the full pathname to the file (for example, an HTML file, image file, multimedia file, and so on).

For example, to include a link to Google from within one of your own web pages, you would use this type of absolute addressing in your <a> link:

<a href=” http://www.google.com/”>Go to Google</a> You can apply what you learned in previous sections to creating links to named anchors on other pages. Linked anchors are not limited to the same page. You can link to a named anchor on another page by including the address or filename followed by # and the anchor name. For example, the

following link would take you to an anchor named photos within the african.html page inside the elephants directory on the domain www.takeme2thezoo.com.

<a href=”http://www.takemetothezoo.com/elephants/african.html#photos”> Check out the African Elephant Photos!</a>

The http:// and the domain name would not be necessary in that instance, as you have already learned.

Linking to an Email Address

In addition to linking between pages and between parts of a single page, the <a> tag allows you to link to email addresses. This is the simplest way to enable your web page visitors to talk back to you. Of course, you could just provide visitors with your email address and trust them to type it into whatever email programs they use, but that increases the likelihood for errors. By providing a clickable link to your email address, you can make it almost completely effortless for them to send you messages and eliminate the chance for typos.

An HTML link to an email address looks like the following:

<a href=”mailto:yourusername@yourdomain.com”>Send me an email message.</a>

The words Send me an email message will appear just like any other <a>

link.

If you want people to see your actual email address (so that they can make note of it or send a message using a different email program), include it both in the href attribute and as part of the message between the <a> and

</a> tags, like this:

<a href=”mailto:you@yourdomain.com”>you@yourdomain.com</a>

In most web browsers, when someone clicks the link, she gets a window into which she can type a message that is immediately sent to you—whatever email program the person uses to send and receive email will automatically be used. You can provide some additional information in the link so that the subject and body of the message also have default values. You do this by adding subject and body variables to the mailto link. You separate the variables from the email address with a question mark (?), the value from the variable with an equal sign (=), and then separate each of the variable and value pairs with an ampersand (&). You don’t have to understand the variable/value terminology at this point. Here is an example of specifying a subject and body for the preceding email example:

<a href=”mailto:author@somedomain.com?subject=Book Question&body= When is the next edition coming out?”>author@somedomain.com</a>

When a user clicks this link, an email message is created with author@ somedomain.com as the recipient, Book Question as the subject of the message, and When is the next edition coming out? as the message body.

Before you run off and start plastering your email address all over your web pages, I have to give you a little warning and then let you in on a handy trick. You’re no doubt familiar with spammers that build up data- bases of email addresses and then bombard them with junk mail advertisements. One way spammers harvest email addresses is by using programs that automatically search web pages for mailto links.

Fortunately, there is a little trick that will thwart the vast majority of spammers. This trick involves using character entities to encode your email address, which confuses scraper programs that attempt to harvest your email address from your web pages. As an example, take the email address, jcmeloni@gmail.com. If you replace the letters in the address with their character entity equivalents, most email harvesting programs will be thrown off. Lowercase ASCII character entities begin at a for letter a and increase through the alphabet in order. For example, letter j is &#106, c is &#99, and so on. Replacing all the characters with their ASCII attributes produces the following:

<a href=”mailto:jcmeloni @gmail.com”>Send

me an email message.</a>

Because the browser interprets the character encoding as, well, characters, the end result is the same from the browser’s perspective. However, auto- mated email harvesting programs search the raw HTML code for pages, which in this case is showing a fairly jumbled-looking email address. If you don’t want to figure out the character encoding for your own address, just type email address encoder in your search engine and you will find some services online that will produce an encoded string for you.

Opening a Link in a New Browser Window

Now that you have a handle on how to create addresses for links—both internal (within your site) and external (to other sites)—there is one addi- tional method of linking: forcing the user to open links in new windows.

You’ve no doubt heard of pop-up windows, which are browser windows—typi- cally advertising products or services—that are opened and displayed auto- matically without the user’s approval. However, the concept of opening anoth- er window or targeting another location does serve a valid purpose in some instances. For example, you might want to present information in a smaller secondary browser window but still allow the user to see the information in the main window. This is often the case when clicking on a link to an animated demo, movie clip, or other multimedia element. You could also want to target a new browser window when you are linking to content off-site.

However, opening a new browser window on behalf of your user—especially when it’s a full-size new window—goes against some principles of usability and accessibility. When people opened new windows, typically it happened through the use of the target attribute of the <a> tag. The target attribute has been removed from the <a> tag in the strict XHTML 1.1 specification.

There are valid ways to achieve the same result while still adhering to principles of usability and accessibility, but these methods require a little JavaScript and other advanced techniques. You will learn about these methods as we move into the JavaScript portion of this book, which will also cover standards-compliant and accessible ways to invoke new windows with your external links.

Using CSS to Style Hyperlinks

The default display of a text-based hyperlink on a web page is underlined blue text. You might also have noticed that links you have previously visit- ed appear as underlined purple text—that color is also a default. If you’ve spent any time at all on the Web, you will also have noticed that not all links are blue or purple—and for that, I think, we are all thankful. Using a little CSS and knowledge of the various pseudoclasses for the <a> link, you can make your links look however you want.

A pseudoclass is a class that describes styles for elements that apply to certain circumstances, such as various states of user interaction with that element.

For example, the common pseudoclasses for the <a> tag are link, visited, hover, and active. You can remember them with the mnemonic “Love- Hate”—LV (love) HA (hate), if you choose.

•. a:link describes the style of a hyperlink that has not been visited previously.

•. a:visited describes the style of a hyperlink that has been visited previously and is present in the browser’s memory.

•. a:hover describes the style of a hyperlink as a user’s mouse hovers over it (and before it has been clicked).

•. a:active describes the style of a hyperlink that is in the act of being clicked, but has not yet been released.

For example, let’s say you want to produce a link with the following styles:

•. A font that is bold and Verdana (and not underlined, meaning it has no text decoration)

•. A base color that is light blue

•. A color of red when users hover over it or when they are clicking it

•. A color of gray after users have visited it

Your style sheet entries might look like the following:

a {
font-family: Verdana, sans-serif; font-weight: bold;
text-decoration: none;
}
a:link {
color: #6479A0;
}
a:visited { color: #CCCCCC;
}
a:hover {
color: #E03A3E;
}
a:active {
color: #E03A3E;
}

Because the sample link will be Verdana bold (and not underlined) regardless of the state it is in, those three property and value pairs can reside in the rule for the a selector. However, because each pseudoclass must have a specific color associated with it, we use a rule for each pseudoclass as shown in the code example. The pseudoclass inherits the style of the parent rule, unless the rule for the pseudoclass specifically overrides that rule. In other words, all the pseudoclasses in the previous example will be Verdana bold (and not underlined). If, however, we had used the following rule for the hover pseudoclass, the text would display in Comic Sans when users hovered over it (if, in fact, the user has the Comic Sans font installed):

a:hover {
font-family: “Comic Sans MS”; color: #E03A3E;
}

Additionally, because the active and hover pseudoclasses use the same font color, you can combine style rules for them:

a:hover, a:active { color: #E03A3E;
}

Listing 7.4 puts these code snippets together to produce a page using styled pseudoclasses; the results of this code can be seen in Figure 7.5.

LISTING 7.4        Using Styles to Display Link Pseudoclasses

<?xml version=”1.0” encoding=”UTF-8”?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
“http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en”>
<head>
<title>Sample Link Style</title>

<style type=”text/css”> a {
font-family: Verdana, sans-serif; font-weight: bold;
text-decoration: none;
}
a:link {
color: #6479A0;
}
a:visited { color: #CCCCCC;
}
a:hover, a:active { color: #FF0000;
}
</style>
</head>
<body>
<h1>Sample Link Style</h1>
<p><a href=”simplelinkstyle.html”>The first time you see me,
I should be a light blue, bold, non-underlined link in the Verdana font</a>.</p>
</body>
</html>
FIGURE 7.5
A link can use particular styles to control the visual display.

If you view the example in your web browser, indeed the link should be a light blue, bold, non-underlined Verdana font. If you hover over the link, or click the link without releasing it, it should turn red. If you click and release the link, the page will simply reload because the link points to the file with the same name. However, at that point the link will be in your browser’s memory and thus will be displayed as a visited link—and it will appear gray instead of blue.

You can use CSS to apply a wide range of text-related changes to your links. You can change fonts, sizes, weights, decoration, and so on.

Sometimes you might want several different sets of link styles in your style sheet. In that case, you can create classes; you aren’t limited to working with only one set of styles for the <a> tag. The following example is a set of style sheet rules for a footerlink class for links I might want to place in the footer area of my website:

a.footerlink {
font-family: Verdana, sans-serif; font-weight: bold;
font-size: 75%;
text-decoration: none;
}
a.footerlink:link, a.footerlink:visited { color: #6479A0;
}
a.footerlink:hover, a.footerlink:active { color: #E03A3E;
}

As you can see in the example that follows, the class name (footerlink) appears after the selector name (a), separated by a dot, and before the pseudoclass name (hover), separated by a colon:

selector.class:pseudoclass a.footerlink:hover

Summary

The <a> tag is what makes hypertext “hyper.” With it, you can create links between pages and links to specific anchor points on any page. This chapter focused on creating and styling simple links to other pages using either relative or absolute addressing to identify the pages.

You learned that when you’re creating links to other people’s pages, it’s important to include the full Internet address of each page in an <a href> tag. For links between your own pages, include just the filenames and enough directory information to get from one page to another.

You discovered how to create named anchor points within a page and how to create links to a specific anchor. You also learned how to link to your email address so that users can easily send you messages. You even learned how to protect your email address from spammers. Finally, you learned methods for controlling the display of your links using CSS.

Table 7.1 summarizes the <a> tag discussed in this chapter.

TABLE 7.1             HTML Tags and Attributes Covered in Chapter 7

Tag/AttributeFunction
<a>…</a>With the href attribute, this creates a link to another document or anchor; with the id attribute, this creates an anchor that can be linked to.
AttributeFunction
href=”address”
id=”name”
The address of the document or anchor point to link to.
The name for this anchor point in the document.

Q&A

Q. What happens if I link to a page on the Internet, and then the person who owns that page deletes or moves it?

A. That depends on how the maintainer of that external page has set up his web server. Usually, you will see a page not found message or something to that effect when you click a link that has been moved or deleted. You can still click the Back button to return to your page. As a site maintainer, you can periodically run link-checking programs to ensure your internal and external links are valid. An example of this is the Link Checker service at http://validator.w3.org/checklink.

Q. One of the internal links on my website works fine on my computer, but when I put the pages on the Internet, the link doesn’t work any- more. What’s up?

A. These are the most likely culprits:

. Capitalization problems—On Windows computers, linking to a file named MyFile.html with <a href=”myfile.html”> will work. On most web servers, the link must be <a href=”MyFile.html”> (or you must change the name of the file to MyFile.html). To make matters worse, some text editors and file transfer programs actu- ally change the capitalization without telling you! The best solu- tion is to stick with all-lowercase filenames for web pages.

. Spaces in filenames—Most web servers don’t allow filenames with spaces. For example, you should never name a web page my page.html. Instead, name it mypage.html or even my_page.html (using an underscore instead of a space).

. Local absolute addresses—If, for some reason, you link to a file using a local absolute address, such as C:\mywebsite\news. html, the link won’t work when you place the file on the Internet. You should never use local absolute addresses; when this occurs, it is usually an accident caused by a temporary link that was created to test part of a page. So, be careful to remove any test links before publishing a page on the Web.

Q. Can I put both href and id in the same <a> tag? Would I want to for any reason?

A. You can, and it might save you some typing if you have a named anchor point and a link right next to each other. It’s generally better, however, to use <a href> and <a id> separately to avoid confusion because they play very different roles in an HTML document.

Q. What happens if I accidentally misspell the name of an anchor or forget to put the # in front of it?

A. If you link to an anchor name that doesn’t exist within a page or mis- spell the anchor name, the link goes to the top of that page.

Workshop

The workshop contains quiz questions and exercises to help you solidify your understanding of the material covered. Try to answer all questions before looking at the “Answers” section that follows.

Quiz

  1. Your best friend from elementary school finds you on the Internet and says he wants to trade home page links. How do you put a link to his site at www.supercheapsuits.com/~billybob/ on one of your pages?
  2. What HTML would you use to make it possible for someone clicking the words “About the Authors” at the top of a page to skip down to a list of credits somewhere else on the page?
  3. If your email address is bon@soir.com, how would you make the text “goodnight greeting” into a link that people can click to compose and send you an email message?

Answers

  1. Put the following on your page:

<a href=”http://www.supercheapsuits.com/~billybob/”>Billy Bob’s site</a>

  • Type this at the top of the page:

<a href=”#credits”>About the Authors</a>

Type this at the beginning of the credits section:

<a id=”credits”></a>

  • Type the following on your web page:

Send me a <a href=”mailto:bon@soir.com”>goodnight greeting</a>!

Exercises

. Create an HTML file consisting of a formatted list of your favorite websites. You might already have these sites bookmarked in your web browser, in which case you can visit them to find the exact URL in the browser’s address bar.

. If you have created any pages for a website, look through them and consider whether there are any places in the text where you’d like to make it easy for people to contact you. Include a link in that place to your email address. You can never provide too many opportunities for people to contact you and tell you what they need or what they think about your products especially if you’re running a business.

8. Working with
Colors, Images, and Multimedia

This list might look long, but each of these tasks is short and sweet, and will help you move your web development experience from the white background/black text examples so far in this book to more interesting (or at least colorful) examples. But that’s not to say that dark text on a light background is bad in fact, it’s the most common color combination you’ll find online.

Although paying attention to color schemes and producing a visually appealing website is important, you don’t have to be an artist by trade to put high impact graphics on your web pages. More importantly, you don’t need to spend hundreds or thousands of dollars on software, either. This chapter will help you get started with creating some of the images you can use in your website. Although the sample figures in this chapter use a popular and free graphics program for Windows, Mac, and Linux users (GNU Image Manipulation Program, or GIMP), you can apply the knowledge learned in this chapter to any major Windows or Macintosh graphics application although the menus and options will look slightly different.

After you learn to create the graphics themselves, you’ll learn how to integrate your graphics using HTML and CSS. At the end of the chapter you’ll learn a bit about integrating additional media, or multimedia, into your website.

Best Practices for Choosing Colors

I can’t tell you exactly which colors to use in your website, but I can help you understand the considerations you should make when selecting those colors on your own. The colors you use can greatly influence your visitors; if you are running an e-commerce site, you will want to use colors that entice your users to view your catalog and eventually purchase something. To that end, you want to make sure colors are used judiciously and with respect. You might wonder how respect enters into the mix when talking about colors, but remember the World Wide Web is an international community and interpretations differ; for instance, pink is a very popular color in Japan, but very unpopular in Eastern European countries. Similarly, green is the color of money in the United States, but the vast majority of other countries have multi-colored paper bills such that “the color of money” isn’t a single color at all and thus the metaphor would be of no value to them.

Besides using colors that are culturally sensitive, other best practices include the following:

. Use a natural palette of colors. This doesn’t mean you should use earth tones, but instead refers to using colors that one would naturally see on a casual stroll around town avoid ultrabright colors that can cause eye strain.

. Use a small color palette. You don’t need to use 15 different colors to achieve your goals. In fact, if your page includes text and images in 15 different colors, you might reevaluate the message you’re attempting to send. Focus on three or four main colors with a few complimentary colors, at the most.

. Consider your demographics. You are likely not able to control your demographics and thus have to find a middle ground that accommodates everyone. The colors enjoyed by younger people are not necessarily those appreciated by older people, just as there are color biases between men and women and people from different geographic regions and cultures.

With just these few tips in mind, it might seem as if your color options are limited. Not so it simply means you should think about the decisions you’re making before you make them. A search for color theory in the search engine of your choice should give you more food for thought, as will the use of the color wheel. The color wheel is a chart that shows the organization of colors in a circular manner. The method of display is an attempt to help you visualize the relationships between primary, secondary, and complementary colors. Color schemes are developed from working with the color wheel; understanding color schemes can help you determine the color palette to use consistently throughout your website. For example, knowing something about color relationships will hopefully enable you to avoid using orange text on a light blue background, or bright blue text on a brown background.

Some common color schemes in web design are as follows:

. Analogous—Colors that are adjacent to each other on the color wheel, such as yellow and green. One color is the dominant color and its analogous friend is used to enrich the display.

. Complementary—Colors that are opposite from each other on the color wheel, such as a warm color (red) and a cool color (green).

. Triadic—Three colors that are equally spaced around the color wheel. The triadic scheme provides balance while still allowing rich color use.

There are entire books and courses devoted to understanding color theory, so continuing the discussion in this book would indeed be a tangent.

However, if you intend to work in web design and development, you will be served well by a solid understanding of the basics of color theory.

Spend some time reading about it—an online search will provide a wealth of information.

Additionally, spend some hands-on time with the color wheel. The Color Scheme Generator at http://colorschemedesigner.com/ enables you to start with a base color and produce monochromatic, complementary, triadic, tetradic, analogic, and accented analogic color schemes.

Understanding Web Colors

Specifying a background color other than white for a web page is easier than you probably realize. For example, to specify blue as the background color for a page, put style=”background-color:blue” inside the <body> tag or in the style sheet rule for the body element. Of course, you can use many colors other than blue. In fact, there are 16 colors listed in the W3C standards: aqua, black, blue, fuchsia, gray, green, lime, maroon, navy, olive, purple, red, silver, teal, white, and yellow. Obviously, there are many more colors displayed on the Web than just those 16. In fact, there are 140 color names that you can use with assurance that all browsers will display these colors similarly. Here’s a partial list of the 140 descriptive color names: azure, bisque, cornflowerblue, dark- salmon, firebrick, honeydew, lemonchiffon, papayawhip, peachpuff, sad- dlebrown, thistle, tomato, wheat, and whitesmoke.

But names are subjective for instance, if you look at the color chart of 140 cross-browser color names, you will not be able to distinguish between fuchsia and magenta. You will then realize that the associated hexadecimal color values for those two terms, fuchsia and magenta, are exactly the same: #FF00FF. You’ll learn about hexadecimal color values in the next section, but for now, know that if you want to be standards-compliant and use more than the 16 color names the W3C standards dictate, you should use the hexadecimal color codes whenever possible.

There are, in fact, 16 million colors made possible with hexadecimal color codes. However, most modern computer displays can display “only” 16,384. But 16,384 is still a lot more than 140, or 16.

You should be aware that not all computer monitors display colors in the same hues. What might appear as a beautiful light blue background color on your monitor might be more of a purple hue on another user’s monitor. Neutral, earth-tone colors (such as medium gray, tan, and ivory) can pro- duce even more unpredictable results on many computer monitors. These colors might even seem to change color on one monitor depending on lighting conditions in the room or the time of day.

In addition to changing the background of your pages to a color other than white, you can change the color of text links, including various properties of links (such as the color for when a user hovers over a link versus when the user clicks a link—as you learned in previous chapters). You can also set the background color of container elements (such as paragraphs, divs, blockquotes, and table cells), and you can use colors to specify the borders around those elements. You’ll see some examples of colors and container elements later in this chapter.

There are plenty of very bad websites, some created by earnest people with no trace of irony whatsoever. However, “The World’s Worst Website” shown in Figure 8.1 was purposefully created to show some of the more egregious sins of website design, especially with its use of colors. A screen- shot does not do it justice—visit and experience the site for yourself at http://www.angelfire.com/super/badwebs/main.htm. If you search for bad website examples in your search engine, you will find many sites that collect examples of bad design and explain just why such a site should be in a Hall of Shame rather than a Hall of Fame. Many sites are considered bad because of their visual displays, and that display begins with color selection. Therefore, understanding colors, as well as the nuances of their specification and use, is a crucial step to creating a good website.

FIGURE 8.1
A partial screenshot of “The World’s Worst Website.”

Using Hexadecimal Values for Colors

To remain standards-compliant, as well as to retain precise control over the colors in your website, you can reference colors by their hexadecimal value. The hexadecimal value of a color is an indication of how much red, green, and blue light should be mixed into each color. It works a little bit like Play-Doh—just mix in the amounts of red, blue, and green you want to get the appropriate color.

The hexadecimal color format is #rrggbb, in which rr, gg, and bb are two- digit hexadecimal values for the red (rr), green (gg), and blue (bb) compo- nents of the color. If you’re not familiar with hexadecimal numbers, don’t sweat it. Just remember that FF is the maximum and 00 is the minimum. Use one of the following codes for each component:

. FF means full brightness.

. CC means 80% brightness.

. 99 means 60% brightness.

. 66 means 40% brightness.

. 33 means 20% brightness.

. 00 means none of this color component.

For example, bright red is #FF0000, dark green is #003300, bluish-purple is #660099, and medium-gray is #999999. To make a page with a red back- ground and dark green text, the HTML code would look like the following:

<body style=”background-color:#FF0000; color:#003300”>

Although only six examples of two-digit hexadecimal values are shown here, there are actually 225 combinations of two-digit hexadecimal values— 0 through 9 and A through F, paired up. For example, F0 is a possible hex value (decimal value 240), 62 is a possible hex value (decimal value 98), and so on.

As previously discussed, the rr, gg, and bb in the #rrggbb hexadecimal color code format stand for the red, green, and blue components of the color. Each of those components has a decimal value ranging from 0 (no color) to 255 (full color).

So, white (or #FFFFFF) translates to a red value of 255, a green value of 255, and a blue value of 255. Similarly, black (#000000) translates to a red value of 0, a green value of 0, and a blue value of 0. True red is #FF0000 (all red, no green, and no blue), true green is #00FF00 (no red, all green, no blue), and true blue is #0000FF (no red, no green, and all blue). All other hexadecimal notations translate to some variation of the 255 possible values for each of the three colors. The cross-browser compatible color name cornflowerblue is associated with the hexadecimal notation #6495ED—a red value of 40, a green value of 149, and a blue value of 237 (almost all of the available blue values).

When picking colors, either through a graphics program or by finding something online that you like, you might see the color notion in hexadecimal or decimal. If you type hexadecimal color converter in your search engine, you will find numerous options to help you convert color values into something you can use in your style sheets.

Using CSS to Set Background, Text, and Border Colors

When using CSS, there are three instances in which color values can be used: when specifying the background color, the text color, or the border color of elements. Previous chapters contained examples of specifying colors without going in great detail about color notion or color theory. For example, in Chapter 7, “Using External and Internal Links,” you learned about using colors for various link states.

Figure 8.2 shows an example of color usage that could easily go into a web design Hall of Shame. I can’t imagine ever using these combinations of colors and styles in a serious website, but it serves here as an example of how color style could be applied to various elements.

FIGURE 8.2
Background, text, and border col- ors can all be set using CSS.

Listing 8.1 shows the XHTML and CSS styles used to produce Figure 8.2.

LISTING 8.1         Using Styles to Produce Background, Text, and Border Colors

<?xml version=”1.0” encoding=”UTF-8”?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
“http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en”>
<head>
<title>Background, Text, and Border Colors</title>
</head>

<body>
<h1>Background, Text, and Border Colors</h1>

<p style=”background-color:#CCCCCC; border:1px solid #000000; color:#FF0000”> Grey paragraph, black border, red text with a
<span style=”color:#FFA500”>orange span</span>.</p>

<div style=”width:300px; height:75px; margin-bottom: 12px; background-color:#000000; border:2px dashed #FF0000;
color: #FFFFFF”>
Black div, red border, white text. </div>

<table border=”1”>
<tr>
<td style=”background-color: #00FF00”>Green Table Cell</td>
<td style=”background-color: #FF0000”>Red Table Cell</td>
</tr>
<tr>
<td style=”background-color: #FFFF00”>Blue Table Cell</td>
<td style=”background-color: #0000FF”>Yellow Table Cell</td>
</tr>
</table>

<blockquote style=”background-color:#0000FF;
border:4px dotted #FFFF00; color:#FFFFFF”><p>Blue blockquote, yellow border, white text.</p></blockquote>
</body>
</html>

Looking at the styles used in Listing 8.1, you should be able to figure out almost everything except some of the border styles. In CSS, borders can’t be designated as a color without also having a width and type; in the first example shown in Listing 8.1, the border width is 1px, and the border type is solid. In the second example shown in Listing 8.1, the border width is 2px, and the border type is dashed. In the fourth example shown in Listing 8.1, the border width is 4px, and the border type is dotted.

When picking colors for your website, remember that a little bit goes a long way if you really like a bright and spectacular color, use it as an accent color and not throughout the primary design elements. For readability, remember that light backgrounds with dark text are much easier to read than dark backgrounds with light text.

Finally, consider the not-insignificant portion of your audience that might be color blind. For accessibility, you might consider using the Colorblind Web Page Filter tool at http://colorfilter.wickline.org/ to see what your site will look like to a person with color blindness.

Choosing Graphics Software

Selecting an overall color scheme for your website is one thing; creating or editing images to go into those templates are quite another—and beyond the scope of this book (or a single book, for that matter). However, in the sections that follow, you’ll learn a few of the basic actions that anyone maintaining a website should quickly master.

You can use almost any graphics program to create and edit images for your website, from the simple paint program that typically comes free with your computer’s operating system to an expensive professional program such as Adobe Photoshop. Similarly, if you have a digital camera or scanner attached to your computer, it probably came with some graphics software capable of creating web page graphics. There are also several free image editors available for download—or even online as a web application that deal just with the manipulation of photographic elements.

If you already have software you think might be good for creating web graphics, try using it to do everything described in these next sections. If your software can’t do some of the tasks covered here, it probably won’t be a good tool for web graphics. In that case, download and install GIMP from http://www.gimp.org. This fully functional graphics program is completely free and is used to perform the actions shown in this chapter.

If GIMP doesn’t suit you, consider downloading the evaluation version of Adobe Photoshop or Corel DRAW. For photo manipulation only, there are many free options, all with helpful features. Google’s Picasa, which is available free at http://picasa.google.com/, is one such option. Picnik (http://www.picnik.com/) is another. Both of these programs are suited for editing images rather than creating them from scratch, and Picasa is also oriented toward organizing your digital photograph collection. As such, these types of programs are not necessarily going to help you design a banner or button image for your site. However, these programs can help you work with some supplementary images, and they are powerful enough that they are worth checking out.

The Least You Need to Know About Graphics

Two forces are always at odds when you post graphics and multimedia on the Internet. The users’ eyes and ears want all your content to be as detailed and accurate as possible, and they also want that information displayed immediately. Intricate, colorful graphics mean big file sizes, which increase the transfer time even over a fast connection. How do you maximize the quality of your presentation while minimizing file size? To make these choices, you need to understand how color and resolution work together to create a subjective sense of quality.

The resolution of an image is the number of individual dots, or pixels, that make up an image. Large, high-resolution images generally take longer to transfer and display than small, low-resolution images. Resolution is usually specified as the width times the height of the image, expressed in pixels; a 300´200 image, for example, is 300 pixels wide and 200 pixels high.

You might be surprised to find that resolution isn’t the most significant fac- tor determining an image file’s storage size (and transfer time). This is because images used on web pages are always stored and transferred in compressed form. Image compression is the mathematical manipulation that images are put through to squeeze out repetitive patterns. The mathematics of image compression is complex, but the basic idea is that repeating patterns or large areas of the same color can be squeezed out when the image is stored on a disk. This makes the image file much smaller and allows it to be transferred faster over the Internet. The web browser then restores the original appearance of the image when the image is displayed.

In the sections that follow, you’ll learn how to create graphics with big visual impact but small file sizes. The techniques you’ll use to accomplish this depend on the contents and purpose of each image. There are as many uses for web graphics as there are web pages, but four types of graphics are by far the most common:

. Photos of people, products, or places

. Graphical banners and logos

. Buttons or icons to indicate actions and provide links

. Background textures for container elements

Preparing Photographic Images

To put photos on your web pages, you need to convert your print based photos to digital images or create photos digitally by using a digital camera. You might need to use the custom software that comes with your scanner or camera to save pictures onto your hard drive, or you can just drag and drop files from your camera to your hard drive. If you are using a scanner to create digital versions of your print photos, you can control just about any scanner directly from the graphics program of your choice see the software documentation for details.

After you transfer the digital image files to your computer, you can use your graphics program to crop, resize, color-correct, and compress to get them ready for use in your website.

Cropping an Image

Because you want web page graphics to be as compact as possible, you’ll usually need to crop your digital photos. When you crop a photo, you select the area you want to display, and you crop away the rest.

Even after your image has been cropped, it might be larger than it needs to be for a web page. Depending on the design of a specific web page, you might want to limit large images to no more than 800´600 pixels (if it is shown on a page by itself, such as an item catalog) or even 640´480 pixels or smaller. When shown alongside text, images tend to be in the 250 to 350 pixel range for width, so there’s just enough room for the text as well. In some cases, you might want to also provide a thumbnail version of the image that links to a larger version, in which case you’ll probably stick closer to 100 pixels in the larger dimension for the thumbnail.

Resizing an Image

The exact tool necessary to change an image’s size will depend on the pro- gram you are using. In GIMP, go to the Image menu and click Scale Image to open the Scale Image dialog box (see Figure 8.5).

FIGURE 8.5
Use the Scale Image dialog box to change the size of an image.

You’ll almost always want to resize using the existing aspect ratio, meaning that when you enter the width you’d like the image to be, the height will be calculated automatically (and vice versa) to keep the image from squishing out of shape. In GIMP, the aspect ratio is locked by default, as indicated by the chain link displayed next to the Width and Height options shown in Figure 8.5. Clicking once on the chain will unlock it, enabling you to specify pixel widths and heights of your own choosing—squished or not.

In most, if not all, graphics programs, you can also resize the image based on percentages instead of providing specific pixel dimensions. For exam- ple, if my image started out as 1629´1487, and I didn’t want to do the math to determine the values necessary to show it as half that width, I could simply select Percent (in this instance from the drop-down next to the pixel display shown in Figure 8.5) and change the default setting (100) to 50. The image width would then become 815 pixels wide by 744 high—and no math was necessary on my part.

Tweaking Image Colors

If you are editing photographic images rather than creating your own graphics, you might need to use some color-correction tools to get the photo just right. Like many image editing programs, GIMP offers several options for adjusting an image’s brightness, contrast, and color balance, as well as a filter to reduce the dreaded red-eye. To remove red-eye using GIMP, go to Filters, click Enhance, and then click Red Eye Removal.

Most of these options are pretty intuitive. If you want the image to be brighter, adjust the brightness. If you want more red in your image, adjust the color balance. In GIMP, the Colors menu gives you access to numerous tools. As with the Scale Image dialog box described in the previous section, each tool displays a dialog box in the foreground of your workspace. As you adjust the colors, the image reflects those changes. This preview function is a feature included in most image editing software.

Figure 8.6 shows the Adjust Hue/Lightness/Saturation tool, one of the many tools provided on the Colors menu. As shown in the figure, many color-related changes occur by using various sliders in dialog boxes to adjust the values you are working with. The Preview feature enables you to see what you are doing as you are doing it. The Reset Color button returns the image to its original state without any changes applied.

FIGURE 8.6
The Adjust Hue/Lightness/ Saturation tool is one of many slider-based color modification tools available in GIMP.

Because of the numerous tools available to you and the preview function available with each tool, a little playful experimentation is the best way to find out what each tool does.

Controlling JPEG Compression

Photographic images on the Web work best when saved in the JPEG file format rather than GIF; JPEG enables you to retain the number of colors in the file while still keeping the overall file size to a manageable level. When you’re finished adjusting the size and appearance of your photo, select File, Save As and choose JPEG as the file type. Your graphics program will likely provide you with another dialog box through which you can control various JPEG options, such as compression. Figure 8.7 shows the Save as JPEG dialog box you’ll see when you save a JPEG in GIMP. You can see here that you can control the compression ratio for saving JPEG files by adjusting the Quality slider between 1 (low quality, small file size) and 100 (high quality, large file size).

FIGURE 8.7
GIMP enables you to reduce file size while still retaining image quality by saving in the JPEG format.

You might want to experiment a bit to see how various JPEG compression levels affect the quality of your images, but 85% quality (or 15% compres- sion) is generally a good compromise between file size (and therefore download speed) and quality for most photographic images.

Creating Banners and Buttons

Graphics that you create from scratch, such as banners and buttons, require you to make considerations uniquely different from photographs. The first decision you need to make when you produce a banner or button is how big it should be. Most people accessing the web now have a computer with a screen that is at least 1024´768 pixels in resolution, if not considerably larger. For example, my screen is currently set at 1440´900 pixels. You should generally plan your graphics so that they will always fit within smaller screens (1024´768), with room to spare for scrollbars and margins. The crucial size constraint is the horizontal width of your pages because scrolling a page horizontally is a huge hassle and a source of confusion for web users. Vertically scrolling a page is much more acceptable, so it’s okay if your pages are taller than the minimum screen sizes.

Assuming that you target a minimum resolution of 800´600 pixels, full-sized banners and title graphics should be no more than 770 pixels wide by 430 pixels tall, which is the maximum viewable area of the page after you’ve accounted for scrollbars, toolbars, and other parts of the browser window.

Within a page, normal photos and artwork should be from 100 to 300 pixels in each dimension, and smaller buttons and icons should be 20 to 100 pixels tall and wide. Obviously, if you design for the 1024´768 resolution, you have more screen “real estate” to work with, but the size guidelines for banners, buttons, and other supplementary graphics are still in effect.

To create a new image in GIMP, go to File and choose New. The Create a New Image dialog box displays (see Figure 8.8). If you aren’t sure how big the image needs to be, just accept the default size of a 640´480. Or you can choose one of the other pre-determined sizes in the Template drop-down, such as Web banner common 468´60 or Web banner huge 728´90. Those two settings are indeed considered “common” and “huge” for website banners. Otherwise, enter the width and height of the new image.

For the image’s background color, you should usually choose white to match the background that most web browsers use for web pages (although as you learned in the previous chapter, that color can be changed). When you know that you’ll be creating a page with a back- ground other than white, you can choose a different background color for your image. Or you might want to create an image with no background at all, in which case you’ll select Transparency as the background color. When an image’s background is transparent, the web page behind the image is allowed to show through those areas of the image. In GIMP, select the background color for your new image by opening the Advanced Options in the Create a New Image dialog box.

FIGURE 8.8
You need to decide on the size of an image before you start working on it.

When you enter the width and height of the image in pixels and click OK, you are faced with a blank canvas—an intimidating sight if you’re as art phobic as most of us! However, because there are so many image creation tutorials (not to mention entire books) available to lead you through the process, I am comfortable leaving you to your own creative devices. This section is all about introducing you to the things you want to keep in mind when creating graphics for use in your sites. This section does not necessarily teach you exactly how to do it because being comfortable with the tool you choose is the first step to mastering them.

Reducing the Number of Colors in an Image

One of the most effective ways to reduce the size of, and therefore the download time for, an image is to reduce the number of colors used in the image. This can drastically reduce the visual quality of some photographic images, but it works great for most banners, buttons, and other icons.

You’ll be glad to know that there is a special file format for images with a limited number of colors; it’s called the Graphics Interchange Format (GIF). When you save an image as a GIF, you might be prompted to flatten layers or reduce the number of colors by converting to an indexed image, as those are requirements for GIFs, as shown in Figure 8.9. The dialog box will simply ask you to confirm these changes that the save process will do for you do not concern yourself with understanding these options at this time but read your software’s help file regarding layers and indexed colors for a full understanding.

FIGURE 8.9
When saving an image as a GIF, you might be prompted to convert it to an indexed color palette.

Remember, the GIF image format is designed for images that contain areas of solid colors, such as web page titles and other illustrated graphics; the GIF format is not ideal for photographs.

PNG (pronounced “ping”) is another useful file format that is supported in all major web browsers. Although the GIF image format enables you to specify a single transparent color, which means that the background of the web page will show through those areas of an image, the PNG format takes things a step further by enabling you to specify varying degrees of transparency.

Working with Transparent Images

You might have seen websites that use background colors or images in their container elements, but also have images present in the foreground that allow the background to show through parts of the foreground graphics. In these cases, the images in the foreground have portions which are transparent, so that the images themselves—which are always on a rectangular canvas do not show the areas of the canvas in which the design does not occur. You’ll often want to use these types of partially transparent images to make graphics look good over any background color or back- ground image you might have in place.

To make part of an image transparent, the image must be saved in the GIF or PNG file format. As mentioned previously in this chapter, most graphics programs that support the GIF format enable you to specify one color to be transparent, whereas PNG images allow for a range of transparency.

Largely because of this transparency range, the PNG format is superior to GIF. All the latest web browsers already support PNG images. For more information on the PNG image format, visit http://www.libpng.org/ pub/png/pngintro.html.

The process of creating a transparent image depends on the type of image you are creating (GIF or PNG) and the graphics software you are using to create it. For instructions, look in your graphics program’s help files or type transparent images with [your program here] into your search engine.

Creating Tiled Backgrounds

Any GIF or JPEG image can be used as a background tile within a contain- er element. However, before you go off and create a tiled background, especially a highly patterned tiled background, ask yourself what that tiled background adds to the overall look and feel of your website, and—more importantly—ask yourself if the text of the site can be read easily when placed over that pattern.

Think about the websites you frequent every day and consider the fact that few use tiled, patterned backgrounds on their entire page. If you restrict your browsing to websites for companies, products, sports teams, or other sites in which information (primarily text) is privileged, the number of sites with tiled, patterned backgrounds will decrease even further.

Although the Web affords everyone the right of individuality in design, if you are creating a site for your business, you might want to avoid a highly patterned background with contrasting colored text.

If you do use a tiled, patterned background image for your entire site, remember that tiled images look best when you can’t tell they’re tiled images. In other words, you know you have a good image when the top edge of a background tile matches seamlessly with the bottom edge, and the left edge matches with the right.

Figures 8.10 and 8.11 show background tiles in use, both with seamless background, but with varying degrees of effectiveness.

FIGURE 8.10
This is an example of a seamless background image whereby you can tell the background is tiled because you can see six identical shapes.
FIGURE 8.11
This is also an example of a seam- less background image, only you can’t tell that it is tiled.

Further on in this chapter, you’ll learn how to place background images within your container elements. Despite my warnings in this section, there are actually times when background images can be powerful weapons in your design arsenal—just not when used as entire page backgrounds.

Creating Animated Web Graphics

The GIF image format enables you to create animated images that can be used to add some motion that will spice up any web page. Animated GIF images also transfer much faster than most of the video or multimedia files that are often used for similar effect. With GIMP, you can create animated GIFs by creating multiple layers within an image, and then modifying the Animated GIF options when saving the file. Additionally, if you have a series of images you want to animate, you can use the free, web-based GIF animation service at Gickr (http://www.gickr.com/).

The first step in creating a GIF animation is to create a series of images to be displayed one after the other—or a series of layers, depending on your particular software program. Each of these images is called a frame. By the way, this use of the word frame has nothing whatsoever to do with the frames you’ll learn about in Chapter 20, “Using Windows and Frames.” Instead, think of the frames like how movies or cartoons are put together—the images that you see on the screen are made up of many individual frames with slight differences in their appearance. After you have your frames in mind, the process of tying them together is relatively simple—it’s the planning stage that’s the most difficult. Take some time to sketch out the frames in storyboard fashion, especially if you plan to have more than just a few frames. After you know how your frames are going to fit together, use the Gickr service mentioned earlier in this section, or read the documentation for your graphics software to learn its particular process for pulling it all together.

Placing Images on a Web Page

To put an image on a web page, first move the image file into the same fold- er as the HTML file or in a directory named images for easy organization.

Insert the following HTML tag at the point in the text where you want the image to appear. Use the name of your image file instead of myimage.gif:

<img src=”myimage.gif” alt=”My Image” />

If your image file were in the images directory below the document root, you would use the following:

<img src=”/images/myimage.gif” alt=”My Image” />

Both the src and the alt attributes of the <img /> tag are required in XHTML web pages. The src attribute identifies the image file, and the alt attribute enables you to specify descriptive text about the image, the latter of which is intended to serve as

an alternative to the image in the event that a user is unable to view the image. You’ll read more on the alt attrib- ute later, in the section “Describing Images with Text.”

As an example of how to use the <img /> tag, Listing 8.2 inserts an image at the top of the page, before a paragraph of text. Whenever a web browser displays the HTML file in Listing 8.2, it automatically retrieves and dis- plays the image file, as shown in Figure 8.12.

LISTING 8.2     Using the <img /> Tag to Place Images on a Web Page       

<?xml version=”1.0” encoding=”UTF-8”?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
“http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>


<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en”>
<head>
<title>A Spectacular Yosemite View</title>
</head>

<body>
<h1>A Spectacular Yosemite View</h1>
<p><img src=”hd.jpg” alt=”Half Dome” /></p>
<p><strong>Half Dome</strong> is a granite dome in Yosemite National
➥Park,
located in northeastern Mariposa County, California, at the eastern end of Yosemite Valley. The granite crest rises more than 4,737 ft (1,444 m) above the valley floor.</p>
<p>This particular view is of Half Dome as seen from Washburn Point.</p>
</body>
</html>
FIGURE 8.12
When a web browser displays the HTML code shown in Listing 8.2, it renders the hd.jpg image.

If you guessed that img stands for image, you’re right. And src stands for source, which is a reference to the location of the image file. As discussed at the beginning of this book, an image is always stored in a file separate from the text, even though it appears to be part of the same page when viewed in a browser.

Just as with the <a href> tag used for hyperlinks, you can specify any complete Internet address in the src attribute of the <img /> tag.

Alternatively, if an image is located in the same folder as the HTML file, you can specify just the filename. You can also use relative addresses, such as /images/birdy.jpg or ../smiley.gif.

Describing Images with Text

Each <img /> tag in Listing 8.2 includes a short text message, such as alt=”Half Dome”. The alt stands for alternate text, which is the message that appears in place of the image itself if it does not load. An image might not load if its address is incorrect, if the user has turned off automatic image downloading in her web browser preferences, or if the Internet connection is very slow and the data has yet to transfer. Figure 8.13 shows an example of alt text used in place of an image.

FIGURE 8.13
Users will see alt messages when images do not appear.

Even when graphics have fully loaded and are visible in the web browser, the alt message typically appears in a little box (known as a tool tip) whenever the mouse pointer passes over an image. The alt message also helps any user who is visually impaired (or is using a voice-based interface to read the web page).

You must include a suitable alt attribute in every <img /> tag on your web page, keeping in mind the variety of situations in which people might see that message. A brief description of the image is usually best, but web page authors sometimes put short advertising messages or subtle humor in their alt messages; too much humor and not enough information is frowned upon, however. For small or unimportant images, it’s tempting to omit the alt message altogether, but it is a required attribute of the <img /> tag.

This doesn’t mean your page won’t display properly, but it does mean you’ll be in violation of the latest XHTML standards. I recommend assigning an empty text message to alt if you absolutely don’t need it (alt=””), which is sometimes the case with small or decorative images. The title attribute is not required by the <img /> tag, but it functions similarly to the   alt attribute; in fact, the title attribute supersedes the alt attribute for tool tips if both attributes are present. Knowing this, the best approach for describing images via text is to use both the alt attribute and the title attribute to provide relevant notation or helpful hints about the image that you think might be useful when viewed as a tool tip or via screen reader software.

Specifying Image Height and Width

Because text moves over the Internet much faster than graphics, most web browsers display the text on a page before they display images. This gives users something to read while they’re waiting to see the pictures, which makes the whole page seem to load faster.

You can make sure that everything on your page appears as quickly as possible and in the right places by explicitly stating each image’s height and width. That way, a web browser can immediately and accurately make room for each image as it lays out the page and while it waits for the images to finish transferring.

For each image you want to include in your site, you can use your graphics program to determine its exact height and width in pixels. You might also be able to find these image properties by using system tools. For example, in Windows, you can see an image’s height and width by right- clicking on the image, selecting Properties, and then selecting Details. After you know the height and width of an image, you can include its dimen- sions in the <img /> tag, like this:

<img src=”myimage.gif” alt=”Fancy Picture” width=”200” height=”100” />

Aligning Images

Just as you can align text on a page, you can align images on the page using special attributes. Not only can you align images horizontally, you also can align them vertically with respect to text and other images that surround them.

Horizontal Image Alignment

As discussed in Chapter 5, “Working with Fonts, Text Blocks, and Lists,” you can use <div style=”text-align:center”>, <div style=”text- align:right”> and <div style=”text-align:left”> to align an element to the center, to the right margin, or to the left margin. These style settings affect both text and images and can be used within the <p> tag as well. Like text, images are normally lined up with the left margin unless a style=”text-align:center” or style=”text-align:right” setting indi- cates that they should be centered or right-justified. In other words, left is the default value of the text-align style property.

You can also wrap text around images by using the float style property directly within the <img /> tag.

In Listing 8.3, <img style=”float:left” /> aligns the first image to the left and wraps text around the right side of it, as you might expect.

Similarly, <img style=”float:right” /> aligns the second image to the right and wraps text around the left side of it. Figure 8.14 shows how these images align on a web page. There is no concept of floating an image to the center because there would be no way to determine how to wrap text on each side of it.

LISTING 8.3     Using text-align Styles to Align Images on a Web Page

<?xml version=”1.0” encoding=”UTF-8”?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
“http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en”>
<head>
<title>More Spectacular Yosemite Views</title>
</head>

<body>
<h1>More Spectacular Yosemite Views</h1>
<p><img src=”elcap_sm.jpg” alt=”El Capitan” width=”100” height=”75” style=”float:left; padding: 6px;”/><strong>El Capitan</strong> is a 3,000-foot (910 m) vertical rock formation in Yosemite National Park, located on the north side of Yosemite Valley, near its western end. The granite monolith is one of the world’s favorite challenges for rock climbers. The formation was named “El Capitan” by the Mariposa Battalion when it explored the valley in 1851.</p>
<p><img src=”tunnelview_sm.jpg” alt=”Tunnel View” width=”100” height=”80” style=”float:right; padding: 6px;”/><strong>Tunnel View</strong> is a viewpoint on State Route 41 located directly east of the Wawona Tunnel as one enters Yosemite Valley from the south.
The view looks east into Yosemite Valley including the southwest face of El Capitan, Half Dome, and Bridalveil Falls. This is, to many, the first views of the popular attractions in Yosemite.</p>
</body>
</html>
FIGURE 8.14
Showing the image alignment from Listing 8.3.

Vertical Image Alignment

Sometimes, you might want to insert a small image in the middle of a line of text; or you might like to put a single line of text next to an image as a caption. In either case, it would be handy to have some control over how the text and images line up vertically. Should the bottom of the image line up with the bottom of the letters, or should the text and images all be arranged so that their middles line up? You can choose between these and several other options:

. To line up the top of an image with the top of the tallest image or letter on the same line, use <img style=”vertical-align:text-top” />.

. To line up the bottom of an image with the bottom of the text, use

<img style=”vertical-align:text-bottom” />.

. To line up the middle of an image with the overall vertical center of everything on the line, use <img style=”vertical-align:middle” />.

. To line up the bottom of an image with the baseline of the text, use

<img style=”vertical-align:baseline” />.

All four of these options are used in Listing 8.4 and displayed in Figure

8.15. Four thumbnail images are now listed vertically down the page, along with descriptive text next to each image. Various settings for the vertical align style property are used to align each image and its relevant text.

LISTING 8.4     Using vertical-align Styles to Align Text with Images       

<?xml version=”1.0” encoding=”UTF-8”?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
“http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en”>
<head>
<title>Small But Mighty Spectacular Yosemite Views</title>
</head>

<body>
<h1>Small But Mighty Yosemite Views</h1>
<p><img src=”elcap_sm.jpg” alt=”El Capitan” width=”100” height=”75” style=”vertical-align:text-top;”/><strong>El Capitan</strong> is a 3,000-foot (910 m) vertical rock formation in Yosemite National Park.</p>
<p><img src=”tunnelview_sm.jpg” alt=”Tunnel View” width=”100” height=”80” style=”vertical-align:text-bottom;”/><strong>Tunnel View</strong> looks east into Yosemite Valley.</p>
<p><img src=”upperyosefalls_sm.jpg” alt=”Upper Yosemite Falls” width=”87” height=”100” style=”vertical-align:middle;”/><strong>Upper Yosemite Falls</strong> are 1,430 ft and are among the twenty highest waterfalls in the world. </p>
<p><img src=”hangingrock_sm.jpg” alt=”Hanging Rock” width=”100” height=”75” style=”vertical-align:baseline;”/><strong>Hanging Rock</strong>, off Glacier Point, used to be a popular spot for people to, well, hang from. Crazy people.</p>
</body>
</html>
FIGURE 8.15
Showing the vertical image alignment options used in Listing 8.4.

Turning Images into Links

You probably noticed in Figure 8.12 that the image on the page is quite large, which is fine in this particular example but isn’t ideal when you’re trying to present multiple images. It makes more sense in this case to create smaller image thumbnails that link to larger versions of each image. Then, you can arrange the thumbnails on the page so that visitors can easily see all the content, even if they see only a smaller version of the actual (larger) image. Thumbnails are one of the many ways you can use image links to spice up your pages.

To turn any image into a clickable link to another page or image, you can use the <a href> tag that you used previously to make text links. Listing contains the code for a modification of Listing 8.3—which already used thumbnails—to provide links to larger versions of the images. To ensure that the user knows to click the thumbnails, the image and some helper text is enclosed in a <div>, as shown in Figure 8.16.

LISTING 8.5     Using Thumbnails for Effective Image Links                     

<?xml version=”1.0” encoding=”UTF-8”?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
“http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en”>
<head>
<title>More Spectacular Yosemite Views</title>
<style type=”text/css”> div.imageleft {
float:left; clear: all;
text-align:center; font-size:9px; font-style:italic;
}
div.imageright { float:right; clear: all;
text-align:center; font-size:9px; font-style:italic;
}
img { padding: 6px; border: none;
}
</style>
</head>
<body>
<h1>More Spectacular Yosemite Views</h1>
<p><div class=”imageleft”>
<a href=”http://www.flickr.com/photos/nofancyname/614253439/”><img src=”elcap_sm.jpg” alt=”El Capitan” width=”100” height=”75”/></a>
<br/>click image to enlarge</div><strong>El Capitan</strong>
is a 3,000-foot (910 m) vertical rock formation in Yosemite National Park, located on the north side of Yosemite Valley, near its western end. The granite monolith is one of the world’s favorite challenges for rock climbers. The formation was named “El Capitan” by the Mariposa Battalion when it explored the valley in 1851.</p>
<p><div class=”imageright”>
<a href=”http://www.flickr.com/photos/nofancyname/614287355/”><img src=”tunnelview_sm.jpg” alt=”Tunnel View” width=”100” height=”80”/></a>
<br/>click image to enlarge</div><strong>Tunnel View</strong> is a viewpoint on State Route 41 located directly east of the Wawona Tunnel as one enters Yosemite Valley from the south. The view looks east into Yosemite Valley including the southwest face of El Capitan, Half Dome, and Bridalveil Falls. This is, to many, the first views of the popular attractions in Yosemite.</p>
</body>
</html>
FIGURE 8.16
Using thumbnails as links improves the layout of a page that uses large images.

The code in Listing 8.5 uses additional styles that will be explained in more detail in later chapters, but you should be able to figure out the basics:

. The <a> tags link these particular images to larger versions, which in this case are stored on an external server (at Flickr).

. The <div> tags, and their styles, are used to align those sets of graph- ics and caption text (and also include some padding).

Unless instructed otherwise, web browsers display a colored rectangle around the edge of each image link. Like text links, the rectangle usually appears blue for links that haven’t been visited recently or purple for links that have been visited recently—unless you specify different colored links in your style sheet. Because you seldom, if ever, want this unsightly line around your linked images, you should usually include style=”border:none” in any <img /> tag within a link. In this instance, the border:none style is made part of the style sheet entry for the img ele- ment because we use the same styles twice.

When you click one of the thumbnail images on the sample page shown, the link is opened in the browser, as shown in Figure 8.17.

FIGURE 8.17
Clicking a linked thumbnail image opens the target of the link.

Using Background Images

As you learned earlier in this chapter, you can use background images to act as a sort of wallpaper in a container element, so that the text or other images appear on top of this underlying design.

The basic style properties that work together to create a background are as follows:

  • . background-color—Specifies the background color of the element. Although not image-related, it is part of the set of background-related properties.
  • . background-image—Specifies the image to use as the background of the element using the following syntax: url(‘imagename.gif’).
  • . background-repeat—Specifies how the image should repeat, both horizontally and vertically. By default (without specifying anything), background images will repeat both horizontally and vertically. Other options are repeat (same as default), repeat-x (horizontal), repeat-y (vertical), and no-repeat (only one appearance of the graphic).
  • . background-position—Specifies where the image should be initially placed relative to its container. Options include top-left, top-center, top-right, center-left, center-center, center-right, bottom-left, bottom-center, bottom-right, and specific pixel and percentage placements.

When specifying a background image, you can put all of these specifica- tions together into one property, like so:
body {
background: #ffffff url(‘imagename.gif’) no-repeat top right;
}

In the previous style sheet entry, the body element of the web page will be white and include a graphic named imagename.gif on the top right. Another use for the background property is the creation of custom bullets for your unordered lists. To use images as bullets, first define the style for the <ul> tag as follows:

ul {
list-style-type: none; padding-left: 0;
margin-left: 0;
}

Next, change the declaration for the <li> tag to:
li {
background: url(mybullet.gif) left center no-repeat
}

Make sure that mybullet.gif (or whatever you name your graphic) is on the web server and accessible; in that case, all unordered list items will show your custom image rather than the standard-filled disc bullet. We will return to the specific use of background properties in Part III, “Advanced Web Page Design with CSS,” when using CSS for overall page layouts.

Using Imagemaps

Sometimes you might want to use an image as navigation, but beyond the simple button-based or link-based navigation that you often see in websites. For example, perhaps you have a website with medical information, and you want to show an image of the human body that links to pages that pro- vide information about various body parts. Or, you have a website that pro- vides a world map users can click to access information about countries.

You can divide an image into regions that link to different documents, depending on where users click within that image. This is called an imagemap, and any image can be made into an imagemap.

Why Imagemaps Aren’t Always Necessary

The first thing you should know about imagemaps is that you probably won’t need to use them except in very special cases. It’s almost always easi- er and more efficient to use several ordinary images that are placed directly next to one another and provide a separate link for each image.

For example, see Figure 8.18. This is a web page that shows 12 different corpo- rate logos; this example is a common type of web page in the business world, one in which you give a little free advertisement to your partners. You could present these logos as one large image and create an imagemap that provides links to each of the 12 companies. Users could click each logo in the image to visit each company’s site. Or, you could display the images on the page as in this example and use 12 separate images—one for each company—with each image including a link to that particular company.

An imagemap is the best choice for an image that has numerous parts, is oddly arranged, or the design of the image itself might be too complicated to divide into separate images. Figure 8.19 shows an image that is best suit- ed as an imagemap.

Mapping Regions Within an Image

To create any type of imagemap, you need to figure out the numerical pixel coordinates of each region within the image that you want to turn into a click- able link. These clickable links are also known as areas. Your graphics program might provide you with an easy way to find these coordinates. Or you might want to use a standalone imagemapping tool such as Mapedit (http://www.boutell.com/mapedit/) or the online imagemap maker at http://www.image-maps.com/. In addition to helping you map the coordinates, these tools also provide the HTML code necessary to make the maps work.

FIGURE 8.18
Web page with 12 different logos; this could be presented as a single imagemap or divided into 12 separate pieces.
FIGURE 8.19
An image that wouldn’t take well to being sliced up—better make it an imagemap.

Using an imagemapping tool is often as simple as using your mouse to draw a rectangle (or a custom shape) around the area you want to be a link. Figure 8.20 shows the result of one of these rectangular selections as well as the interface for adding the URL and the title or alternate text for this link. Several pieces of information are necessary to creating the HTML for your imagemap: coordinates, target URL, title of link, and alternative text for the link.

FIGURE 8.20
Using an imagemapping tool to create linked areas of a single graphic.

Creating the HTML for an Imagemap

If you use an imagemap generator, you will already have the HTML neces- sary for creating the imagemap. However, it is a good idea to understand the parts of the code so that you can check it for accuracy. The following HTML code is required to start any imagemap:

<map name=”mapname”>

Keep in mind that you can use whatever name you want for the name of the

<map> tag, although it helps if you make it as descriptive as possible. Next, you’ll need an <area /> tag for each region of the image. Following is an example of a single <area /> tag that is used in the mapping-a-map imagemap example:

<area shape=”rect” coords=”100,136,116,152” href=” http://www.whitmancounty.org/” alt=” Whitman County, WA”

title=”Whitman County, WA” />

This <area /> tag has five attributes, which you will use with every area you describe in an imagemap:

. shape indicates whether the region is a rectangle (shape=”rect”), a circle (shape=”circle”), or an irregular polygon (shape=”poly”).

. coords gives the exact pixel coordinates for the region. For rectangles, give the x,y coordinates of the upper-left corner followed by the x,y coordinates of the lower-right corner. For circles, give the x,y center point followed by the radius in pixels. For polygons, list the x,y coor- dinates of all the corners in a connect-the-dots order.

. href specifies the page to which the region links. You can use any address or filename that you would use in an ordinary <a href> link tag.

. alt enables you to provide a piece of text that is associated with the shape. Most browsers (Firefox excluded) display this text in a small box when a user hovers his mouse over the shape. This text adds a subtle but important visual cue to users who might not otherwise realize that they are looking at an imagemap. Firefox correctly uses the title attribute in addition to the alt attribute to provide a visual cue, which is why, as noted previously in this chapter, you should use both attributes.

Each distinct clickable region in an imagemap must be described as a single area, which means a typical imagemap consists of a list of areas. After coding the <area /> tags, you are done defining the imagemap, so wrap things up with a closing </map> tag.

The last step in creating an imagemap is wiring it to the actual map image. The map image is placed on the page using an ordinary <img /> tag.

However, there is an extra usemap attribute that is coded like this:

<img src=”map.png” usemap=”#countymap” style=”border:none; width:650px; height:509px” alt=”Native Peoples Census Map” />

When specifying the value of the usemap attribute, use the name you put in the id of the <map> tag (and don’t forget the # symbol). Also include the style attribute to specify the height and width of the image and to turn off the border around the imagemap, which you might or might not elect to keep in imagemaps of your own.

Listing 8.6 shows the complete code for a sample web page containing the map graphic, its imagemap, and a few mapped areas.

LISTING 8.6     Defining the Regions of an Imagemap with <map> and <area /> Tags

<?xml version=”1.0” encoding=”UTF-8”?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en”>
<head>
<title>Testing an Imagemap</title>
</head>

<body>
<h1>Testing an Imagemap</h1>
<p style=”text-align:center”>Click on a logo to go to the county’s web site.<br/>
<img src=”map.png” usemap=”#countymap” style=”border:none; width:650px;height:509px” alt=”Native Peoples Census Map” /></p>

<map name=”countymap” id=”countymap”>
<area shape=”rect” coords=”100,136,116,152” href=”http://www.whitmancounty.org/”
alt=”Whitman County, WA” title=”Whitman County, WA” />
<area shape=”rect” coords=”29,271,42,283” href=”http://www.sccgov.org/” alt=”Santa Clara County, CA” title=”Santa Clara County, CA” />
<area shape=”rect” coords=”535,216,548,228” href=”http://visitingmifflincounty.com/”
alt=”Mifflin County, PA” title=”Mifflin County, PA” />
</map>
</body>
</html>

Figure 8.21 shows the imagemap in action. Notice in the bottom of your browser window that your browser (in this example, Firefox) displays the link address for whatever area the mouse is hovering over. Additionally, when you hover the mouse over an area, the alt or title text for that area—in this example, Whitman County—is displayed on the imagemap.

FIGURE 8.21
The imagemap defined in Listing 8.6
as it displays on the web page.

Integrating Multimedia into Your Website

Now that you’ve learned how to work with static images, the natural next step is to work with multimedia. The term multimedia encompasses everything we see and hear on a web page: audio, video, and animation, as well as static images and text. In this section, you won’t learn how to create any particular audio, video, or animation, but you will learn how to include such files in your site, through either linking or embedding the content.

Remember, though, that not every user has devices that will play your media type, nor do all users have broadband Internet connections which allow these large files to transfer quickly. Always warn your visitors that the links they click will take them to multimedia files and offer them the choice to view or listen to the content don’t force the files upon them.

Creating multimedia of any kind can be a challenging and complicated task. If you’re planning to create your own content from scratch, you’ll need far more than this book to become the next crackerjack multimedia developer. After you have some content, however, this section will show you how to place your new creations into your web pages.

For those of us who are artistically challenged, several alternative ways to obtain useful multimedia assets are available. Aside from the obvious (such as hiring an artist), here are a few suggestions:

. Much of the material on the Internet is free. Of course, it’s still a good idea to double-check with the author or current owner of the content; you don’t want to be sued for copyright infringement. In addition, various offices of the U.S. government generate content which, by law, belongs to all Americans. (For example, any NASA footage found online is free for your use.)

. Many search engines (google.com, yahoo.com, bing.com, and so on) have specific search capabilities for finding multimedia files. As long as you are careful about copyright issues, this can be an easy way to find multimedia related to a specific topic. A simple search for sample Flash animations, sample QuickTime movie, or sample audio files will produce more results than you can handle.

. If you are creatively inclined, determine the medium you like most— for some of you it might be video production, others may enjoy audio production, and still others might want to dabble in animation. After you have determined a starting point, look into the various types of software which will enable you to create such artistic masterpieces.

Many companies provide multimedia software, such as Adobe (http://www.adobe.com/) and Apple (http://www.apple.com/).

Linking to Multimedia Files

The simplest and most reliable option for incorporating a video or audio file into your website is to simply link it in with <a href>, exactly as you would link to another HTML file.

For example, the following line could be used to offer a MOV video of a hockey game:

<a href=”hockey.mov”>View the hockey video clip.</a>

When the user clicks the words View the hockey video clip., the hockey.mov QuickTime video file is transferred to her computer from your web server. Whichever helper application or plug-in she has installed automatically starts as soon as the file has finished downloading. If no compatible helper or plug-in can be found, the web browser will offer her a chance to download the appropriate plug-in or save the video on her hard drive for later viewing.

The click action results in the browser either playing the video with the help of a plug-in (if one is found that can play the clip) or deferring to a suitable helper application.

If you change the link from pond.wmv (Windows Media) to pond.mov (QuickTime), your browser handles the link differently. Instead of launching another program, the QuickTime plug-in enables you to view the movie clip directly in the browser window.

As you might have guessed, this approach of using a simple link to play multimedia files offers the best backward compatibility because the browser bears all the responsibility of figuring out how to play a multimedia clip.

The downside to this is that you don’t have much control over how a clip is played, and you definitely can’t play a clip directly in the context of a page.

Embedding Multimedia Files

XHTML contains a standard <object> tag that is the preferred way to embed multimedia of any kind in a web page. This tag is used instead of the old <embed /> tag that you might still see in some HTML source code.

Embedding a multimedia file into a page produces a set of software controls that allow the file to be played directly—no secondary window is necessary, and there’s no need to navigate away from the page you are on.

Following is code to embed the pond video using the <object> tag by itself:

<object classid=”CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6”
width=”320” height=”305”>
<param name=”type” value=”video/x-ms-wmv” />
<param name=”URL” value=”pond.wmv” />
<param name=”uiMode” value=”full” />
<param name=”autoStart” value=”false” />
</object>

This code isn’t too terribly complicated when you consider that it literally embeds a video directly into your web page (see Figure 8.22). The messiest part of the code is the classid attribute of the <object> tag, which is set to a long alphanumeric code. This code is the global ID for Windows Media Player, which means that you’re telling the <object> tag to embed Windows Media Player on the page to play the video clip. You can just copy and paste this code into your own web pages.

FIGURE 8.22
The <object> tag enables you to embed a video clip on a web page while specifying which media player is to play it.

The width and height attributes of the <object> tag determine the size of the embedded Windows Media Player window. Some browsers will automatically size the embedded player to fit the content if you leave these attributes off, whereas others won’t show anything at all. Play it safe by setting them to a size that suits the multimedia content being played.

There are four <param> tags within the <object> tag that are responsible for additional details about how the clip is to be played. Each tag has two attributes, name and value, which are responsible for associating data (value) with a particular setting (name). In this example, the URL for the media clip is set to pond.wmv. The third parameter, uiMode, determines which buttons and user interface options are made available by Windows Media Player—full indicates that all user interface features are enabled, such as the control buttons and volume slider. Finally, the autoStart parameter is set to false so that the video clip does not automatically start playing when the page is opened in a browser.

The type parameter is perhaps the trickiest. It identifies the type of media being displayed, which in this case is a Windows Media Video (WMV) file. This media type must be specified as one of the standard Internet MIME types.

A MIME type is an identifier for uniquely identifying different types of media objects on the Internet. MIME stands for Multipurpose Internet Mail Extensions, and this name comes from the fact that MIME types were originally used to identify email attachments. These MIME types should be used in the type attribute of the <object> tag to identify what kind of multimedia object is being referenced in the data attribute.

Following are the MIME types for several popular sound and video for- mats you might want to use in your web pages:

  • . WAV Audio—audio/x-wav
  • . AU Audio—audio/basic
  • . MP3 Audio—audio/mpeg
  • . MIDI Audio—audio/midi
  • . WMA Audio—audio/x-ms-wma
  • .   RealAudio—audio/x-pn-realaudio-plugin
  • . AVI—video/x-msvideo
  • . WMV—video/x-ms-wmv
  • . MPEG Video—video/mpeg
  • . QuickTime—video/quicktime

Listing 8.7 shows the relevant code for the pond web page, where you can see the <object> tag as it appears in context..

LISTING 8.7        Using an <object> Tag to Directly Embed a WMV Video Clip

<?xml version=”1.0” encoding=”UTF-8”?>
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.1//EN”
“http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd”>

<html xmlns=”http://www.w3.org/1999/xhtml” xml:lang=”en”>
<head>
<title>Fun in the Pond</title>
</head>

<body>
<h1>Fun in the Pond</h1>
<div style=”float:left; padding:3px”>
<object classid=”CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6”
width=”320” height=”305”>
<param name=”type” value=”video/x-ms-wmv” />
<param name=”URL” value=”pond.wmv” />
<param name=”uiMode” value=”full” />
<param name=”autoStart” value=”false” />
<embed width=”320” height=”305” type=”video/x-ms-wmv” src=”pond.wmv” controls=”All” loop=”false” autostart=”false” pluginspage=”http://www.microsoft.com/windows/windowsmedia/” />
</object>
</div>
<p>Michael’s backyard pond is not only a fun hobby but also an ongoing home improvement project that is both creative and relaxing.</p>
<p>He has numerous fish in the pond, all Koi from various places as far as Japan, Israel, and Australia. Although they don’t bark, purr, or fetch anything other than food, these fish are his pets, and good ones at that.</p>
</body>
</html>

You might notice that there’s some extra code that didn’t appear in the earlier <object> tag example. Unfortunately, as discussed earlier in the section, not all web browsers are entirely consistent in their support of the <object> tag. For this reason, it is necessary to include an <embed/> tag within the<object> tag to account for browser inconsistencies. This isn’t an ideal solution, but it’s all we have while browser vendors continue to lag behind pre- vailing standards. If you pay close attention, you’ll notice that the <embed/> tag contains all the same information as the <object> tag. The <object> tag is a bit more complex than what is revealed here. However, you don’t need to know how to use the more advanced facets of the <object> tag just to play multimedia content. In other words, it isn’t important for you to become a multimedia guru to share some multimedia clips on your web pages.

Additional Tips for Using Multimedia

Before you add video, audio, or animations to your website, first ask yourself if you really should. When you use these types of multimedia, be sure to do so for a reason. Gratuitous sound and video, just like gratuitous images, can detract from your overall message. Then again, if your message is “Look at the videos I have made” or “Listen to my music and download some songs,” then multimedia absolutely must play a role in your website.

Here are a few additional tips to keep in mind:

  • . Don’t include multimedia in a page and set it to automatically play when the page loads. Always give users the option to start (and stop) your sound or video.
  • . When possible, give users a choice of multimedia players. Don’t limit yourself to multimedia content playable by only one type of player on only one operating system.
  • . Multimedia files are larger than the typical graphics and text files, which means you need to have the space on your web server to store them, as well as the bandwidth allotment to transfer them to whomever requests them via your website.
  • . If your site is entirely audio or video and offers very little by way of text or graphics, understand that a certain segment of your audience won’t see or hear what you want to present because of the limitations of their system or bandwidth. Provide these users with additional options to get your information.
  • . Leverage free online video hosting services, such as YouTube (http://www.youtube.com/). Not only does YouTube provide storage for your video clips, it will provide you with the code necessary to embed the video in your own web page. For example, Figure 8.23 shows the YouTube page for the cutest puppy in the world. If you copy and paste the text from the Embed area shown in the figure, you would get the following:
<object width=”425” height=”344”>
<param name=”movie” value=”http://www.youtube.com/v/yPxiHd2BOpo &rel=0&color1=0xb1b1b1&color2=0xcfcfcf&feature=player_profilepage &fs=1”></param>
<param name=”allowFullScreen” value=”true”></param>
<param name=”allowScriptAccess” value=”always”></param>
<embed src=”http://www.youtube.com/v/yPxiHd2BOpo&rel=0&color1=0xb1b1b1 &color2=0xcfcfcf&feature=player_profilepage&fs=1” type=”application/x-shockwave-flash” allowfullscreen=”true” allowScriptAccess=”always” width=”425” height=”344”></embed>
</object>

You could then insert the code into your web page.

FIGURE 8.23
YouTube provides storage of your video files as well as links and
<object> code for use in your own pages.

Summary

In this chapter, you learned a few best practices for thinking about color use, and how to use the color wheel to help you find colors that will com- plement your text. Additionally, you learned about hexadecimal notion for colors—that all colors are expressed in notations related to the amount of red, green, and blue in them—and how hexadecimal notation enables you to apply nuanced colors to your elements. More importantly, you learned about the three color-related style properties that can be used to apply color to container backgrounds, borders, and text using CSS.

You also learned the basics of preparing graphics for use on web pages. If nothing else, you learned that this is a very complex topic, and you learned just enough in this chapter to whet your appetite. The examples in this chapter used the popular (and free!) GIMP software package, but feel free to use the graphics software that best suits your needs. Among the actions you learned were how to crop, resize, and tweak image colors, and you also learned about the different file formats. There are many consider- ations you must keep in mind when including graphics in your site, including graphic size and resolution and how to use transparency, ani- mated GIFs, and tiled backgrounds.

After you have created or edited some images, you can place them in your web page, which you also learned how to do through the <img /> tag. You

learned how to include a short text message that appears in place of the image as it loads and also appears whenever users move the mouse pointer over the image. You also discovered how to control the horizontal and vertical align- ment of each image and how to wrap text around the left or right of an image.

You learned how to use images as links—either by using the <a> tag around the images or by creating imagemaps. You also learned a little bit about how to use images in the background of container elements.

Finally, you learned how to embed video and sound into a web page. You discovered how to use a simple link to a multimedia file, which is the most broadly supported but least flexible option for playing media content. You then learned how to use the <object> tag to embed a media player directly in a web page. Not only that, you discovered that for maximum browser compatibility, it helps to assist the <object> tag with the <embed /> tag. The <object> and <embed /> tags can be used to include a vast array of media types, including WAV, MP3, RealAudio, and MIDI files—not to mention AVI, WMV, and QuickTime videos, to name just a few.

Table 8.1 summarizes the tags and attributes covered in this chapter.