Chapter 4. Adding Graphics

It’s safe to say that the creators of the Internet never imagined that it would look the way it does today—thick with pictures, ads, videos, and animated graphics. They designed a meeting place for leading academic minds; we ended up with something closer to a Sri Lankan bazaar. But no one’s complaining, because the Web would be an awfully drab place without pictures.

In this chapter, you’ll master the art of web graphics. You’ll learn how to add ordinary images to a web page and to position them perfectly. You’ll also see how to use styles to jazz up your pictures with borders, captions, and background effects.

Introducing the <img> Element

Web page pictures don’t live in HTML files. Instead, you store them as separate files, like banana.jpg and photo01.jpg. To display a picture in a web page, you use the <img> element.

For example, here’s an <img> element that displays the picture banana.jpg:

<img src="banana.jpg" />

When a browser reads the <img> element above, it sends out a request for the banana.jpg file. After retrieving it, the browser inserts the picture into the page in place of the <img> element. If the image file is large or the Internet connection is very slow, you might actually see the web page text appear first, before the picture shows up.

Here’s an example that puts a picture in the second paragraph of a typical (albeit somewhat boring) web page (Figure 4-1):

<!DOCTYPE html>
<html>
<head>
  <title>Two paragraphs, One picture</title>
</head>
<body>
  <p>In the next paragraph, you'll see a picture.</p>
  <p><img src="banana.jpg" /></p>
</body>
</html>
One <img> element is all it takes to summon the banana.jpg picture and inject it into this SimplePic.htm web page.
Figure 4-1. One <img> element is all it takes to summon the banana.jpg picture and inject it into this SimplePic.htm web page.

Alternate Text

The src attribute is the only detail an <img> element needs to function. But there’s one other attribute you should supply—the alt attribute, which represents the alternate text a browser displays if it can’t display the image itself.

Here’s an example of an <img> element that includes alternate text:

<img src="matador.jpg" alt="There's no picture, so all you get is this
alternate text." />

Alternate text proves useful not only in the above circumstance, but in several other cases as well, including when:

  • A viewing-impaired visitor uses a screen-reading program (a program that “speaks” text, including the words in an alt attribute).

  • A search engine (like Google) analyzes a page and all its content so it can index the content in a search catalog.

  • A browser requests a picture but can’t find it. (Perhaps you forgot to copy it to your web server?)

  • A web visitor switches off his browser’s ability to display pictures to save page-download time (this isn’t terribly common today).

  • A browser doesn’t support images (this is understandably rare these days, too, but the text-only Lynx browser is still kicking around on some old Unix systems).

The first two reasons are the most important. Web experts always use meaningful text when they write alt descriptions to ensure that screen readers and search engines interpret the corresponding pictures correctly.

Don’t confuse alternate text with pop-up text, which is an optional message that appears when a website visitor points to an image (see Figure 4-2). To add pop-up text, use the title attribute:

<img src="matador.jpg" alt="A matador extends his cape in welcome."
title="Welcome to the ring." />
Left: For this <img> element to work, you have to put the file it points to in the same folder as the web page. Otherwise, you’ll see the dreaded broken image icon.Middle: The alternate text helps a bit when you use it to explain what your visitor should see.Right: You can also use the title attribute to supply pop-up text, which appears when a guest points to the picture.
Figure 4-2. Left: For this <img> element to work, you have to put the file it points to in the same folder as the web page. Otherwise, you’ll see the dreaded broken image icon. Middle: The alternate text helps a bit when you use it to explain what your visitor should see. Right: You can also use the title attribute to supply pop-up text, which appears when a guest points to the picture.

If an <img> element links to a picture that doesn’t exist and you haven’t supplied any alternate text, every browser reacts the same way—by showing a blank box with a broken-image icon (Figure 4-2, left). But if you have a missing picture and your <img> element includes alternate text, the result varies. Chrome continues to show a blank box. Internet Explorer shows a blank box but adds the alternate text inside it (see Figure 4-2, middle). And Firefox displays the alternate text as a paragraph of ordinary content on the page, with no picture box or missing picture icon to alert you of the problem.

Picture Size

When it comes to pictures, the word size has two meanings: it can refer to the dimensions of the picture (how much screen space it takes up on a web page), or it can signify the picture’s file size (the number of bytes required to store it). To web page creators, both measures are important, but this section is all about the physical dimensions. (We’ll talk about file sizes on Compression.)

Picture dimensions are noteworthy because they determine how much real estate an image occupies onscreen. Web weavers measure graphics in units called pixels. A pixel represents one tiny dot on a computer screen. The web world doesn’t work with fixed units like inches and centimeters, because you never know how large your visitor’s monitor is, and therefore how many pixels it can cram in.

Ordinarily, a picture gets its full resolution. So if your picture is a gigantic 2000 x 4000 pixels, that’s what appears in your web page. However, the <img> element lets you resize a picture through its optional height and width attributes. Consider this example:

<img src="photo01.jpg" alt="An explicitly sized picture" width="100"
height="150" />

In this markup, the <img> element gives the picture a width of 100 pixels and a height of 150 pixels. If this is larger than the real dimensions of the photo01.jpg picture, the browser stretches and mangles the image to make it fit the size you set (see Figure 4-3).

