HTML and CSS Reference
In-Depth Information
Setting the Size of Background Images
When adding a background image to an element, it's important to realize that the background is simply that.
The element won't increase in size to accommodate that great image you've chosen. If you want the image to
be displayed in full, you need to make sure the element is wide and tall enough. At least, that's the case in older
browsers. CSS3 gives you more flexibility with the background-size property, which is supported by all browsers
in widespread use except IE 8 and earlier.
he background-size property accepts the following values:
contain Scale the image to the largest possible size so that both its width and height fit
into the background positioning area.
cover Scale the image to its smallest size so that both its width and height can
completely cover the background positioning area.
One or two lengths or percentages.
When using lengths or percentages, the first value sets the width of the background
image, and the second sets its height. If only one value is given, the height is treated
as auto . Percentages are relative to the background positioning area as determined by
background-origin . he contain , cover , and auto keywords all preserve the image's
aspect ratio.
The difference between contain and cover is best shown through actual examples. Figure 8-23 shows two
300px square <div> elements, both with the same background image (the code is in size_keywords.html). The
image is 500px × 667px . he <div> on the left sets background-size to contain , the one on the right sets it to cover .
Figure 8-23. The same background image is resized differently without losing its aspect ratio
Using contain results in the whole image being used, but it doesn't necessarily fill the entire background. On
the other hand, using cover fills the background, but doesn't necessarily use the whole image. If you look at the
coastline in both images, they're the same, but the lower section of the image on the right is cut of.
The actual result depends on the comparative dimensions of the background image and element. What's
more, background-size can be combined with all the other background properties to produce different effects.
For example, setting background-position to center shifts the yachts into the upper third of the <div> on the
right in Figure 8-23 .
 
Search WWH ::




Custom Search