Netregistry - http://www.netregistry.com.au/news
HTML and CSS: An Absolute Beginner's Guide Part 3/3
http://www.netregistry.com.au/news/articles/146/1/HTML-and-CSS-An-Absolute-Beginners-Guide-Part-33/Page1.html
By SitePoint Books
Published on 2/Nov/2006
 
A wise man once said that a journey of a thousand miles begins with a single step. In this chapter, you'll take that first metaphorical step on your journey towards web site enlightenment: you'll create your first web page. By the end of the chapter, you'll have duplicated that first page to form the beginnings of a multi-page web site.

Page 1

HTML and CSS:
An Absolute Beginner's Guide

SitePoint

Ian
LloydBy Ian Lloyd, SitePoint.com

So, you're ready to take the plunge and begin to learn how to build your own web pages and sites? Fantastic! We've got quite a ride ahead, so I hope you're feeling adventurous.

Chapter 3. Adding Some Style

In Chapter 1, Setting Up Shop and Chapter 2, Your First Web Pages, we stepped through the process of setting up your computer so that we could develop web sites, and pulled together the beginnings of a web site with which you could impress your friends and family! The trouble is, when you came to show off your fledgling site to your nearest and dearest, they weren't impressed!

"That's nice dear," said your better half, then carried on doing the dishes. Even Rover (normally your biggest fan), was singularly unimpressed, and decided it would be better to curl up in a warm corner until you stopped waving the laptop in his face. What have you done wrong?

The answer is: nothing. It's true that the web site may look a little bland at present, but the underlying structure on which it's built is rock-solid. To return to our automotive analogy, you now have a perfect chassis and some decent bodywork, and, while your car's not making people turn their heads just yet, it's only a matter of time. Just let them see what you can do with this rolling shell!

In this chapter, we'll begin the process of adding that lick of paint to your otherwise plain site. The tool for the job is Cascading Style Sheets -- CSS to those in the know (or with limited typing abilities). Let's take a look at what CSS can do for you.

What is CSS?

As this chapter revolves almost exclusively around CSS, it's probably a good idea to begin with a basic discussion of what CSS is, and why you should use it. As we've already mentioned, CSS stands for Cascading Style Sheets, but that's too much of a mouthful for most people -- we'll stick with the abbreviation!

CSS is a language that allows you to change elements such as text size, color, bolding, background colors, border styles, and colors -- even the position of elements on the page. Let's take a look at some CSS in action; we'll start by learning about inline styles.

Inline Styles

If you're familiar with Microsoft Word (or a similar word processing package), you may well have created your fair share of flyers, advertisements, or personal newsletters (as well as the more mundane letters to the local authorities and so on). In doing so, you've probably used text formatting options to color certain parts of your text. It's as simple as highlighting the words you want to change, then clicking on a color in a drop-down palette. The same effect can be achieved in XHTML using a little bit of inline CSS. This is what it looks like:

<p style="color: red">The quick brown fox jumped over the lazy  
    dog.</p>

In the example above, we use a style attribute inside the opening <p> tag. Applying a style to a specific XHTML element in this way is known as using an "inline style."

The style attribute can contain one or more declarations between its quotation marks. A declaration is made up of two parts: a property, and a value for that property. In the example above, the declaration is color: red (color being the property and red being its value).

If you wanted to, you could add another declaration to the example above. For instance, as well as having the text display in red, you might want it to appear in a bold typeface. The property that controls this effect is font-weight; it can have a range of different values, but mostly you'll use normal or bold. As you might expect, you'd use the following markup to make the paragraph red and bold:

<p style="color: red; font-weight: bold">The quick brown fox  
    jumped over the lazy dog.</p>

Notice that a semicolon separates the two declarations. You could carry on adding styles in this way, but beware: this approach can get messy! There are cleverer ways to apply styling, as we'll see very soon.

Adding Inline Styles

Open about.html in your text editor, and add an inline style. We want to make the text in the first paragraph after the 'About Us' heading bold and blue. Refer to the previous example as you create the style.

Does the markup for your paragraph look like this?

<p style="color: blue; font-weight: bold;">Bubble Under is a group  
    of diving enthusiasts based in the south-west UK who meet up  
    for diving trips in the summer months when the weather is good  
    and the bacon rolls are flowing. We arrange weekends away as  
    small groups to cut the costs of accommodation and travel and  
    to ensure that everyone gets a trustworthy dive buddy.</p>

If the markup does look like that shown here, save about.html and take a look at it in your browser. It should appear like the page shown in Figure 3.1.

1533_bluepara
Figure 3.1. Content displaying with blue and bold styles


Page 2

The span Element

You can easily color a whole paragraph like this, but more often than not, you'll want to pick out just a couple of specific words to highlight within a paragraph. You can do this using a span element, which can be wrapped around any content you like. Unlike p, which means paragraph, or blockquote, which signifies a quotation, span has no "meaning." A span is little more than a tool for highlighting the start and end of something to which you want to apply a style. (Applying a span also gives you the ability to do some other clever things to your web page with scripting, but for our purposes, its scope is limited to the things it allows you to do with CSS.) Instead of making that whole paragraph blue, we might want just the first two words, "Bubble Under," to be blue and bold. Here's how we can use the span element to achieve this:

<p><span style="color: blue; font-weight: bold;">Bubble  
    Under</span> is a group of diving enthusiasts based in the  
    south-west UK who meet up for diving trips in the summer  
    months when the weather is good and the bacon rolls are  
    flowing. We arrange weekends away as small groups to cut the  
    costs of accommodation and travel and to ensure that everyone  
    gets a trustworthy dive buddy.</p>

When we view that markup in a browser, we see the display shown in Figure 3.2.

1533_bluebubbleunder
Figure 3.2. Using the span element to pick out specific words for styling

Let's take a quick look at other ways that we can apply inline styles (don't worry, this isn't part of our project site; feel free to experiment).

<p style="font-style: italic">The quick brown fox jumped over the  
    lazy dog.</p>

Not surprisingly, that CSS declaration will italicize all the text in the paragraph. Here's another example, in which span is used to highlight specific words:

<p>The quick brown fox <span style="font-style: italic;  
    font-weight: bold">jumped</span> over the lazy dog.</p>

Embedded Styles

Inline styles are a simple, quick way to apply some 'makeup' to specific sections of a document, but this is not the best method of styling a page. Wouldn't it be better if you could set styles in just one place, rather than having to type them out every time you wanted to use them?

Embedded style sheets are a logical step up. An embedded style allows you to add to the start of a web page a section that sets out all the styles that will be used on that page. To do this, you need to use the style element inside the head:

