Chapter 2
Writing and Styling Pages in HTML and CSS

What You’ll Learn in This Chapter:

Image Introducing HTML

Image Elements of an HTML Page

Image A More Advanced HTML Page

Image Some Useful HTML Tags

Image Adding Your Own Style

Image Defining the Rules

Image Add a Little class

Image Applying Styles

Image Formatting Text with Styles

Image Adding Lines

In this chapter we introduce HTML, the markup language behind virtually every page of the World Wide Web. A sound knowledge of HTML provides an excellent foundation for the Ajax applications discussed in later chapters.

Introducing HTML

It wouldn’t be appropriate to try to give an exhaustive account of HTML (Hypertext Markup Language)—or, indeed, any of the other component technologies of Ajax—within this book. Instead we’ll review the fundamental principles and give some code examples to illustrate them, paying particular attention to the subjects that will become relevant when we start to develop Ajax applications.

What Is HTML?

The World Wide Web is constructed from many millions of individual pages, and those pages are, in general, written in Hypertext Markup Language, better known as HTML.

That name gives away a lot of information about the nature of HTML. We use it to mark up our text documents so that web browsers know how to display them and to define hypertext links within them to provide navigation within or between them.

Anyone who (like me) can remember the old pre-WYSIWYG word processing programs will already be familiar with text markup. Most of these old applications required that special characters be placed at the beginning and end of sections of text that you wanted to be displayed as (for instance) bold, italic, or underlined text.

What Tools Are Needed to Write HTML?

Because the elements used in HTML markup employ only ordinary keyboard characters, all you really need is a good text editor to construct HTML pages. Many are available, and most operating systems have at least one such program already installed. If you’re using some version of Windows, for example, the built-in Notepad application works just fine.

Image

Although Notepad is a perfectly serviceable text editor, many so-called programmers’ editors are available offering useful additional functions such as line numbering and syntax highlighting. Many of these are under open source licences and can be downloaded and used at no cost. It is well worth considering using such an editor, especially for larger or more complex programming tasks.

The use of word processing software can cause problems due to unwanted markup and other symbols that such programs often embed in the output code. If you choose to use a word processor, make sure that it is capable of saving files as plain ASCII text.

Image

The CD accompanying this book contains the popular and capable jEdit program-mer’s editor.

Our First HTML Document

Let’s jump right in and create a simple HTML document. Open your chosen editor and enter the text shown in Listing 2.1. The HTML markup elements (often referred to as tags) are the character strings enclosed by < and >.

Listing 2.1 testpage.html

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” ”http://www.w3.org/TR/html4/loose.dtd”>
<html>
<head>
<title>A Simple HTML Document </title>
</head>
<body>
<h1>My HTML Page</h1>
Welcome to my first page written in HTML.<br />
This is simply a text document with HTML markup to show some
words in <b>bold</b> and some other words in <i>italics</i>.
<br />
</body>
</html>

Now save the document somewhere on your computer, giving it the name testpage.html.

If you now load that page into your favorite browser, such as Internet Explorer or Firefox, you should see something like the window displayed in Figure 2.1.

Figure 2.1 Our test document displayed in Internet Explorer.

Image

Elements of an HTML Page

Let’s look at Listing 2.1 in a little more detail.

The first element on the page is known as the DOCTYPE element. Its purpose is to notify the browser of the “flavor” of HTML used in the document. The DOCTYPE element used throughout this book refers to HTML 4.0 Transitional, a fairly forgiving version of the HTML specification that allows the use of some earlier markup styles and structures in addition to the latest HTML 4.0 specifications.

The DOCTYPE element must always occur right at the beginning of the HTML document.

Next, note that the remainder of the document is enclosed by the elements <html> at the start of the page and </html> at the end. These tags notify the browser that what lies between should be interpreted and displayed as an HTML document.

Image

Although many modern browsers correctly display HTML without these tags, it is bad practice to omit them. Even if the page is shown correctly on your own PC, you have no idea what operating system and browser a visitor may be using—he or she may not be so lucky.

