HTML and CSS Reference
In-Depth Information
The
cover
keyword tells browsers to scale the image in order to cover all of the back-
ground while still retaining the proportions of the image, even if that means cropping
the image. The
contain
keyword, on the other hand, tells browsers to scale the image
so that all of the image is completely contained within the element, even if that means
that not all of the element is covered by the image. Figure 4-7 provides examples of a
background image scaled to a specifi c size, and scaled using the
cover
and
contain
keywords.
Figure 4-7
background-size property
background-size: 300px 200px;
background-size: cover;
background-size: contain;
200px;
300px;
the image is displayed at a
specific size
the image is scaled until it
covers the entire element, but
part of the image is cropped
the image is scaled so that the
entire image is contained
within the element, but part of
the element remains uncovered
Vaclav Volrab/Shutterstock.com
Thus, to create a background image that is half the width and height of the containing
element, centered vertically and horizontally, and not tiled, you could apply the follow-
ing styles:
If you include only
one value in the
background-size
property, the browser
uses it to set the image
width and sets the height
proportionally.
background-position: center center;
background-repeat: no-repeat;
background-size: 50% 50%;
In the box model discussed earlier, every element contains a content box, a padding
box, and a border box. You can defi ne the extent of a background image or color using
the style
background-clip:
box
;
where
box
is
content-box
,
padding-box
, or
border-box
(the default). As shown in
Figure 4-8, the keyword you choose controls whether the background image or color is
clipped at the edge of the content or the edge of the padding, or runs all the way to the
edge of the element border.