<head>
  <title>Bubble Under - The diving club for the south-west  
      UK</title>
  <meta http-equiv="Content-Type"  
      content="text/html; charset=utf-8" />
  <style type="text/css">
    p {
      font-weight: bold;
    }
  </style>
 
</head>


Page 3

In the markup shown above, we've moved the inline style into an embedded style sheet. The embedded style sheet starts with a <style type="text/css"> tag and, predictably, ends with a </style> tag. The actual style declarations are enclosed in a set of curly braces: { and }. The p that appears before the first curly brace tells the browser what the style rules are for; in this case, we're making the text inside every p element bold. The p is called the selector, and it's a great tool for quickly and easily changing the appearance of lots of elements on your page. The selector, curly braces, and declarations combine to make up what's called a rule.

In this case, our style sheet contains one rule: "Please style all the paragraphs on this page so that the text appears in a bold font."

If we wanted to, we could add more declarations to our rule. For instance, if we wanted to make the text bold and blue, we'd add the declaration color: blue to our rule:

<style type="text/css">
  p {
    font-weight: bold;
    color: blue;
  }
</style>

Jargon Break

Okay, okay. There's been an awful lot of jargon so far. Let's recap: Figure 3.3, 'The anatomy of a rule' brings the theory into focus.

1533_rulesexplained
Figure 3.3. The anatomy of a rule

Why Embedded Styles are Better than Inline Styles

In the example provided in Figure 3.3, text in all paragraphs will display in bold, blue type. This is useful because it saves you having to type <p style="font-weight: bold; color: blue"> every time you start a new paragraph -- a clear benefit over inline styles. If you wanted to change the color of all paragraph text to red, you need only to change it in the style sheet at the top of the page. That's efficiency for you!

<style type="text/css">
  p {
    font-weight: bold;
    color: red;
  }
</style>

For this reason, an embedded style sheet is a marked improvement over inline styles. But what if you have a web site that comprises many pages? If you want to make your changes across the whole site, using embedded style sheets in the way I demonstrated above is still not quite the perfect solution. Why not? Because, to make a site-wide change, you'd have to edit the embedded style sheet on every single page of that site. The best solution is to use an external style sheet.

External Style Sheets

Why External Style Sheets are Better than Embedded Styles

An external style sheet provides a location in which you can place styles that can be applied on all of your web pages. This is where the true power of CSS lies, and it's for this reason that we haven't spent too much time applying inline styles or embedded styles to our diving club project site.

The Bad Old Days

In the past, or The Bad Old Days, as we'll call them, people would create web sites on a page-by-page basis, and style them on a page-by-page basis using all manner of nasty elements of which I dare not even speak! Sometimes, these sites grew beyond the webmaster's wildest imagination. "Fantastic," thought Mr or Mrs Webmaster. "My web site now has over 200 pages! Soon I'll be bigger than Microsoft." A few months later, the webmaster decided to redesign the web site and realized, with considerable horror, that he or she would have to alter each and every single web page in order to redesign the site in a consistent manner. Every page needed 20 or more different tweaks, and each tweak had to be applied consistently to every page of the site. Inevitably, some pages were missed, and eventually the redesign plan got unceremoniously dropped. In short, the ugly web site remained ugly for a whole lot longer before dying a nasty death through sheer negligence (indeed, there are many such 'legacy' documents littered around the Web today). This need not be the case, though.

CSS gives you the power to set styling rules in one place. When you want to make changes to your web site, you make changes in that one place, and your whole web site changes automatically to reflect those new styles.

Happy Days! CSS Support is Here!

The good news is that the large majority of web browsers in use today offer excellent support for CSS (though this has not always been the case, which is why some people have been slow to adopt CSS-based design). Some browsers can choke on a few of the more advanced CSS techniques, but, by and large, you can style your web pages with CSS and be confident that what you see on your screen is the same view that 99.5% of your intended audience will see.


Page 4

Creating an External CSS File

If you are to make use of all the benefits that an external style sheet can provide, you'll first need to create a CSS file that can be shared among all the pages of your web site. Open your text editor and enter the following:

Example 3.1. style1.css
 
/*
CSS for Bubble Under site
*/
 
p {
  font-weight: bold;
  color: blue;
}

Save the file in the same folder as your HTML files, naming it style1.css; you can save a CSS file in the same way you saved your HTML files.

Note that the first few lines we typed into our CSS file will not actually do anything. Like HTML, CSS allows you to add comments. It's a shame that the tags for HTML comments are different from those for CSS comments, but they do exactly the same thing: they allow you to make notes about your work without affecting the on-screen display. In CSS, a comment starts with a /* and ends with a */; the browser ignores anything in between. Above, we used the comment simply to make a note about the purpose of the file, namely that it is the CSS for the Bubble Under site. We've also added a rule to turn the type in all our paragraphs bold and blue.

Linking CSS to a Web Page

Before your CSS can have any effect, you need to link it to the web page, or pages, to which you want the styles to apply. To do this, you need to add a link element to the head of each and every web page that will be styled with CSS. Our site contains just three pages at the moment, so this will be nice and easy. The link element simply "links" a file to the page on which the element appears; in this case, the linked file is a style sheet.

Below, the new line appears in the context of the homepage:

Example 3.2. index.html (excerpt)
 
<head>
  <title>Bubble Under - The diving club for the south-west  
      UK</title>
 
  <meta http-equiv="Content-Type"  
      content="text/html; charset=utf-8" />
  <link href="style1.css" rel="stylesheet" type="text/css" />
</head>

Let's take a look at what the markup means.

The href attribute tells the web browser where the style sheet file (style1.css) can be found, in the same way that the href attribute is used in an anchor to point to the destination file (e.g. <a href="home.htm">Home</a>).

The rel="stylesheet" and type="text/css" parts of the link tag tell the browser what kind of file is being linked to, and how the browser should handle the content. You should always include these important attributes when linking to a .css file.

Note: Empty Element Alert!

The link element is another of those special empty elements we discussed in Chapter 2, Your First Web Pages: it has no start or end tags. link is a complete element in its own right, and ends with the space and forward slash required by XHTML.

Now that we know how to link our pages to our CSS file, let's try it out on our project site:

       
  • Open each of your web pages -- index.html, about.html, and contact.html -- in your text editor. Add the following line just before the closing </head> tag in each of those files. <link href="style1.css" rel="stylesheet" type="text/css" />
  •    
  • Be sure to save each page. Then, try opening each one in your web browser.

All of your paragraphs should now display in bold, blue text. If so, congratulations -- you've now linked one style sheet to three separate pages. If you change the color specified in your .css file from blue to red, you should see that change reflected across your pages the next time you open them.