Note

Approach height and width attributes with caution. Sometimes, novice web authors use them to make thumbnails, small versions of large pictures. But using the height and width attributes to scale down a large picture comes with a performance penalty—namely, the browser still needs to download the original, larger image, even though it displays it at a smaller size. On the other hand, if you create thumbnails in a graphics editor like Photoshop, the file sizes are smaller, ensuring that your pages download much more quickly.

Many web page designers leave out image height and width attributes. However, experienced web developers sometimes add them using the same dimensions as the actual picture. As odd as this sounds, there are a couple of good reasons to do so.

First, when you include image size attributes, browsers know how large a picture is and can start laying out a page even as the graphic downloads (see Figure 4-2, left). On the other hand, if you don’t include the height and width attributes, the browser won’t know the dimensions of the picture until it’s fully downloaded, at which point it has to rearrange the content. This is potentially distracting if your visitors have slow connections and they’ve already started reading the page.

The second reason is because the dimensions control the size of the picture box if a browser can’t download the image (see Figure 4-2, middle). However, you shouldn’t rely on this strategy, because it doesn’t work in Firefox—that browser ignores the height and width attributes for missing pictures, and it doesn’t display an image box. (To really prevent a missing picture from scrambling your layout, carve your pages into separate sections using <div> elements, and position them with style sheets, as described in Chapter 8.)

Never use HTML’s height and width attributes to resize a picture, because the results are almost always unsatisfying. Enlarged pictures are jagged, shrunken pictures are blurry, and if you change the ratio of height to width (as with the top-right and bottom images shown here), browsers squash pictures out of their normal proportions (top left).
Figure 4-3. Never use HTML’s height and width attributes to resize a picture, because the results are almost always unsatisfying. Enlarged pictures are jagged, shrunken pictures are blurry, and if you change the ratio of height to width (as with the top-right and bottom images shown here), browsers squash pictures out of their normal proportions (top left).

So should you use the height and width attributes? It’s up to you, but they’re probably more trouble than they’re worth for the average website. If you use them, you need to make sure to update them if you change the size of your picture, a chore that can quickly get tedious.

Picture Placement

If you don’t take any extra steps, a browser inserts each image into the flow of your text, right where you put the <img> element in your HTML. It lines up the bottom of the graphic with the baseline of the text that surrounds it. (The baseline is the imaginary line on which the text sits.) This is called an inline image, and you can see one in Figure 4-4.

You can change the vertical alignment of text using the vertical-align style sheet property. Specify a value of top, middle, or bottom, depending on whether you want the picture to line up with the top, middle, or bottom of the line of text.

Usually, you don’t want a picture inside an ordinary line of text (unless it’s a very small emoticon, like the ones you find in instant message programs). You can use paragraphs, line breaks, or tables to do a better job of separating images from text.
Figure 4-4. Usually, you don’t want a picture inside an ordinary line of text (unless it’s a very small emoticon, like the ones you find in instant message programs). You can use paragraphs, line breaks, or tables to do a better job of separating images from text.

Here’s an example that adds an inline style (Using Inline Styles) to the image that sets the vertical-align property. It lines the picture up with the top of the line of text.

<img src="happy.gif" alt="Happy Face" style="vertical-align: top" />

This technique is worthwhile if you’re trying to line up a very small picture, like a fancy bullet. But it doesn’t work very well with large images. That’s because no matter which vertical-align option you choose, only one line of text can appear alongside an inline picture (as you can see in Figure 4-4).

If you don’t want your picture to pop up in the middle of your text, you can separate it from the surrounding content using line breaks (<br>) or horizontal rules (<hr>). However, inline images never move on their own. If you want to create floating pictures with wrapped text, hold that thought—you’ll see how on Tutorial: Wrapping Text Around an Image.

Tutorial: Storing Images in a Subfolder

The previous examples kept things simple by assuming that your web pages and image files are all in the same folder. If, for example, you put the SimplePic.htm page (Figure 4-1) on your desktop, you also needed to put the banana.jpg file there as well, so the <img> element could find it.

This is all well and good, but sometimes you don’t want to keep your web pages and pictures in the same place. In fact, if you have a large collection of pictures, it’s a good idea to keep them in a separate subfolder. That way, you can better manage the clutter, so you can edit web pages without tripping over picture files. This setup also lets you browse and tweak the pictures without being distracted by the web pages. In the following tutorial, you’ll set up this sort of arrangement.

Tip

Like all the tutorials in this book, you can find the support files for this exercise on the companion site at http://prosetech.com/web. Just look in the folder named Tutorial-4-1 (which stands for “Chapter 4, first tutorial”). There you’ll find the files you need to get started in the Start subfolder, and the solution to the exercise in the End subfolder.