The document within these outer tags is split into two further sections. The first is enclosed in <head> and </head> tags, and the second is contained between <body> and </body>. Essentially, the document’s head section is used to store information about the document that is not to be displayed in the browser window, whereas the body of the document contains text to be interpreted and displayed to the user via the browser window.

The <head> of the Document

From Listing 2.1 we can see that the head section of our simple HTML document contains only one line—the words A Simple HTML Document enclosed in <title> and </title> tags.

Remember that the head section contains information that is not to be displayed in the browser window. This is not, then, the title displayed at the top of our page text, as you can confirm by looking again at Figure 2.1. Neither does the document title refer to the filename of the document, which in this case is testpage.html.

In fact, the document title fulfils a number of functions, among them:

Image Search engines often use the page title (among other factors) to help them decide what a page is about.

Image When you bookmark a page, it is generally saved by default as the document title.

Image Most browsers, when minimized, display the title of the current document on their icon or taskbar button.

It’s important, therefore, to choose a meaningful and descriptive title for each page that you create.

Many other element types are used in the head section of a document, including link, meta, and script elements. Although we don’t give an account of them here, they are described throughout the book as they occur.

The Document <body>

Referring again to Listing 2.1, we can clearly see that the content of the document’s body section is made up of the text we want to display on the page, plus some tags that help us to define how that text should look.

To define that certain words should appear in bold type, for example, we enclose those words in <b> and </b> tags. Similarly, to convert certain words into an italic typeface, we can use the <i> and </i> tags.

The heading, My HTML Page, is enclosed between <h1> and </h1> tags. These indicate that we intend the enclosed text to be a heading. HTML allows for six levels of headings, from h1 (the most prominent) to h6. You can use any of the intermediate values h2, h3, h4, and h5 to display pages having various levels of subtitles, for instance corresponding to chapter, section, and paragraph headings. Anything displayed within header tags is displayed on a line by itself.

All the tags discussed so far have been containers—that is, they consist of opening and closing tags between which you place the text that you want these tags to act upon. Some elements, however, are not containers but can be used alone. Listing 2.1 shows one such element: the <br /> tag, which signifies a line break. Another example is <hr /> (a horizontal line).

Image

If you want to write in the body section of the HTML page but don’t want it to be interpreted by the browser and therefore displayed on the screen, you may do so by writing it as a comment. HTML comments start with the character string <!-- and end with the string --> as in this example:

     <!-- this is just a comment and won’t be displayed in the browser -->

Adding Attributes to HTML Elements

Occasionally there is a need to specify exactly how a markup tag should behave. In such cases you can add (usually within the opening tag) parameter and value pairs, known as attributes, to change the behavior of the element:

<body bgcolor=”#cccccc”>
… page content goes here …
</body>

In this example, the behavior of the <body> tag has been modified by adjusting its BGCOLOR (background color) property to a light gray. Figure 2.2 shows the effect this has if applied to our file testpage.html:

Figure 2.2 Our test page with the body color changed to gray.

Image

Image