Now, using blue, bold text might be a good way to make sure your style sheets are correctly linked, but it's not necessarily the design effect we want to use. Remove the p rule from your style sheet, but leave the comment, and let's start building our style sheet for real.


Page 5
Starting to Build our Style Sheet

The style sheet is ready to be used: it's saved in the right location, and all of your web pages (all three -- count 'em!) are linked to it correctly. All we need to do, then, is set some styles!

One of the first changes that people often make to a web site's default styling is to alter the font (or typeface) that's used. On Windows, most browsers will opt for Times New Roman -- the font that has been used in all the screen shots we've seen so far. For many people, though, it's a little bit dull, probably because this font is used more than any other. It's very easy to change fonts using CSS's font-family property. The best place to use this is within the body element, as shown below.

Example 3.3. style1.css
 
/*
CSS for Bubble Under site
*/
 
body {
  font-family: Verdana;
}

Here, I've chosen to use the Verdana font. It's applied to the body element because body contains every element that you will see on the web page. The nature of the way in which CSS is applied means that every element contained in the body element will take on the same font (unless another font is specified for a given element or elements within body -- but more on that a little later).

Great: Verdana it is! But ... what if some people who view your site don't have Verdana installed on their computers? Hmm, that's a tricky one. The short answer is that the browser will make its best guess about which font it should use instead, but we don't have to make the browser do all the guesswork. The font-family property allows us to enter multiple fonts in the order in which we'd prefer them to be used. So, we could type something like this:

body {
  font-family: Verdana, Helvetica, Arial, sans-serif;
}

This translates as: "Please style everything in the body of my web page so that the text appears as Verdana. Failing that, please try using Helvetica and, failing that, Arial. If none of the above are installed, just use whatever sans-serif font is available."

We'll use this selection of fonts in our diving site, so let's open the style sheet file and play around with some CSS.

       
  • Type the above CSS into style1.css.
  •    
  • Save the file, then open the homepage (index.html) in your browser.

If everything went to plan, your web page (all three of them, actually) should display slightly differently than they did before. Figure 3.4 shows the appearance of our newly-styled homepage.

Note: Sans-serif Fonts: Better for On-screen Viewing

A serif font is one that has all those fancy extensions and flourishes at the ends of each letter. These "flourishes," which are shown in Figure 3.5, are known as serifs. They're great for reading printed material, as they give a little shape to the words, making them easier to read.

However, on the screen, serif fonts can become a little messy, especially when they're used for smaller type -- there simply aren't enough pixels on the screen to do these little flourishes justice. For this reason, you'll notice that many web sites use sans-serif fonts (French words that literally mean "without serif") when the font size is set quite small.

Note that when you refer to a sans-serif font in CSS, you must hyphenate the two words, i.e. sans-serif.

1533_sansserif
Figure 3.4. A font change in the style sheet affects the body of our web pages

1533_serif
Figure 3.5. Highlighting the serifs of a serif font (Georgia)


Page 6

Stylish Headings

The first element that we'll style is our level 1 headings, denoted by the h1 element. Let's add some rules to our CSS file to see what's possible when it comes to those headings. In your text editor, add the following to style1.css:

h1 {
  font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
}

Save the CSS file and refresh your view of the homepage in your browser. Can you see what's changed? All the first-level headings now display in the Trebuchet MS font, while everything else displays in Verdana.

The font we've chosen is another sans-serif font, but it's different enough to provide plenty of contrast with the paragraphs, as Figure 3.6 illustrates.

1533_headingfontchange
Figure 3.6. h1 headings displaying in one font (Trebuchet MS) while other text displays in another (Verdana)

Some Font Names Deserve Quotes

In the example above, "Trebuchet MS" appeared in quotation marks. You don't need to bother wrapping quote marks around font names, unless the font comprises several words, such as 'Courier New' or 'Times New Roman.' A single-word font name, such as Arial or Verdana, does not need to be wrapped in double quotes.

Have a quick look around all three pages of the web site and you'll see that your new styles have been applied to all your web pages. Let's go a step (or two) further.

Note: What's Going On? Nothing's Changed!

If you try refreshing your browser's view of a page and nothing appears to change, first check that you saved the changes you made to the CSS file. If you have saved the altered file, check that you typed the CSS exactly as described. If you did, you may be experiencing a caching problem with your browser.

Web browsers "cache" some content. What this means is that, to save having to download files each and every time you visit a given web page, your browser uses versions of the files that it saved to the hard drive previously. This reduces the time it takes to display a web page that has been loaded once before. Unfortunately, your cache can get out of date, and when that happens, the page you visit (i.e. you enter the URL, and the browser pulls the page stored in its cache) might not display the most recent data.

This happens most frequently with images, but it can also occur with CSS files. The good news is that you have control over your browser's cache settings and the amount of space the cache takes up on your hard disk before previously cached content gets replaced with newer data. You can poke around your browser's settings for words like "Cache" or "Temporary Internet Files" to change these settings; however, most users opt to leave their caches to the default settings.

If you're positive that you've made the necessary changes to your CSS file (and saved them) correctly, you may need to "force-reload" the CSS file in your browser.

To stop the caching problem and force the browser to get the most up-to-date version of your CSS file, simply hold down the Shift key and click on the Refresh (or reload) icon on your browser's toolbar.


Page 7

A Mixture of New Styles