Here’s what you need to do:

  1. First, get the SimplePic.htm page and the banana.jpg image from the Tutorial-4-1\Start folder.

    Put them both on your desktop, or copy them to the location you use to store web pages as you work on them.

  2. Create a subfolder named images.

    You can name your image-holding subfolder whatever you want. The name “images” may not seem very descriptive, but it’s a common choice, so it’s the approach we’ll take in this tutorial.

  3. Move the image file (banana.jpg) into the images subfolder.

    If you were to open the web page now, you’d find that your picture has gone missing from the <img> element. But fear not—a fix is at hand.

  4. Open the SimplePic.htm web page in your text editor.

  5. Edit the src attribute of the <img> element so it includes the subfolder name.

    In other words, you need to change this:

    <p><img src="banana.jpg" /></p>

    to this:

    <p><img src="images/banana.jpg" /></p>

    Notice that you use a forward slash (/) in relative addresses, not a backward slash (\). If you’re used to file paths on Windows computers, this is a small but important change—ignore it, and your pictures might not appear when a browser opens your pages from a web server.

    Note

    Make sure you’re consistent with capitalization. If you name a subfolder images but refer to it as Images in the <img> element, you can run into a serious headache. Your pictures may work when you test the web page on your own computer, but they’ll fail to appear when you upload the page to a real website.

  6. Save your changes and then open your page in a browser (or refresh it, if it’s already open).

    Now the image appears in the page, exactly as it did before.

Note

The technical term for the path that leads to the picture in this example (images/banana.jpg) is a relative path. Relative paths tell a browser where to go, starting from the current location (where the web page is located). Relative URLs describes relative paths in more detail and has more examples.

File Formats for Web Graphics

So far, you’ve seen image examples that have the extension .jpg. However, web browsers actually support a small set of standard image formats:

  • The JPEG (pronounced “jay-peg”) format is suitable for photos and pictures that can tolerate some loss of quality. JPEG doesn’t work as well if your picture contains text or line art, because the resulting image won’t be as sharp.

  • The GIF (pronounced “jif” or “gif”) format is suitable for graphics with a very small number of colors (like simple logos or clip art). It gives lousy results if you use it to display photos.

  • The PNG (pronounced “ping”) format is suitable for all kinds of images, although it doesn’t compress photos as well as JPEG. PNG is particularly good for small, sharp graphics (like logos) and today it’s used as a more powerful replacement for the GIF standard.

  • SVG (Scalable Vector Graphics) is an up-and-coming standard for vector drawings (for example, logos and figures that consist of text and shapes, rather than photographs). For the right type of art, SVG has a number of advantages, including its small size and flexibility. You can resize SVGs without losing detail or getting blurry images. However, Internet Explorer versions 8 and earlier don’t display SVG images, which means it’s still not a reliable choice for web graphics. For that reason, this chapter doesn’t discuss it, although you can learn more about it (and some of the workarounds that make it work, sort of, in old versions of Internet Explorer) at http://tinyurl.com/2gy2vyg.

Note

Some browsers give you a few more format options, but you’re better off steering away from them to ensure widest browser compatibility. For example, Internet Explorer supports bitmaps (image files that end with the .bmp extension). Don’t ever use them—not only will they confuse other browsers, but they’re also ridiculously large because the standard doesn’t include compression.

Graphics formats differ in how they use compression to squash down file sizes, and in how many colors they offer. You’ll dive deeper into these considerations in the following sections. For now, Table 4-1 outlines how the different formats stack up, and Figure 4-5 compares them in a web page (see the box on How Compression Works for an explanation of compression types).

Table 4-1. Image file formats for the Web.

FORMAT

TYPE OF COMPRESSION

MAXIMUM COLORS

BEST SUITED FOR

JPEG

Lossy

24-bit (16.7 million colors)

Photos.

GIF

Lossless

8-bit color (256 colors)

Simple logos, graphical text, and diagrams with line art.

PNG

Lossless

24-bit (16.7 million colors)

Images that would normally be GIF files but need more colors.

SVG

Lossless (but it’s optional, as SVG data is already quite small)

24-bit (16.7 million colors)

Art drawn in an illustration program. However, IE version 8 and earlier don’t support it.

JPEGs and GIFs are the original image formats of the Web. You’ll notice that GIFs produce clearer text, while JPEGs do a much better job of handling continuous bands of color. GIFs simulate extra colors through dithering, a process that mixes different colored dots to simulate a solid color. The results are unmistakably unprofessional. (You may not be able to see the reduced text quality in this black-and-white screen capture, but if you take a look at the file JPEGvsGIF.htm from the companion site, you’ll see the difference up close.) For this reason, the PNG standard has largely replaced the GIF standard.
Figure 4-5. JPEGs and GIFs are the original image formats of the Web. You’ll notice that GIFs produce clearer text, while JPEGs do a much better job of handling continuous bands of color. GIFs simulate extra colors through dithering, a process that mixes different colored dots to simulate a solid color. The results are unmistakably unprofessional. (You may not be able to see the reduced text quality in this black-and-white screen capture, but if you take a look at the file JPEGvsGIF.htm from the companion site, you’ll see the difference up close.) For this reason, the PNG standard has largely replaced the GIF standard.

Compression

Once upon a time, web connections were slow and web designers spent hours agonizing over the size of every image on their sites. Today, image size is still a consideration (albeit a smaller one) because of mobile devices. People using smartphones, tablets, and other web-enabled devices are often forced to use slower connections (for example, the overtaxed WiFi at the local coffee shop). Phone companies also charge based on usage, so visit too many picture-clogged pages and it could cost you.

