Web Graphics Usage

Graphics on the web are used in two general ways.

Example:

Here is a screenshot from Simply Recipes. There are quite a few graphics here.

alt
Screenshot of Simply Recipes

The photographs, illustrations, and artwork are outlined in blue:

alt

Images used to create structure and variety in the site outlined in red:

alt

Where should I define my images?

When possible, we follow these rules for using graphics:

HTML img Tag

We define images in HTML using the <img> tag.

The <img> has two required attributes

src
This tells the browser where to look for the image file. It works just like the href attribute you've already used.
alt
This is the "alternate text". This is the text that will display if your image is missing or the browser doesn't show images. It should describe the image.

The <img> tag is a self-closing tag. That means you put a slash at the end of it in XHTML.

Example:

<img src="images/molly.jpg" alt="A photograph of a Corgi puppy named Molly" />

CSS Background Images

In CSS we can set an image to be in the background.

This will display behind the normal text and other images in our HTML.

We can use this image to make a nice textured background.

alt

Here's the CSS code to use the image. I'm using a div with the id of "demo" for this example.
#demo {
  background-image: url(i/texture.jpg);
}

Note: The URL of the image is relative to the CSS file, not the HTML.

See Example

The default setting for background images is for them to repeat both vertically and horizontally. We can change that with background-repeat.

#demo {
  background-image: url(i/texture.jpg);
  background-repeat: no-repeat;
}

You can choose four settings for background-repeat:

See Example

You can also change the color of the background in addition to your image. In CSS, the specified background color will display under the background image.

#demo {
  background-image: url(i/texture.jpg);
  background-repeat: no-repeat;
  background-color: #C6AB6D; /* Brownish */
}

See Example

Lastly, you can change the position of your background image.

You can use keywords, units of measurement, or percentages.

alt

#demo {
  background-image: url(i/texture.jpg);
  background-color: #C6AB6D;

  background-position: 50px 100px;
}

See Example

CSS Background Shorthand Property

You can define all of the above properties by simply using the shorthand background property.

#demo {
  background: #C6AB6D url(i/texture.jpg) repeat-x 50px 100px;
}

background-size Property

The background-size property allows you to control the displayed sized of the graphic.

While you can use all the normal and numeric measurements for this property, the most notable values are the keywords cover and contain. These are used for full screen graphics.

#demo {
  background: gray url(i/molly.jpg) no-repeat center center;
  background-size: cover
}

See Example


Additional Reading