Color values in HTML are coded using a hexadecimal system. Each color value is made up of three component values, corresponding to red, green, and blue. Each of the color values can range from hex 00 to hex ff (zero to 255 in decimal notation). The three hex numbers are concatenated into a string prefixed with a hash character (#). The color value #000000 therefore corresponds to black, and #ffffff to pure white.

Images

Images can be inserted in our page by means of the <img /> tag. In this case we specify the source file of the image as a parameter by using the src attribute. Other aspects of the image display that we can alter this way include the borders, width, and height of the image:

<img src=”myimagefile.jpg” border=”2” width=”250” height=”175” />

Border width, image width, and image height are in numbers of pixels (the “dots” formed by individual picture elements on the screen).

Image

A further useful attribute for images is alt, which is an abbreviation of alternative text. This specifies a short description of the image that will be offered to users whose browsers cannot, or are configured not to, display images. Alternative text can also be important in making your website accessible to those with visual impairment and other disabilities:

 <img src=”myimagefile.jpg” alt=”Description of Image” />

Tables

Often you want to display information in tabular format, and HTML has a set of elements designed specifically for this purpose:

<table>
<tr><th>Column Header 1</th><th>Column Header 2</th></tr>
<tr><td>Data Cell 1</td><td>Data Cell 2</td></tr>
<tr><td>Data Cell 3</td><td>Data Cell 4</td></tr>
</table>

The <table> and </table> tags contain a nested hierarchy of other tags, including <tr> and </tr>, which define individual table rows; <th> and </th>, which indicate cells in the table’s header; and <td> and </td>, which contain individual cells of table data.

Look ahead to Figure 2.3 to see an example of how a table looks when displayed in a browser window.

Hyperlinks

Hypertext links (hyperlinks) are fundamental to the operation of HTML. By clicking on a hyperlink, you can navigate to a new location, be that to another point on the current page or to some point on a different page on another website entirely.

Links are contained within an <a>, or anchor tag, a container tag that encloses the content that will become the link. The destination of the link is passed to this tag as a parameter href:

Here is <a href=”newpage.html”>my hyperlink</a>

Clicking on the words my hyperlink in the preceding example results in the browser requesting the page newpage.html.

Image

A hyperlink can contain images as well as, or instead of, text. Look at this example:
<a href=”newpage.html”><img src=”picfile.gif” /></a>
Here, a user can click on the image picfile.gif to navigate to newpage.html.

A More Advanced HTML Page

Let’s revisit our testpage.html and add some extra elements. Listing 2.2 shows seville.html, developed from our original HTML page but with different content in the <body> section of the document. Figure 2.3 shows how the page looks when displayed, this time in Mozilla Firefox.

Now we have applied a background tint to the body area of the document. The content of the body area has been centered on the page, and that content now includes an image (which we’ve given a two-pixel-wide border), a heading and a subheading, a simple table, and some text.

Listing 2.2 seville.html

<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN” “http://www.w3.org/TR/html4/loose.dtd”>
<html>
<head>
<title>A Simple HTML Document</title>
</head>
<body bgcolor=”#cccccc”>
<center>
<img src=”cathedral.jpg” border=”2” alt=”Cathedral” />
<h1>Guide to Seville</h1>
<h3>A brief guide to the attractions</h3>
<table border=”2”>
<tr>
  <th bgcolor=”#aaaaaa”>Attraction</th>
  <th bgcolor=”#aaaaaa”>Description</th>
</tr>
<tr>
  <td>Cathedral</td>
  <td>Dating back to the 15th century</td>
</tr>
<tr>
  <td>Alcazar</td>
  <td>The medieval Islamic palace</td>
</tr>
</table>
<p>Enjoy your stay in beautiful Seville.</p>
</center>
</body>
</html>

Let’s take a closer look at some of the code.

First, we used the BGCOLOR property of the <body> tag to provide the overall background tint for the page:

<body bgcolor=”#cccccc”>

Everything in the body area is contained between the <center> tag (immediately after the body tag) and its partner </center>, immediately before the closing body tag. This ensures that all of our content is centered on the page.

The main heading is enclosed in <h1> … </h1> tags as previously, but is now followed by a subheading using <h3> … </h3> tags to provide a slightly smaller font size.

By using the border property in our opening <table> tag, we set a border width of two pixels for the table:

<table border=”2”>

Meanwhile we darkened the background of the table’s header cells slightly by using the BGCOLOR property of the <th> elements:

<th bgcolor=”#aaaaaa”>Vegetables</th>

Figure 2.3 testpage2.html shown in Mozilla Firefox.

Image

Some Useful HTML Tags

Table 2.1 lists some of the more popular HTML tags.

Table 2.1 Some Common HTML Markup Elements

Image

Image

Image

The World Wide Web Consortium is responsible for administering the definitions of HTML, HTTP, XML, and many other web technologies. Its website is at http://www.w3.org/.

Adding Your Own Style

As you’ve already learned, HTML was written as a markup language for defining the structure of a document (paragraphs, headings, tables, and so on). Although it was never intended to become a desktop publishing tool, it does include some basic formatting attributes, such as font-size, align and the aforementioned bgcolor . In 1996, the W3C first recommended the idea of Cascading Style Sheets (CSS) to format HTML documents. The recommendation, which was updated in mid-1998, enables web developers to separate the structure and format of their documents.

The CSS recommendation describes the following three types of style sheets:

Image Embedded The style properties are included (within the <style> tags) at the top of the HTML document. A style assigned to a particular tag applies to all those tags in this type of document. In this book, you’ll see embedded style sheets most often.

Image Inline The style properties are included throughout the HTML page. Each HTML tag receives its own style attributes as they occur in the page.

Image Linked The style properties are stored in a separate file. That file can be linked to any HTML document using a <link> tag placed within the <head> tags.

In the following sections, you’ll learn how to construct these style sheets and how to apply them to your documents.

Image

Even without all the formatting benefits that style sheets provide, web developers can rejoice in knowing that using style sheets will no doubt be the biggest timesaver they’ve ever encountered. Because you can apply style sheets to as many HTML documents as you like, making changes takes a matter of minutes rather than days.

Before the advent of style sheets, if you wanted to change the appearance of a particular tag in your website, you would have to open each document, find the tag you wanted to change, make the change, save the document, and continue on to the next document. With style sheets, you can change the tag in a single style sheet document and have the changes take effect immediately in all the pages linked to it.

Defining the Rules

Style sheet rules are made up of selectors (the HTML tags that receive the style) and declarations (the style sheet properties and their values). In the following example, the selector is the body tag and the declaration is made up of the style property (background) and its value (black). This example sets the background color for the entire document to black.

body {background:black}

You can see that, in a style sheet, the HTML tag is not surrounded by brackets as it would be in the HTML document, and the declaration is surrounded by curly braces. Declarations can contain more than one property. The following example also sets the text color for this page to white. Notice that the two properties are separated by a semicolon.

body {background:black; color:white}

If you want to apply the same rules to several HTML tags, you could group those rules together, as in the following example:

body, td, h1 {
             background:black;
             color:white
             }

Add a Little class

As the old saying goes, rules are made to be broken. What if you don’t want every single h1 heading in your document to be white on a black background? Maybe you want every other h1 heading to be yellow on a white background. Let me introduce you to the class attribute. You can apply this attribute to almost every HTML tag, and it’s almost like creating your own tags.

Figure 2.4 shows a fairly standard HTML page that uses an aqua table at the top of the page to hold the navigation links, and places other tabular content in yellow tables throughout the document. You can see the HTML document for that page in Figure 2.5.

Figure 2.4 An HTML page that formats two tables differently.

Image

Figure 2.5 The HTML document for the page in Figure 2.4. Notice the class attribute in each <table> tag.

Image

Take a closer look at the style properties in Figure 2.5. This document defines two table styles within the <style> tags. The HTML tag name table is followed by a period (.) and the class names (nav and rest).

table.nav {background:aqua}
table.rest {background:yellow;
            text-align:center;
            color:black}

When the table is referenced in the body of the document, you must apply the class attribute to tell the browser which style properties should be applied. The HTML markup for each table in this example appears in the following HTML code. You can see that the class name appears within quotations just like the other HTML attributes (and as with the width attribute shown here).

<table class=”nav” width=”100%”>
<table class=”rest” width=50%>

Applying Styles

Before moving on, we’ll quickly cover how to apply style properties to your documents. Remember, you have three methods to add style sheets: embedded, linked, and inline. We’ll discuss each one in turn.

Embedded Styles

All the styles are defined at the top of the HTML document within the <head> tags because they contain information about the entire document. The styles defined here apply only to the one document in which they appear. If you plan to use these same styles in another document, you need to add them there as well.

<head>
<style type=”text/css”>
table.nav {background:aqua}
table.rest {background:yellow;
            text-align:center;
            color:black}
a:link {color:red;
        text-decoration:none}
</style>
</head>

Image

The <style> tag almost always includes the type= “text/css” attribute, so you should get used to adding it.

Linked Styles

Linked style sheets hold all the style properties in a separate file. You then link the file into each HTML document where you want those style properties to appear.

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

With this method, I’ve created a separate file called mystyles.css (for cascading style sheet) that contains all my style properties. You can see that the same type=”text/css” attribute shows up here. Following are the entire contents of the mystyles.css file. These are the same styles that showed up in the preceding embedded styles example, but now they appear in a separate text file.

table.nav {background:aqua}
table.rest {background:yellow;
            text-align:center;
            color:black}
a:link {color:red;
        text-decoration:none}

Inline Styles

With inline styles, the style properties are added to the HTML tag as the tag is entered. This means that if I want the same style to appear on all the <h1> tags in my document, I would have to type those styles in all the <h1> tags. Look at the following example. I am still using the same style properties, as in the previous examples, but now you can see how the two tables would be created using inline styles.

<table style=”background:aqua” width=”100%”>

<table style=”background:yellow; text-align:center;
              color:black” width=”100%”>

Using inline styles, the <style> tag becomes the style attribute. Multiple style properties are still separated by semicolons, but the entire group of properties for each tag is grouped within each HTML tag. This type of style sheet is fine for documents in which you need to apply styles to only one or two elements, but you wouldn’t want to do all that work when you have a lot of styles to add.

Cascading Precedence

Web browsers give precedence to the style that appears closest to the tag. So, inline styles (which appear as attributes within the tag itself) are most important. Embedded styles (which appear at the top of the HTML file) are applied next, and linked styles (which appear in another file altogether) are applied last.

Imagine that you have created an embedded style for the <h1> tag, but want to change that style for one occurrence of the <h1> tag in that document. You would create an inline style for that new <h1> tag. The browsers recognize that fact and change the style for that tag to reflect the inline style.

Image

Style sheet precedence is supposed to place more importance on embedded styles than on linked style sheets. In actual practice, however, you’ll find that both Internet Explorer and Netscape treat linked sheets as more important than embedded sheets (but they do treat inline styles as more important than either of the other two). You’ll find that you have better luck if you use either linked or embedded styles, but not both.

Formatting Text with Styles

Text is the most important element of any Web page. Without text, there is nothing on the page to help people decide whether it’s worth coming back.

Text on an HTML page is structured by the <body>, <p>, <td>, <tr>, <th>, <h1> <h6>, and <li> tags (among others). You can add your own style preferences to each of these tags using the style properties shown in Table 2.2.

In the following example, we’ve added some embedded style elements that set the font, font size, and font color for the body text of a basic HTML page. In Figure 2.6, you can see how those styles change the appearance of the document in the browser.

<!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” lang=”en”>
<head>
<title>My First Web Page</title>
<style type=”text/css”>
body {font-family:”Arial”;
      font-size:”12pt”;
      color:red}
</style>
</head>
<body>
<p>This is my <b><i>first</i></b> Web page.</p>
</body>
</html>

Figure 2.6 The browser applies the style attributes to the text in the <body> tags.

Image

Table 2.2 lists the many style properties that you can use to format your text.

Table 2.2 Style Properties for Text

Image

Microsoft maintains a brief tutorial for style sheets on its typography site (http://www. microsoft.com/typography/default.mspx). The tutorial teaches Web page authors how style sheets can enhance their documents. The <style> tag for one of those examples is shown in the following code. This is impressive because of the many different styles and classes defined in this document. You can see that you are only limited by your own imagination. You can see the page this style code created in Figure 2.7.

<style type=”text/css”>
body {background: coral}
.copy {color: Black;
    font-size: 11px;
    line-height: 14px;
    font-family: Verdana, Arial, Helvetica, sans-serif}
a:link {text-decoration: none;
    font-size: 20px;
    color: black;
    font-family: Impact, Arial Black, Arial,
                 Helvetica, sans-serif}
.star {color: white;
    font-size: 350px;
    font-family: Arial, Arial, helvetica, sans-serif}
.subhead {color: black;
    font-size: 28px;
    margin-top: 12px;
    margin-left: 20px;
    line-height: 32px;
    font-family: Impact, Arial Black, Arial,
                 Helvetica, sans-serif}
.what {color: black;
    font-size: 22px;
    margin-left: 20px;
    font-weight: bold;
    font-style: italic;
    font-family: Times New Roman, times, serif}
.quott {color: black;
    font-size: 120px;
    line-height: 120px;
    margin-top: -24px;
    margin-left: -4px;
    font-family: Arial Black, Arial, helvetica, sans-serif}
.quotb {color: black;
    font-size: 120px;
    line-height: 120px;
    margin-right: -1px;
    margin-top: -33px;
    font-family: Arial Black, Arial, helvetica, sans-serif}
.quote {color: red;
    font-size: 24px;
    line-height: 28px;
    margin-top: -153px;
    font-family: Impact, Arial Black, Arial,
                 Helvetica, sans-serif}
.footer {color: cornsilk;
     background: red;
     font-size: 22px;
     margin-left: 20px;
     margin-top: 16px;
     font-family: Impact, Arial Black, Arial,
                  Helvetica, sans-serif}
.headline {color: black;
     font-size: 80px;
     line-height: 90px;
     margin-left: 20px;
     font-family: Impact, Arial Black, Arial,
                  Helvetica, sans-serif}
.mast {color: cornsilk;
    font-size: 90px;
    font-style: italic;
    font-family: Impact, Arial Black, Arial,
                 Helvetica, sans-serif}
</style>

Figure 2.7 The preceding style code produced this page, found at http://www.microsoft.com/typography/css/gallery/slide3.htm.

Image

image

None of the most popular web browsers react the same way to all the style sheet properties. Your best bet is to remember to test everything before you publish it. Webmaster Stop maintains a table of style sheet properties mapped to the most popular browsers. Check out this table (http://www.webmasterstop.com/118.html) to find out whether the style sheet properties you plan to use are supported by specific browsers.

Link Styles

You have probably seen those bright blue underlined hyperlinks on the Web. Style sheets have the following selectors to help you change the look of them:

Image a:link Sets the styles for unvisited links.

Image a:visited Sets the styles for visited links.

Image a:active Sets the styles for the link while it is linking.

Image a:hover Sets the style for the link while your mouse is hovering.

Table 2.3 shows some of the style properties you can assign to your links.

Table 2.3 Style Properties for the Anchor Styles

Image

Image

One of the most popular style sheet effects on the Web right now is to remove the underlining on hyperlinks. To do this on your pages, just add the text-decoration:none declaration to the a styles, as shown in the following example:

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

If you like the look of the underlined hyperlink, you’re in luck. You don’t have to specify anything at all. Underlining is assumed for all a styles.

Color Styles

As you can see in Table 2.4, you can apply color to your HTML tags in two different ways: with color or with background.

Table 2.4 Style Properties for Color

Image

Image

Don’t forget to test your pages before you publish them. Not all colors work together. If you’ve specified a black background color and a black text color, you have a problem because no one will be able to see your text.

Adding Lines

A horizontal line, or horizontal rule as it is named in HTML, is one of the easiest tags to use. You can insert the <hr /> tag anywhere in your document to insert a horizontal line that extends across the space available. Take a look at the following sample HTML. It shows three <hr> tags: two used as a section break between text and the other used inside a table cell. Figure 2.8 shows how they appear in the browser.

<!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” lang=”en”>
<head>
<title>Horizontal Lines</title>
<style type=”text/css”>
td {text-align=center} </style>
</head>
<body>
<p>This is a horizontal line.</p>
<hr />
<p>This is another horizontal line.</p>
<hr />
<table width=”50%” rules=cols>
  <tr>
   <td>This is also a<hr />horizontal line.</td>
   <td>There is <br />no line on this<br />side
       of the table.</td>
  </tr>
</table>
</body>
</html>

Figure 2.8 The <hr /> tag inserts a horizontal line that stretches across the available horizontal space.

Image

Margin Styles

Style sheets give you another important advantage: You can specify the margins of almost any HTML element. The margins can be defined in pt, in, cm, or px sizes.

body {margin-left: 100px;
     margin-right: 100px;
     margin-top: 50px}

You can set the margin-left, margin-right, and margin-top properties individually or combine them into one property called margin that applies the sizes to the top, right, and left margins.

body {margin: 100px 100px 50px}

Summary

This chapter discussed the basics of web page layout using Hypertext Markup Language, including the structure of HTML documents, examples of HTML page elements, and page styling using both element attributes and cascading style sheets.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.134.88.228