Let's change the look of the site a little more: we'll add more styles to the body, and change the look of the navigation. Copy the CSS below into your style1.css file (or copy it from the book's code archive):

Example 3.4. style1.css
 
/*
CSS for Bubble Under site
*/
 
body {
  font-family: Verdana, Helvetica, Arial, sans-serif;
  background-color: #e2edff;
  line-height: 125%;
  padding: 15px;
}
 
h1 {
  font-family: "Trebuchet MS", Helvetica, Arial, sans-serif;
  font-size: x-large;
 
}
 
li {
  font-size: small;
}
 
h2 {
  color: blue;
  font-size: medium;
  font-weight: normal;
}
 
li {
  font-size: small;
}
 
p {
  font-size: small;
  color: navy;
}

Save the CSS file, then click Reload in your browser. Hopefully, you'll be looking at a page like the one shown in Figure 3.7.

1533_bluebkgnd
Figure 3.7. Applying subtle changes to the CSS that affects font display

A New Look in a Flash!

We've introduced quite a few new style declarations here. Let's examine a few of them in the order in which they appear in the CSS file.

Example 3.5. style1.css (excerpt)
 
body {
  font-family: Verdana, Helvetica, Arial, sans-serif;
  background-color: #e2edff;
  padding: 15px;
  line-height: 125%;
}

The background-color property can be applied to most elements on a web page, and there are many different ways in which you can specify the color itself. One is to use recognized color names such as navy, blue, red, yellow, and so on. These are easy to remember and spell, but you are limited somewhat by the range. Another way of referencing colors is to use a hexadecimal color specification. Yes, you're right: that does sound a little scary. I mean, just look at it:

background-color: #e2edff;

It's hardly intuitive, is it? This obscure-looking reference translates to a light shade of blue. You could not, as a beginner, begin to guess that this would be a light blue, but thankfully there are numerous tools on the Web that let you choose a color from a chart, then give you the code to match. Take a look at some of these tools (a good selection of links to color scheme tools is available at http://www.clagnut.com/blog/260/). and you'll soon be able to find the hexadecimal numbers you need to create your ideal color schemes.


Page 8

Note: What the Heck's Hex?

Colors in HTML are often written as a hexadecimal color specification. You might remember the hexadecimal counting system from your high school math class. Or maybe you were asleep up the back of the room. Never mind. Hexadecimal is that weird counting system that goes up to 16 instead of 10; the one you thought you'd never have any practical use for. Well, you do now!

That's right: when you count in hexadecimal, there are not ten, but 16 digits. The hexadecimal sequence looks like this:

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F, 10, 11, 12, 13...

Eh? What's happening here? Well, as you can see, after we get to 9, instead of going straight to 10 (as we do when counting in decimal) we go through A, B, C, D, E, and F before we finally hit 10. That gives us six extra digits to use when we count! Sound confusing? Well, it is. But as it so happens, computers can count in hexadecimal far better than humans can.

The key here is that all of those numbers that we know and love in the decimal system, like 2,748, 15,000,000 and -- er  -- 69, can be represented in hexadecimal. Look, Table 3.1 proves it!

Decimal Hexadecimal
7 7
15 F
2,748 ABC
15,000,000 E4E1C0
69 45

When a color is expressed as a hexadecimal number, such as ff0000, that number actually comprises three values that are joined together. The values represent the proportions of red (the ff part), green (the first two zeros), and blue (the second two zeros) that are mixed to create the specified color. Those three primary colors can be combined to display any color on the screen, similar to the way a television set uses different intensities of red, green, and blue to create a single dot on its screen. In this example, ff is the value for red, while the green and blue values are zero. It may not surprise you, then, to learn that #ff0000 will give you the color red.

The padding property is used to provide space between the outside edge of the element in question and the content that sits inside it. Because we're referring to the body element, you can think of the outside edge as being the top, bottom, and sides of the browser's viewport (that being the part of the browser where the web page is viewable, not including any of the browser's tool bars, menus, or scroll bars). We'll take a look at padding in more detail in Chapter 4, Shaping Up with CSS.

The value we've given to this property specifies how much space must exist between the edge of the viewport and the content. In this case, we've specified 15px, or 15 pixels. We mentioned pixels before, when we specified the size of an image, but what is a pixel? Basically, one pixel is one of the tiny dots that make up what you see on the computer screen. The screen itself is made up of hundreds of thousands of these pixels, so a 15-pixel border isn't going to take up too much space on your screen!

The line-height property is an interesting one. By increasing that value (we used 125% in our example), you can increase the space between lines of text -- something that can greatly increase legibility. Try tweaking this value, save your CSS file, and see how the new value affects the text on your web page.

Now, to the paragraph styles:

Example 3.6. style1.css (excerpt)
 
p {
  font-family: Times, "Times New Roman", serif;
  color: navy;
}

We've already shown that it's possible to change the color of text in a paragraph; now, we're going to settle on the sensible (and appropriate!) color of navy.

Let's see what's changed with the list item style:

Example 3.7. style1.css (excerpt)
 
li {
  font-size: small;
}

The size of the list items has changed ever so slightly through our application of the font-size property. Here, we've decided to set the font size using the small keyword, but we could just as easily have used the percentage or pixel methods we've already seen -- there are many ways to skin a cat with CSS! Font size keywords range from xx-small to xx-large and offer a quick way to style text. Unfortunately, different browsers implement font size keywords slightly differently, and unfortunately you can't be guaranteed that an xx-large font will render at the same size in all browsers. However, unless you're extremely worried about precise sizing, these keywords make a good starting point. (For more reasons than we have space to discuss, text sizing in CSS is a topic that causes heated debate in some circles. As you become familiar with CSS, you may want to learn more about the other text-sizing techniques that it offers. A good place to start would be SitePoint's CSS discussion forum at http://www.sitepoint.com/launch/cssforum/.)


Page 9

Next, we introduced a new rule, this time for the h1 element (the main heading on our web pages, which displays the site name) and, once again, used a font-size property to specify the size of the text (extra large is the answer!).

Example 3.8. style1.css (excerpt)
 
h1 {
  font-size: x-large;
}

The h2 element also gets a minor makeover:

Example 3.9. style1.css (excerpt)
 
h2 {
  color: blue;
  font-size: medium;
  font-weight: normal;
}

Browsers usually display headings in bold type, but we can have them display in standard type by giving the font-weight property a value of normal.

A Beginner's Palette of Styling Options

We've looked at some examples of styles that can be applied to your web pages through CSS, but the examples we've seen have been a mixed bag (deliberately so). There are so many more from which you can pick and choose -- too many possibilities, in fact, for us to be able to list them all here. However, this section lists some of the basic properties and values with which you might like to experiment. Feel free to try any of these in your CSS file. Note that we'll be adding to this list in subsequent chapters; it's by no means exhaustive!

       
  • color, background-color -- As we've seen, both of these properties can take color keywords (e.g. red, blue, green, or yellow) or hexadecimal color specifications such as #ff0000.
  •    
  • font-family -- This property takes a list of fonts, containing any fonts you choose in order of preference. Be sure to provide options that users are likely to have on their computers (e.g. Arial, Verdana, etc.). This list should end with one of the "generic" CSS fonts such as serif or sans-serif, which any browser that supports CSS will recognize.
  •    
  • font-size -- This property can be any one of the following:
         
    • font size keywords
      •    
      • xx-small
      •    
      • x-small
      •    
      • small
      •    
      • medium
      •    
      • large
      •    
      • x-large
      •    
      • xx-large

         

    • a relative unit
      •    
      • such as a percentage (e.g. 140%)

         

    • fixed font sizes
      •    
      • pixels (e.g. 20px)
      •    
      • points (e.g. 12pt, as you may be used to using in Microsoft Word)
      • Fixed font sizes are not always a great idea, as they cannot easily be scaled up or down to suit the reader's needs. Relative font sizes are definitely the preferred option.

         

    • font-weight

      •    
      • bold or normal

         

    • font-style

      •    
      • normal or italic

         

    • text-decoration

      •    
      • none, underline, overline, or line-through

Page 10

Note: Backing it Up!

Before you experiment with the CSS properties above, it might be an idea to make a backup of your CSS file, just in case you run into difficulties. Remember that you can download all the examples used in this chapter from the code archive if you accidentally mangle your CSS file. If this happens, don't worry! It's all part of the learning process, and you can be sure that no animals will be harmed in the process. Only a handful of poor CSS selectors will be mistreated. Shed no tears!

Recap: the Style Story so Far

Let's allow ourselves a moment to reflect. Our site now boasts a CSS file with a selection of attractive styles. We're in the enviable position of being able to change the site at a whim by altering just that one CSS file. Let's try styling some more of the elements on our web pages.

Changing the Emphasis

Open about.html in your text editor.

Find the paragraph about meeting up in a local pub and add an emphasis element as shown here:

Example 3.10. about.html (excerpt)
 
<p>And when we're not diving, we often meet up in a local pub  
    to talk about our recent adventures (<em>any</em> excuse,  
    eh?).</p>

Save the page, then view it in your web browser; it should appear as shown in Figure 3.8. As you can see, emphasis elements appear in italics by default. We're going to use CSS to change that default style.

1533_emphasisitalics
Figure 3.8. Using emphasis to set type to italics by default

Open style1.css (if you haven't already opened it for editing) and add the following rule below the others:

Example 3.11. style1.css (excerpt)
 
em {
  font-style: normal;
  text-transform: uppercase;
}

Save the CSS file, then refresh your browser's view of the About Us page. Does your page look like Figure 3.9?

1533_emphasiscaps
Figure 3.9. The emphasis appearing as capitalized text instead of italics

Now, whenever you add an em element to any web page of your site (assuming that page is linked to style1.css), the emphasized text will appear in capital letters, not italics. But this raises an interesting point: when should you override a browser's default style for one of your own choosing? Presumably, the default styles that browsers use were selected carefully; how can you be sure that your redefinition of the styles is a good idea? Weren't italics a suitable style for emphasis? They probably were. As Spiderman's creators say, 'With great power comes great responsibility,' so be sure to exercise caution. Just because you can change a default style does not always mean you should.

Perhaps a compromise is in order. Let's change the emphasis so that it's still italic, but also appears in uppercase letters. All we need to do is remove the font-style declaration; the em element will then revert to its default italicized appearance, as depicted in Figure 3.10.

Example 3.12. style1.css (excerpt)
 
em {
  text-transform: uppercase;
}


Page 11

1533_tagline
Figure 3.11. The tag line appearing in italics

What's happening here? Perhaps a CSS-to-English translation is required. This CSS rule means, "For any paragraph element that occurs inside an element that has an id of tagline, set the text to italics and the font to Georgia, Times, or some other serif font if you don't have either of those."

Note: Getting a Positive ID

The # notation in the CSS refers to an element with a specific id attribute -- in this case, tagline. We'll learn more about selecting ids and manipulating them in subsequent chapters.

Contextual Selectors

#tagline p is known as a contextual selector. Here are some other examples (with their English translations):

#navigation a {
  text-decoration: none;
}

Translation: for any link found inside the navigation area (an element with an id of navigation), remove any decoration on that text; in other words, remove the underline (any other links on the page will remain underlined).

#footer p {
  line-height: 150%;
}

Translation: set the vertical height between lines of text contained in paragraphs inside the footer area (e.g. a div element with an id of footer) to 150%. This would override the browser default of 100%, or other line-height values that might be set, for example, on the body.

h1 strong {
  color: red;
}

Translation: for any text inside a level one heading that's marked up as strong, set the color to red (any other instance of strong on the page will not be set to red).

h2 a {
  text-decoration: none;
}

Translation: don't underline the text of any link inside a level two heading (the default setting underlines all links, so any other links on the page will remain underlined).

Grouping Styles

If you want to apply the same style to different elements on a web page, you don't have to repeat yourself. For example, let's say that you want to set heading levels one through three in yellow text with a black background. Perhaps you'd do this:

h1 {
  color: yellow;
  background-color: black;
}
 
h2 {
  color: yellow;
  background-color: black;
}
 
h3 {
  color: yellow;
  background-color: black;
}

That's very messy, and once you have a lot of styles on the page, it gets even more difficult to maintain. Wouldn't it be great if you could reduce some of that work? You can! Here's how:

h1, h2, h3 {
  color: yellow;
  background-color: black;
}

Translation: if the element is a level one heading, a level two heading, or a level three heading, set the text to yellow and the background to black.

Note: Comma = "Or"

Think of the commas in the selector above as the word "or."

Let's try grouping some styles in our project site. We don't have any h3 headings yet, but they're coming:

Edit your CSS file (style1.css) by adding the following to the bottom of it:

Example 3.16. style1.css (excerpt)
 
h1, h2, h3 {
  font-family: "Trebuchet MS", Helvetica, Arial, sans-serif;
  background-color: navy;
  color: white;
}

Save the file, then refresh the 'About Us' page in your browser (assuming it's still open from your last exercise). You should be looking at a page like the one shown in Figure 3.12.

1533_blueheadings
Figure 3.12. Displaying the changed heading styles

That CSS really does kill several birds with one stone (and I said no animals would be harmed! Apologies to ornithologists). Now, not only do you have the convenience of being able to style many pages from one central location (your CSS file), but you have the added convenience of being able to style many elements in one go. Your CSS file becomes easier to manage and -- a nice little side-benefit -- smaller, and therefore quicker to download.

But something interesting is happening in our CSS file: it appears that we may have a conflict in our rules. Or have we?


Page 11

1533_tagline
Figure 3.11. The tag line appearing in italics

What's happening here? Perhaps a CSS-to-English translation is required. This CSS rule means, "For any paragraph element that occurs inside an element that has an id of tagline, set the text to italics and the font to Georgia, Times, or some other serif font if you don't have either of those."

Note: Getting a Positive ID

The # notation in the CSS refers to an element with a specific id attribute -- in this case, tagline. We'll learn more about selecting ids and manipulating them in subsequent chapters.

Contextual Selectors

#tagline p is known as a contextual selector. Here are some other examples (with their English translations):

#navigation a {
  text-decoration: none;
}

Translation: for any link found inside the navigation area (an element with an id of navigation), remove any decoration on that text; in other words, remove the underline (any other links on the page will remain underlined).

#footer p {
  line-height: 150%;
}

Translation: set the vertical height between lines of text contained in paragraphs inside the footer area (e.g. a div element with an id of footer) to 150%. This would override the browser default of 100%, or other line-height values that might be set, for example, on the body.

h1 strong {
  color: red;
}

Translation: for any text inside a level one heading that's marked up as strong, set the color to red (any other instance of strong on the page will not be set to red).

h2 a {
  text-decoration: none;
}

Translation: don't underline the text of any link inside a level two heading (the default setting underlines all links, so any other links on the page will remain underlined).

Grouping Styles

If you want to apply the same style to different elements on a web page, you don't have to repeat yourself. For example, let's say that you want to set heading levels one through three in yellow text with a black background. Perhaps you'd do this:

h1 {
  color: yellow;
  background-color: black;
}
 
h2 {
  color: yellow;
  background-color: black;
}
 
h3 {
  color: yellow;
  background-color: black;
}

That's very messy, and once you have a lot of styles on the page, it gets even more difficult to maintain. Wouldn't it be great if you could reduce some of that work? You can! Here's how:

h1, h2, h3 {
  color: yellow;
  background-color: black;
}

Translation: if the element is a level one heading, a level two heading, or a level three heading, set the text to yellow and the background to black.

Note: Comma = "Or"

Think of the commas in the selector above as the word "or."

Let's try grouping some styles in our project site. We don't have any h3 headings yet, but they're coming:

Edit your CSS file (style1.css) by adding the following to the bottom of it:

Example 3.16. style1.css (excerpt)
 
h1, h2, h3 {
  font-family: "Trebuchet MS", Helvetica, Arial, sans-serif;
  background-color: navy;
  color: white;
}

Save the file, then refresh the 'About Us' page in your browser (assuming it's still open from your last exercise). You should be looking at a page like the one shown in Figure 3.12.

1533_blueheadings
Figure 3.12. Displaying the changed heading styles

That CSS really does kill several birds with one stone (and I said no animals would be harmed! Apologies to ornithologists). Now, not only do you have the convenience of being able to style many pages from one central location (your CSS file), but you have the added convenience of being able to style many elements in one go. Your CSS file becomes easier to manage and -- a nice little side-benefit -- smaller, and therefore quicker to download.

But something interesting is happening in our CSS file: it appears that we may have a conflict in our rules. Or have we?


Page 12

1533_emphasisitalicscaps
Figure 3.10. Emphasis displaying as uppercase italics

Note: Emphasis vs Italics

You might well be asking yourself, "If I want an italic font, can't I use an italic element?" In fact, HTML provides an i element for just this purpose, but its use isn't recommended. Why not? Well, marking something up as i says nothing about its meaning; i only communicates how it should be presented on the screen. Such elements are referred to as presentational HTML elements, and they should be avoided. Likewise, the b element (for bold), another old HTML element, should not be used. The preferred option is to use strong or, if you just want to display headings in bold, to use CSS.

Why is this important? It mightn't seem important to you, as you look at the italicized text in your web browser. But imagine you were a blind user of software that read web pages aloud to you, instead of displaying them on the screen. Such a program (called a screen reader) would read text marked up with an em element with slight emphasis, and text marked up with strong in a slow, powerful voice -- but what would it do with text marked up with i or b? Well, these elements say nothing about the meaning of the text, so it would ignore them. The same is true of many programs that analyze web pages, such as web indexing programs run by Yahoo! and Google -- em and strong tags tell these programs that the words inside them are important, whereas i and b tell them nothing.

One other presentational tag that you might see others use, but should never copy, is the u element. Wrap this around some text and you get needless underlining that only serves to confuse users (because in web pages, underlined text normally signifies a link -- something that the u element most definitely does not).

Looking at Elements in Context

Pop quiz: which of these items is bigger? A pen or a sheep? Well, the answer is either, depending on the context. If you were a farmer, you'd swear that the pen is bigger. After all, you spend many hours a week rounding up herds of sheep into a nice big pen. If, however, you're an office worker, you'd opt for the sheep being the larger of the two -- you'd find it a lot easier to pick up a pen and flip it around your fingers.

Context can change things quite drastically, and context is something that can be used to our advantage in CSS. We can style an element in a number of different ways, depending on its position. Let's head back to our example site for another lesson. Don't be sheepish, now!

Currently, we have styled paragraphs so that they appear in a navy blue, sans-serif font (Verdana, specifically), as does almost everything else on the page:

Example 3.13. style1.css (excerpt)
 
body {
  font-family: Verdana, Helvetica, Arial, sans-serif;
}
 
p {
   font-size: small;
   color: navy;
}

This is all well and good, but there's one paragraph on our site that's a little different than the others in terms of its purpose. Can you spot which one it is? It's our first paragraph, the one in the tag line. Here's the XHTML for that section:

Example 3.14. index.html (excerpt)
 
<div id="tagline">
  <p>Diving club for the south-west UK - let's make a splash!</p>
 
</div>

It's different because it's not really part of the document content and, as such, it might benefit from some different styling. The fact that this particular paragraph is contained within a specific div element -- which has an id attribute of tagline -- is something that we can put to great use. Because it's contained within its own div, we can set a rule for this paragraph and this paragraph only.

Open the CSS file for editing, and add the following after the first paragraph rule:

Example 3.15. style1.css (excerpt)
 
#tagline p {
  font-style: italic;
  font-family: Georgia, Times, serif;
}

Save the file, then refresh the About Us page (or any of the three, for that matter) in your browser. Your page should now look something like the one shown in Figure 3.11.


Page 13

Which Rule Wins?

When we added the grouped declaration for the headings, we changed some styles that we'd set previously. A look at the source shows that the level two heading, h2, has been set to be blue and white in different places in our style sheet:

Example 3.17. style1.css (excerpt)
 
h2 {
  color: blue;
  font-size: medium;
  font-weight: normal;
}
 
em {
  text-transform: uppercase;
}
 
h1, h2, h3 {
  font-family: "Trebuchet MS", Helvetica, Arial, sans-serif;
  background-color: navy;
  color: white;
}

Because the declaration specifying that the h2 should be white comes later, it has overridden the earlier one. It doesn't matter if you've defined an h2 to be blue 100 times through your style sheet; if the last definition says it should be white, then white it will be!

Note: Filenames for your Style Sheets

Although we've been working with style1.css for some time, you may be wondering why we named the file this way. The name is deliberate. You might want to add another style to your web site at a later date, and numbering is a basic way to keep track of the styles you can apply to a site.

You might be thinking, "Why not name it something like marine.css because it uses marine colors, references to under-sea animals, and so on?" That's a fair question, but the important thing to note about CSS is that you can always change the styles later, and your naming convention might, at a later date, bear no relevance to the styles a file contains. For example, you can edit marine.css such that all the colors in your web site are changed to ochres, browns, and sandy yellows. This ability to change the web site's design in one action is the whole point of CSS! With the new design, your web site might have an earthy/desert feel to it, yet you could still have 200 or more pages referring to a style sheet by the filename of marine.css. Something's not right there, is it? This is why I've chosen an abstract name for the CSS file, and I recommend that you do the same for the web sites you develop.

Recapping our Progress

Time for another breather. What have we learnt? Well, we've learned some more styles that you can apply in CSS, we've seen how you can style certain elements depending on their context, and more recently, we've discussed how you can group elements that need to be styled in the same way. There's one thing that we've touched on only briefly, yet it demands more attention because it's so fundamental to the way the Web functions. That topic is links.

Styling Links

Links are everywhere on the Web: they truly are the basis of everything you see online. Nowadays, we're used to seeing highly decorative web pages adorned by a wealth of different images and features. Take a step back in time, though, and you'll find that the World Wide Web was little more than a collection of linked documents. Go back to the earliest browsers and you'll find that those links were underlined, which remains the case today. By default, a browser uses the following color scheme for links:

        
  • blue - an unvisited link
  •     
  • purple - a link to a web page that you've previously visited
  •     
  • red - an active link (one you're clicking on, but, for whatever reason, the next page hasn't quite appeared; we don't see this much in these days of widespread broadband usage, because pages load much faster than they used to!)

Page 14

This color scheme isn't to everyone's taste, but it's what we're stuck with now. At least, it's what we would be stuck with if we couldn't use CSS to redefine those colors.

At its most basic, a CSS style for links might look like this:

a {
  font-weight: bold;
  color: black;
}

Now, instead of being blue and having a normal font weight, your links appear in bold, black type. Try adding that to your style1.css file; save it and see how it affects your web pages -- Figure 3.13 illustrates.

1533_blacklinks
Figure 3.13. Styling all the links in our navigation to bold and black

Link States

As I mentioned previously, there are different types of links (unvisited, visited, active) that you'll come across on a web page. There's one other state that I haven't mentioned, but it's one with which you're probably familiar: the hover state (which occurs when you pass your cursor over the link). In CSS, you can change the styling of all of these link states using something that sounds complicated but is really fairly straightforward: pseudo-classes. Here is some CSS that shows the color/style scheme for the different link states:

a {
  font-weight: bold;
}
 
a:link {
  color: black;
}
 
a:visited {
  color: gray;
}
 
a:hover {
  text-decoration: none;
  color: white;
  background-color: navy;
}
 
a:active {
  color: aqua;
  background-color: navy;
}

The different states are addressed within the CSS through the use of the a element selector, and by applying (with the aid of a colon) the pseudo-classes of link, visited, hover, and active.

Note: Getting your Link States in Order

Browsers usually aren't fussy about the order in which you specify rules in your CSS file, but links should always be specified in the order shown above: link, visited, hover, and active. Try to remember the letters LVHA. The more bitter of us might find it easier to remember this mnemonic with the phrase, "Love? Ha!" We can thank Jeffrey Zeldman for that little gem. (Designing With Web Standards, Jeffrey Zeldman, New Riders.)

Let's change the styles for different link states in our project site:

       
  • If it's not already open, open the project site's CSS file (style1.css), and add the above CSS at the bottom of the file.
  •    
  • Save the CSS file.
  •    
  • Open any of the three web pages in your browser (or hit Reload) to see how the styled links display.

Figure 3.14 shows the three different link states: the home link is unvisited, the link to the About Us page shows that it has been visited previously (shown in gray), and the link to the Contact Us page is being hovered over by the user's cursor.

1533_linkstates
Figure 3.14. Styling three different link states using CSS


Page 15

Feel free to experiment in the CSS file with the different foreground and background colors, and other text formatting styles that were detailed in the table earlier in this chapter.

Note: Clearing your History

Your browser automatically stores a certain amount of your browsing history, and uses this information to decide whether a link has been visited or not (and, hence, how the link should be displayed). If you're building a site and testing links, you might want to check how an unvisited link looks but, because of your browsing history, they may all show as having been visited. This is almost certainly the case with our three-page project site -- the links in your navigation list are probably all gray. To reset this, you can clear your browser's history. In IE, select Tools > Internet Options. You'll see a button that reads Clear History, as shown in Figure 3.15; click it, then reload the web page. Any links you may have visited will now appear as unvisited.

1533_clearhistory
Figure 3.15. Clearing the history in IE displays unvisited link styles again

Other browsers have similar options, which may be found in locations such as Tools > Options or Preferences > Privacy. I won't list all the different methods for deleting your history from various browsers here, but if you rummage around, you should be able to find them without too much difficulty.

Class Selectors

To date, we've discussed the ways in which we can style various elements, such as paragraphs and headings; we've also seen how we can style elements in specific areas of the page using the id attribute. However, implementing broad-brush styles, such as coloring the text in all p elements navy, is very much a blanket approach to design. What if you want some of those paragraphs (or any elements, for that matter) to look a little different than the rest? Class selectors are the answer.

A class selector lets you define a style that can be used over and over again to style many different elements. So, for example, let's say you wanted to make some parts of your text stand out -- to make them look slightly more appealing or fun than other parts of the document. You could do so in your CSS like this:

.fun {
  color: #339999;
  font-family: Georgia, Times, serif;
  letter-spacing: 0.05em;
}

Here, we've created a style rule for a class called "fun." The fact that it's a class selector is denoted by the period at the beginning of the class name. We've slipped another property into this rule: letter-spacing defines the space between each of the letters. We've set a spacing of 0.05em here. 1em is the height of the M character in any font, so 0.05em is 5% of that height. It doesn't sound like much of a difference, but when it comes to typography, subtle changes are usually more effective than extreme ones.

In order to make use of the style, all you need to do is add the class="fun" attribute to an element:

<p class="fun">A man walks into a bar; you would've thought he'd  
    see it coming!</p>


Page 16

Let's apply some classes to our project site. First, we'll need to add the style rule shown above to the style sheet we're working on:

       
  • Open style1.css and add the CSS from the above block to the bottom of that file.
  •    
  • Save style1.css, then open about.html.
  •    
  • Find the paragraph that's contained inside the blockquote element.
  •    
  • Add the class="fun" attribute to the paragraph's opening tag.

This is how your markup should look right now:

Example 3.18. about.html (excerpt)
 
<blockquote>
  <p class="fun">"Happiness is a dip in the ocean followed by a
      pint or two of Old Speckled Hen. You can quote me on  
      that!"</p>
</blockquote>

Note that the class attribute was applied at the paragraph level. If there were a few paragraphs in our man Bob's quotation, you'd end up with something like this:

<blockquote>
  <p class="fun">"Happiness is a dip in the ocean followed by a  
      pint or two of Old Speckled Hen. You can quote me  
      on that!</p>
  <p class="fun">"Join us for a weekend away at some of our  
      favorite dive spots and you'll soon be making new  
      friends.</p>
  <p class="fun">"Anyway, about time I got on with some  
      <em>proper</em> work!"</p>
 
</blockquote>

There's a lot of repetition in there. Surely there's a tidier way to apply this style? There sure is!

<blockquote class="fun">
  <p>"Happiness is a dip in the ocean followed by a pint or two of  
      Old Speckled Hen. You can quote me on that!</p>
  <p>"Join us for a weekend away at some of our favorite dive  
      spots and you'll soon be making new friends.</p>
 
  <p>"Anyway, about time I got on with some <em>proper</em>  
      work!"</p>
</blockquote>


Page 17

In this example, we apply that class of fun to the blockquote element, so everything contained in that element inherits the style of the parent container. This saves us from having to apply these different classes all over our pages (an affliction that has become known as class-itis -- a not-too-distant relation of div-itis, which we discussed in Chapter 2, Your First Web Pages).

Note: class vs id

So far, we've looked at both class selectors (which involve periods) and id selectors (which involve pound signs). Are you confused by them? It's true that these selectors are similar, but there is one important difference: a specific id can only be applied to one XHTML element. So, for example, on any web page, there can only be one element with an id of mainnavigation, and only one with an id of header. A class, on the other hand, can appear as many times as required.

Note: Limiting Classes to Specific Elements

Imagine you want to italicise any blockquote element that has a class attribute with the value fun, but not other elements with that class value. Think it sounds tricky? Not with CSS!

.fun {
  font-family: Georgia, Times, serif;
  color: #339999;
  letter-spacing: 0.05em;
}
 
blockquote.fun {
  font-style: italic;
}

Now, any text inside a pair of <blockquote class="fun"> and </blockquote> tags will appear in italics.

By prefixing our normal class selector with an element name, we're telling the browser to apply the following declarations to that element-and-class combination only. It's as simple as element.class, but make sure you don't leave any spaces!

Note: Specifically Speaking

Those with an eagle eye will have noticed that not all of the fun styles in the previous example are actually applied to the quotation. The font-family and letter-spacing declarations take effect, but the color change does not! The reason for this can be explained with the concept of specificity.

Specificity simply means the rule that is the most specific is the one that is applied. "Most specific" really means "most deeply-nested in the document's structure." In our markup, the p element appears inside the blockquote element, so any style applied to the p is deemed to be the more specific of the two and, therefore, will always win out. We have such a rule in our project site -- the one that states that all paragraphs should be navy-colored -- so this is the one that takes effect:


Page 18

Example 3.19. style1.css (excerpt)
 
p {
  color: navy;
}

Note that, unlike the conflicting rules we encountered in the section called "Which Rule Wins?", this battle between style rules has no relation to the order in which they appear in the style sheet.

Specificity can get confusing, so don't lose too much sleep over it -- for now, it's enough just to be aware of the concept, as this may be the reason why one of your styles doesn't take effect when you're convinced it should. Specificity is covered in greater depth in the SitePoint book HTML Utopia: Designing Without Tables Using CSS [31], if you'd like to explore it further.

Styling Partial Text Using span

So, a class can be applied in many different places -- perhaps to a specific paragraph, or to a block of several paragraphs contained in a blockquote, or to a div that holds many different types of content. But what would you do if you wanted to apply the style to a very small section of text'maybe just a couple of words, or even just a couple of letters, within a paragraph? For this, once again, you can use the span element.

Earlier in this chapter I showed how you could use the span element in conjunction with inline styles to pick out and style specific words within a paragraph. The exact same technique can be used with classes: we simply place an opening <span> tag at the point at which we want the styling to begin, and the closing </span> tag at the point at which the styling should end. The advantage of this technique over the inline style demonstrated earlier is, of course, that with this technique, the style is defined in a single location, so you could potentially add the "fun" class to many different elements on many different pages with a minimum of hassle. When you decide that you want to have a different kind of fun (so to speak), you need only change your style sheet (style1.css) for that new style to be reflected across your site.

<p><span class="fun">Bubble Under</span> is a group of diving
    enthusiasts based in the south-west UK who meet up for diving  
    trips in the summer months when the weather is good and the  
    bacon rolls are flowing. We arrange weekends away as small  
    groups to cut the costs of accommodation and travel and to  
    ensure that everyone gets a trustworthy dive buddy.</p>

Try applying the span element to your "about" page as suggested in the above code. If you save the changes and check them in your browser (remember to hit Reload), your page should look like the one shown in Figure 3.16.


Page 19

1533_bubbleunderfun
Figure 3.16. Applying the "fun" class to two specific words

Note: Don't Throw (Needless) spans into the Works

The span element is nearly always used with a class attribute. There is not normally a good reason to apply a span element to your XHTML on its own, although you may see some web sites that do so.

Before you apply a span to any given element on your web page, take a moment to think about whether there's another element that's better suited to the task. For example, you should not use something like this:

<p>Do it <span class="shouty">now</span>!</p>

A more appropriate choice would be to use the strong element:

<p>Do it <strong>now</strong>!</p>

Think of the meaning of what you're writing, and aim for an XHTML element that suits the purpose. Other examples might be em, cite, and blockquote..

Summary

It's been another busy chapter, but my, how our site's blossoming! A chapter or two ago, we hadn't even built a web page, but now we're at the stage where we know how to apply a (virtual) lick of paint to any type of XHTML element on a page, to a specific section of a web page depending on its id, or to arbitrary portions of a page -- sometimes in several different places -- using class selectors.

The web site is starting to look a little more colorful, but the layout is still fairly basic. In the next chapter, we'll look at how it's possible to change the layout of elements on a page -- their position, shape, size, and more -- using CSS.

Styling text? Been there, done that. Let's move to the next level! For that, you'll need your own copy of Build Your Own Web Site The Right Way Using HTML & CSS [32]. After the next chapter, on CSS, we explore the tasks of using images on your web site, the appropriate use of tables, building forms that promote user interaction, publishing your site to the Web, adding a blog to your site, and hooking up to ready-made tools like statistics packages, search functions, and discussion forums that you can apply to your site. As I mentioned, the book comes with a complete code archive, so you can apply the files we use in the book straight into your own sites (makes life easy, eh?).

About This Article

   

Build your own AJAX web applicationsThis Article Excerpted from: “Build Your Own Website The Right Way Using HTML & CSS” published by Melbourne-based SitePoint.

   

Order online and get free shipping when you order a second book, plus a bonus quick reference poster worth $9.95.

    SitePoint
 

NetRegistry November Newsletter

 
   

Read the Nov '06 newsletter here

   
Special Offer
   

Content