ptg16476052
220 LESSON 9: Using Images on Your Web Pages
The second reason to specify the dimensions of an image is to let the browser know
ahead of time how large it is going to be. You should do this even if you aren’t going
to resize the image, because it enables the browser to establish the page layout before
it downloads the images that will be displayed. This will help your pages display more
quickly because the browser can lay out the page correctly before the images are fully
downloaded. You can set the height and width of the image using the height and width
attributes, the height and width style properties, or by specifying the height and width of
the parent element.
Image Backgrounds
With CSS, you can specify a background image for any element and control exactly how
it appears and is positioned.
To add a background image to an element, use the background-image style property. In
the example below, I added a background image to a <div>, and added a few other style
properties to illustrate how the background works. You can see how the example code
appears in a browser in Figure 9.14.
<div style="background-image: url('black_rook.png');
height: 240px; width: 240px; border: 1px solid black;
background-color: #9 99;">
An element with a background.
</div>
As you can see from the example, background images are tiled both horizontally and
vertically. I added a grey background to the <div> but you can’t see it at all because the
background image is tiled to cover the entire background. I also added a border to show
the exact size of the <div>.
Finding the best image size is a challenge for all web designers.
You don’t want images that are too large, making them slow to
download on smartphones and tablets, but you don’t want tiny
images that look terrible on 5K displays. A good rule of thumb is
to create your feature images as large or slightly larger than your
page will handle. Then use CSS and responsive web design to
resize it down for smaller devices. For nonfeature images, you can
start with smaller initial images. You should never use CSS or the
browser to make an image appear larger than it is. This will never
look good. Instead, if you need a larger version of the image, go
back and get a larger original.
CAUTION