To keep your website as fast, lightweight, and efficient as possible, follow this advice:

  • Keep your pictures small. If you really must fill the browser window, create a smaller version of the picture, put that on the page, and then make it a link (Understanding the Anchor). Then, when someone clicks the picture, you can open a new page with the full-sized image in it.

  • Use the right image format. For large photos, that’s JPEG.

  • Lower the quality. To get better compression, you can lower the quality of your JPEGs (if your graphics program has this feature). But test out this approach first to make sure you can tolerate the loss in detail. As you compress a JPEG image, you introduce various problems collectively known as compression artifacts. The most common are blocky regions in an image, halos around edges, and a general blurriness. Some pictures exhibit these flaws more than others, depending on the image’s amount of detail.

  • Use a picture-squishing tool. There are plenty of free tools that can scan through a folder of image files and crush each one down to a smaller size. You’ll probably need to go get coffee (because the process can take some time), but you’ll be rewarded with files that are (on average) 15% to 40% smaller, with no reduction in quality. Try FileOptimizer (http://tinyurl.com/FileOptimizer) for Windows computers, and ImageOptim (http://imageoptim.com) for Macs.

Choosing the Right Format

It’s important to learn which format to use for a given task. To help you decide, walk through the following series of questions.

Is your picture a hefty photo?

Yes: JPEG is the best choice for cutting large, finely detailed pictures down to size. Depending on the graphics program you use, you may be able to choose how much compression you want to apply.

Does your picture have sharp edges and need more than 256 colors?

Yes: PNG is the best answer here. It supports full color and uses lossless compression, so you don’t lose any detail. If your picture has a limited number of colors (256 or fewer), you can use GIF instead of PNG, but there’s no reason to.

Does your picture include a transparent area?

Yes: Use PNG. As you’ll learn on Tutorial: Wrapping Text Around an Image, PNG permits partial transparency, which lets you stack transparent layers and blend them to create a more natural effect. GIF has a cruder all-or-nothing transparency feature, and JPEG doesn’t support transparency at all.

Note

You read earlier that HTML keeps page elements like headlines in rectangular boxes. The same holds true for images—even a picture of a beach ball is enclosed in a box. That’s why transparency in images is so important. It lets you place an image on a page with that page’s background showing through; the result is a page with a seamlessly integrated image.

Putting Pictures on Colored Backgrounds

No matter what format you use, graphics programs store your image files as rectangles, even if the image itself isn’t rectangular. For example, if you create a smiley-face graphic, your graphics program saves that round illustration on a white, rectangular background.

If your page background is white as well, this doesn’t pose a problem because the image’s background blends in with the rest of your page. But if your page has a different background color (Colors), you’ll run into the graphical clunkiness shown in Figure 4-6.

Top: When you place this smiley-face picture on a page with a white background, it blends right in.Bottom: With a non-white background, the white box around your picture is glaringly obvious.
Figure 4-6. Top: When you place this smiley-face picture on a page with a white background, it blends right in. Bottom: With a non-white background, the white box around your picture is glaringly obvious.

Web designers came up with two solutions. One is to use transparency, a feature common to both PNG and GIF graphics. The basic idea is that your image contains transparent pixels—pixels that don’t have any color at all. When a browser comes across these, it doesn’t paint anything. Instead, it lets the background of the page show through. To make part of an image see-through, you define a transparent color using your graphics program. In the example above, for instance, you’d set the white background of your smiley-face graphic as the transparent color.

Although transparency seems like a handy way to make sure your image always has the correct background, in practice, it rarely looks good. The problem you usually see is a jagged edge where the colored pixels of your picture end and the web page background begins (see Figure 4-7).

The easiest way to fix this problem is to use the correct background color when you create your web graphic, instead of using transparency. In other words, when you draw your smiley-face image, give it the same background color as your web page. Your graphics program can then perform antialiasing, a technology that smooths an image’s jagged edges to make them look nice. That way, the image edges blend in well with the picture’s background, and when you display the image on your web page, it fits right in. The only limitation with this approach is its lack of flexibility. If you change your page color, you need to edit all your graphics.

The picture at the bottom of this page uses transparency, but the result—a jagged edge around the smiley face—is less than stellar. To smooth this edge, graphics programs use a sophisticated technique called antialiasing, which blends the picture color with the background color. Browsers can’t perform this feat, so the edges they make aren’t nearly as smooth.
Figure 4-7. The picture at the bottom of this page uses transparency, but the result—a jagged edge around the smiley face—is less than stellar. To smooth this edge, graphics programs use a sophisticated technique called antialiasing, which blends the picture color with the background color. Browsers can’t perform this feat, so the edges they make aren’t nearly as smooth.

Another approach is to use blended transparency (also known as alpha blending, because the alpha value of an image is a number that represents how transparent a pixel is). For example, instead of creating an image that cuts abruptly between colored pixels and transparent pixels, use one that blends the edge out using a fringe of semitransparent pixels. This feature sounds great, and PNG graphics use it, but you need serious Photoshop skills to create this effect. (If you want to go this route, try starting with the bare-bones tutorial at http://tinyurl.com/ypf78g.) Sadly, this is the price of creating polished web graphics.

Tutorial: Wrapping Text Around an Image

When you put an ordinary, unadorned <img> in your web page, it becomes an inline image. As explained earlier, inline images are locked into place alongside your text. You can put text above an inline image and text below it, but that’s about as fancy as your page can get.

While inline images serve their purpose, they aren’t the most elegant solution. A more flexible approach—and one that almost every web page uses—is to wrap text around images, so that the page mixes text and pictures into a cohesive design. Images that have text wrapped on one side or the other are called floating images, because they float next to an expanse of text. To create a floating image, you rely once more on the power of style sheets.

Tip

Like all the tutorials in this book, you can find the solution for this exercise on the companion site at http://prosetech.com/web. Just look in the folder named Tutorial-4-2 (which stands for “Chapter 4, second tutorial”). There you’ll find the files that you need to get started in the Start subfolder, and the solution to the exercise in the End subfolder.

Here’s how to get started:

  1. Get the ordinary version of the page from the Tutorial-4-2\Start folder.

    Find the web page TomatoSoupRecipe.htm and an image named TomatoSoup.jpg. Right now, this page uses an inline image, so the picture of the steaming-hot bowl of soup sits in the middle of the content, between the recipe list and the recipe instructions. Figure 4-8 shows the page as it is now, and Figure 4-9 shows the result you’re after.

    This inline image cleaves one section of text from the next.
    Figure 4-8. This inline image cleaves one section of text from the next.
  2. Decide what kind of style sheet you want to use.

    As always, you can apply style properties to the <img> element using an external style sheet, an internal style sheet, or an inline style (The Three Types of Style Sheets covers the differences).

    In this example, the TomatoSoupRecipe.htm page already has an internal style sheet that sets the font. You can find the rules in the <style> element, which is in the <head> section at the top of the page.

    Now that you’ve floated the image to the left, the text can fill the space beside it, on the right.
    Figure 4-9. Now that you’ve floated the image to the left, the text can fill the space beside it, on the right.
  3. Create a style for the <img> element, and then add it to your style sheet.

    This tutorial uses the following style, which you can add to the internal style sheet:

    <style>
      body {
        font-family: Georgia;
      }
      img.FloatLeft {
      }
    </style>

    This style has a two-part name. The first part, img, is the element name. It makes sure that the style can work only on images. The second part, FloatLeft, is the class name. It ensures that the rule targets images that have the FloatLeft class associated with them (because you probably don’t want every picture on your page to float).

    To apply the FloatLeft style, you have to add the class attribute to the target <img> element, like so:

    <img src="TomatoSoup.jpg" alt="A bowl of tomato soup." class="FloatLeft" />

    You now have a style sheet, a style rule for floating images, and an image that uses your rule. However, nothing has changed, because you haven’t defined the FloatLeft style yet.

  4. Set the float property.

    You create floating images using a CSS property named float. You set the value of the float property to either left or right, which lines up the image on either the left or right edge of the text.

    In this tutorial, you want to float your soup on the left, so you must add the two lines shown in bold:

    <style>
      body {
        font-family: Georgia;
      }
      img.FloatLeft {
        float: left;
        margin: 10px;
      }
    
    </style>

    When you set the float attribute, it makes sense to adjust the image’s margin settings at the same time, so you have a little breathing room between your image and the surrounding text.

  5. Save your changes, and open (or refresh) the web page.

    Now you can admire your handiwork (Figure 4-9).

To get floating text to work the way you want, always put the <img> element just before the text that should wrap around the image. In the soup recipe example, you placed it just after the recipe list and before the list of instructions.

Note

Based on this example, you might think that the float property sends a picture to the left or right side of a page, but that’s not exactly what happens. Remember, in CSS, HTML treats each element on a page as a container. When you create a floating image, the image actually goes to the left or right side of its container. If you put an image inside a smaller container—like a cell in a table or a <div> that creates a sidebar—you’ll see that the image floats to the side of that element.

Figure 4-10 shows a few more image-wrapping examples, which demonstrate what happens if you move the image farther down into a paragraph of text or float it on the right.

Remember, all image files are rectangles. When you wrap text around a floating image, the browser follows the contour of this invisible square, even if the image itself has a different shape, like a circle, or includes extra white space.
Figure 4-10. Remember, all image files are rectangles. When you wrap text around a floating image, the browser follows the contour of this invisible square, even if the image itself has a different shape, like a circle, or includes extra white space.

Adding a Border

Right now, your picture is sitting pretty in the page. But maybe you want something else to divide the soup photo from its surrounding content. CSS has the perfect tool for you: a customizable border that you can draw around your picture in a close-fitting rectangle.

In Chapter 3, you learned to use the border-style and border-width properties to add borders around blocks of text. Happily, you can use these properties to add a border to an image just as easily.

In the tomato soup example, you simply add the border-style and border-width properties to the style rule you already created. Here’s how you apply a thin, grooved border to all sides of the soup image:

img.FloatLeft {
  float: left;
  margin: 10px;
  border-style: groove;
  border-width: 3px;
}

Figure 4-11 shows the basic border styles. Remember, you can change the thickness and color of any border to get a very different look (Basic Borders).

This example shows several inline images in a row, separated from one another with a single space. Each image sports a different border. The browser fits all the pictures it can on the same line. When it reaches the right edge of the browser window, it wraps the pictures to the next line. If you resize the window, the arrangement of the pictures changes.
Figure 4-11. This example shows several inline images in a row, separated from one another with a single space. Each image sports a different border. The browser fits all the pictures it can on the same line. When it reaches the right edge of the browser window, it wraps the pictures to the next line. If you resize the window, the arrangement of the pictures changes.

Adding a Caption

Captions add a nice touch to photos, and you can put them above or below the image. For inline images, you just add a line of text immediately before or after the picture, separated by a line break. But that won’t work with floated images, because the image and the caption have to float in tandem.

As it happens, the solution is simple. Just take the FloatLeft style rule shown earlier, and change the name from img.FloatLeft to .FloatLeft. That way, you can use the rule with any element:

.FloatLeft {
  float: left;
  margin: 10px;
}

Next, wrap the <img> element and your text in a <span> element, and then make the entire <span> element float using the FloatLeft style rule:

<span class="FloatLeft">
   <img src="TomatoSoup.jpg" alt=" A bowl of tomato soup." />
   <br />
   <i>A bowl of rustic tomato soup</i>
</span>

Figure 4-12 shows the result.

If you don’t want to float a picture on its own, you can float a box that holds a picture and some other content, like this caption.
Figure 4-12. If you don’t want to float a picture on its own, you can float a box that holds a picture and some other content, like this caption.

Note

You use a <span> element in this example instead of a <div> element because you can put a <span> element inside other block elements, like a paragraph. In other words, by using a <span> element, you can easily put your floating picture-and-caption container inside one of your paragraphs.

Clearing a Float

Wrapping text can get a little tricky, because the results you get depend on the width of the browser window. For example, you might think that your text is long enough to wrap around a graphic, but in a wide window, it might take up just a few short lines, letting the rest of the page’s content bump into your floating graphic. You might even end up with another floating picture bumping into your first floating picture.

To see this problem in action, it’s time to look at another tutorial. In this tutorial, found in the Tutorial-4-3 folder, you’re still dealing with the same content as the previous tutorial. However, there’s a second picture added to the mix, which exposes a new problem.

Figure 4-13 demonstrates the issue, using the version of the TomatoRecipe.htm page from the Tutorial-4-3\Start folder. This page includes two pictures, both floating on the left edge. The effect works in a narrow window, but in a wide browser the two pictures get into a tangle.

In this version of the tomato soup page, the goal is to place one picture next to the list of ingredients, and another next to the list of steps. But the browser wraps everything next to the first picture (as long as it fits), causing this jumbled layout.
Figure 4-13. In this version of the tomato soup page, the goal is to place one picture next to the list of ingredients, and another next to the list of steps. But the browser wraps everything next to the first picture (as long as it fits), causing this jumbled layout.

To prevent this layout pileup, you use the clear property. It turns off any wrapping that’s currently in effect on the page, forcing the browser to jump to the bottom of the floating content before it continues displaying the rest of the page.

You can add the clear property to any element. Common choices include the paragraph element (<p>) or the line break element (<br>). Here’s an example:

<br style="clear: both;" />

To fix the problem in Figure 4-13, use the clear property after the list of ingredients ends and before the list of instructions starts. To try this out, open the starter version of the TomatoRecipe.htm page, insert the <br> element where you believe it should go, and then refresh the page to see the result. If you put the line break in the right place, you’ll get the more organized version of the page featured in Figure 4-14.

The clear property tells your browser to stop wrapping text, ensuring that the next paragraph starts after the floating picture.
Figure 4-14. The clear property tells your browser to stop wrapping text, ensuring that the next paragraph starts after the floating picture.

Here’s a shortened version of the solution, which shows where the pictures and line break fall in the markup. You can review the full markup by looking at the page in the Tutorial-4-3\End folder:

<h1>Simple Tomato Soup</h1>

<!-- Here's the first floating picture, next to the ingredients. -->
<img src="TomatoSoup.jpg" class="FloatLeft" alt="A bowl of tomato soup." />

<p class="Description">A simple, nourishing soup that showcases fresh
tomatoes.</p>
<ul>
<li>2 carrots</li>
<li>2 sticks celery</li>
<li>1-2 onions</li>
<li>1 tsp salt</li>
<li>3 lbs tomatoes, peeled</li>
<li>A few mint leaves</li>
</ul>

<!-- Now jump past the first floated picture. -->
<br style="clear: both;" />

<!-- Here's the second floating picture, next to the instructions. -->
<img src="BlendTheSoup.jpg" class="FloatLeft" alt="A bowl of tomato soup." />

<p>Roughly chop the carrots, celery, and onions. The mixture ...

Note

In this example, the clear property is set to both, which tells the browser to turn off floating for both left-floated and right-floated content. Instead of using both, you can use left (skip past any left-floated content only) or right (skip past any right-floated content).

Background Images

CSS makes it possible to use an image as the background for a page, which is a neat but slightly old-fashioned way to add personality to your website. For example, you could use light parchment paper as a background for a literary site. A Twilight fan site might put a dark cemetery image to good use. Some people find the effect a little distracting, but it’s worth considering if you want to add a dramatic touch and you can restrain yourself from going overboard. (Or if you straight-up love kitsch.)

Tip

Although professional websites don’t usually have a whole-page background, the CSS background image feature is still plenty useful. As you’ll learn later in this section, you can use it to put a background behind any individual element, which makes it a useful way to add headers, panel borders, and other sorts of decoration to your pages.

Web designers almost always choose to tile background images, which means a browser copies a small picture over and over again until it fills the window (see Figure 4-15). You can’t use a single image to fill a browser window because you have no way of knowing how wide and tall to make it, given people’s variable browser settings. And if you did have visitors’ exact screen measurements, you’d need to create an impractically large image that would take a long time to download.

Top: Start with a small tile graphic with a stony pattern.Bottom: Using style sheets, you can tile this graphic over the whole page. In a good tiled image, the edges line up to create the illusion of a seamless larger picture.
Figure 4-15. Top: Start with a small tile graphic with a stony pattern. Bottom: Using style sheets, you can tile this graphic over the whole page. In a good tiled image, the edges line up to create the illusion of a seamless larger picture.

To create a tiled background, use the background-image style property. Your first step is to apply this property to the <body> element, so that you tile the whole page. Next, you need to provide the name of the image file using the form url(‘filename’), as shown here:

body {
  background-image: url('stones.jpg');
}

This tiles the image stones.jpg across a page to create your background.

Keep these points in mind when you create a tiled background:

  • Make your background light, so the text displayed on top of it remains legible. (If you really have to go dark, you can use white, bold text so that it stands out. But don’t do this unless you’re creating a website for a trendy new band or opening a gothic clothing store.)

  • Set the page’s background color to match the color of the tiled image. For example, if you have a dark background picture and use white text for your content, make the background color black. That way, if a browser can’t download the background image, visitors can still see your content.

  • Use small tiles to reduce the amount of time your visitors need to wait before they can see the page.

  • If your tiled image has an irregular pattern, make sure the edges line up. The left edge should continue the right edge, and the top edge should continue the bottom edge. Otherwise, when the browser tiles your image, you’ll see lines where it stitches the tiles together.

Tip

The Web is full of common background images, like stars, blue skies and clouds, fabric and stone textures, fires, dizzying geometric patterns, borders, and much more. You can find these by searching Google for “backgrounds,” or head straight to the somewhat dated sites that specialize in downloadable backgrounds, like www.grsites.com/textures and www.backgroundsarchive.com.

Background Watermarks

Most websites tile a picture to create a background image, but that’s not your only option. You can also take a single image and place it at a specific position on your page. Think, for example, of a spy site whose background image faintly reads “Top Secret and Confidential.”

An inconspicuous single-image background like this is called a watermark. (The name stems from the process used to place a translucent logo on paper saturated with water.) To make a good watermark, use a background picture that’s pale and unobtrusive.

To add a watermark to your page, use the same background-image property you learned about above. But you need to add a few more style properties (see Table 4-2). First, you have to turn off tiling using the background-repeat property. At the same time, it makes sense to align your picture on the page to either side or centered, using the background-position property.

Here’s an example that places a picture in the center of a web page:

body {
  background-image: url('smiley.jpg');
  background-repeat: no-repeat;
  background-position: center;
}

Note

The center of your document isn’t necessarily the center of your browser window. If, for example, you position your image in the center of a long web page, you won’t see it until you scroll down.

Table 4-2. Background image properties.

PROPERTY

DESCRIPTION

COMMON VALUES

CAN BE INHERITED?

background-image

The image file you use as your page background.

A URL pointing to the image file, as in url(‘mypig.jpg’)

No[a]

background-repeat

Whether or not you tile the image to fill the page; you can turn off tiling altogether, or turn it off in one dimension (so that images tile vertically but not horizontally, for example).

repeat, repeat-x, repeat-y, no-repeat

No

background-position

Where you want to place the image. Use this only if you aren’t tiling the image.

top left, top center, top right, center left, center, center right, bottom left, bottom center, bottom right

No

background-attachment

Whether you want to fix the image (or tiles) in place when a visitor scrolls the page.

scroll, fixed

No

[a] Background pictures aren’t inherited. However, if you don’t explicitly assign a background color to an element, it’s given a transparent background, which means the background of the containing element will show through.

You can also turn off an image’s ability to scroll along with the rest of a page to get the rather odd effect of an image that’s fixed in place (see Figure 4-16). For example, this style creates a background image that always sits squarely in the center of a window:

body {
  background-image: url('smiley.gif');
  background-repeat: no-repeat;
  background-position: center;
  background-attachment: fixed;
}

Backgrounds for Other Elements

You don’t need to apply a background to a whole page. Instead, you can bind a background to a single paragraph or, more usefully, to a <div> element. That way, you can create the same effect as a sidebar in a magazine. Usually, you want to add a border around this element to separate it from the rest of your web page. You might also need to change the color of the foreground text so it’s legible (for example, white shows up better than black on dark backgrounds).

This staring smiley face remains perpetually in the center of the window, even when you scroll up or down. It’s a little creepy.
Figure 4-16. This staring smiley face remains perpetually in the center of the window, even when you scroll up or down. It’s a little creepy.

Here’s an example of a background image you can use with any container element:

.pie {
  background-image: url('pie.jpg');
  margin-top: 20px;
  margin-bottom: 10px;
  margin-left: 70px;
  margin-right: 70px;
  padding: 10px;
  border-style: double;
  border-width: 3px;
  color: white;
  background-color: black;
  font-size: large;
  font-weight: bold;
  font-family: Verdana,sans-serif;
}

This style specifies a background image, sets the margins and borders, and chooses background and foreground colors to match.

Here’s a <div> that uses this style:

     <div class="pie">
       <p>Hungry for some pie?</p>
     </div>

Figure 4-17 shows the result.

Top: Using background images in small boxes is surprisingly slick.Bottom: A particularly neat feature is the way the picture grows when you resize the page, thanks to tiling.
Figure 4-17. Top: Using background images in small boxes is surprisingly slick. Bottom: A particularly neat feature is the way the picture grows when you resize the page, thanks to tiling.

Graphical Bullets in a List

In Chapter 2, you learned how to use the <ul> element to create a bulleted list. However, you were limited to a small set of predefined bullet styles. If you look around the Web, you’ll see more interesting examples of bulleted lists, including some that use tiny pictures as custom bullets.

You can add custom bullets by hand using the <img> element, but there’s an easier option. You can use the list-style-image property to set a bullet image. Here’s an example that uses a picture named 3Dball.gif:

ul {
  list-style-image: url('3Dball.gif');
}

Once you create this style rule and put it in your style sheet, your browser automatically applies it to an ordinary bulleted list like this one:

<ul>
  <li>Are hard to miss</li>
  <li>Help compensate for feelings of inadequacy</li>
  <li>Look so darned cool</li>
  <li>Remind people of boring PowerPoint presentations</li>
</ul>

Figure 4-18 shows the result.

Graphical bullets range from simple arrows and checkboxes to extravagant three-dimensional spotted balls, like those shown here.
Figure 4-18. Graphical bullets range from simple arrows and checkboxes to extravagant three-dimensional spotted balls, like those shown here.

Finding Free Art

The Web is awash in graphics. In fact, finding a web page that isn’t chock-full of images is about as unusual as spotting Bill Gates in a dollar store. But how do you generate all the pictures you need for a graphically rich site? Do you really need to spend hours in a drawing program fine-tuning every picture you want? The answer depends on exactly what type of pictures you need, of course, but you’ll be happy to hear that the Web is a great resource for ready-to-use pictures.

It’s not hard to find pictures on the Web. You can, for example, use a handy Google tool to search for graphics on a specific subject (type http://images.google.com into your browser and search away). Unfortunately, finding an image usually isn’t good enough. To use it without worrying about a lawyer tracking you down, you also need the rights to use the picture. If you get lucky, a website owner might grant you permission to use a graphic after you send a quick email. But that’s the exception rather than the rule.

Fortunately, photo enthusiasts have set up community sites where they post their pictures for the world to see—and on some of these sites, you can search for and reuse anything you want, for free. One of the best was Stock.XCHNG (pronounced “stock exchange,” after stock photography, the name for the vast catalogs of reusable pictures that graphic designers collect). Recently, Getty Images purchased the Stock.XCHNG site and renamed it “Free Images.” Sadly, there aren’t many active contributors any more, but you can still access the same free catalog of pics at http://sxc.hu (Figure 4-19).

Stock.XCHNG offers a searchable catalog of well over 100,000 photos on every subject. Every day, eager photo enthusiasts upload their sometimes-striking work, including some of the images used in this book. In this figure, a search for “paris food” results in some interesting culinary treats.
Figure 4-19. Stock.XCHNG offers a searchable catalog of well over 100,000 photos on every subject. Every day, eager photo enthusiasts upload their sometimes-striking work, including some of the images used in this book. In this figure, a search for “paris food” results in some interesting culinary treats.

Another good place for digging up free photos is Flickr (www.flickr.com), though the site includes both images that are free to reuse and those that are not. The best way to find pictures you can use is with an advanced search at www.flickr.com/search/advanced. Enter your search keywords (as you would in a normal search), but check the “Only search within Creative Commons-licensed content” setting (Figure 4-20). That ensures that you find only files you can snatch.

Here you’ve limited your Flickr search to figures you can use on your own website. However, the figures may still have restrictions that prevent you from using them on commercial sites or from modifying them.
Figure 4-20. Here you’ve limited your Flickr search to figures you can use on your own website. However, the figures may still have restrictions that prevent you from using them on commercial sites or from modifying them.

Be aware, though, that content you use under a Creative Commons license may come with one or two restrictions. For example, it may stipulate that you can’t use the picture on a commercial website (at least not without getting permission from the picture owner). It may also restrict you from changing or editing the picture. When you find a picture you like, you can get the details by scrolling down to the License box (which you’ll find in the bottom-right corner of the page). Or you can explicitly search for pictures that don’t have these restrictions, using the additional settings shown in Figure 4-20.

If you can’t find the picture you want at Stock.XCHNG or Flickr, you may never find it—at least not without going to a commercial site, like iStockPhoto (www.istockphoto.com), Fotolia (www.fotolia.com), or Dreamstime (www.dreamstime.com), all of which charge a few dollars for royalty-free images. But if you’d like to look at some other no-pay alternatives, check out the article on finding free photographs at http://tinyurl.com/49yquv3.

Get Creating a Website: The Missing Manual, 4th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.