CSS3 Background Size: Contain & Cover

Two other possible values for background-size are contain and cover. The contain keyword scales the background image to be as large as possible (but both width and height must fit inside the content area). As such, depending on the proportions of the background image and the background positioning area, there may be some areas of the background which are not covered by the background image.

The cover keyword scales the background image so that the content area is completely covered by the background image (both width and height are equal to or exceed the content area). As such, some parts of the background image may not be visible in the background positioning area.

The following example illustrates the use of contain and cover:

HTML file: Displayed by browser:
<style>
.div1 {
    border: 1px solid black;
    height:200px;
    width:300px;
    background: url(../html_beg/images/flower.gif);
    background-repeat: no-repeat;
}
.div2 {
    border: 1px solid black;
    height:225px;
    width:300px;
    background: url(../html_beg/images/flower.gif);
    background-size: contain;
    background-repeat: no-repeat;
}
.div3 {
    border: 1px solid black;
    height:200px;
    width:275px;
    background: url(../html_beg/images/flower.gif);
    background-size: cover
    background-repeat: no-repeat;
}
</style>
<body>
<div class="div1">
<h3>Original image:</h3>
<p>No background-image size has been specified at all in this example.</p>
</div>
<br />
<div class="div2">
<h3>Using the "Contain" Keyword:</h3>
<br /><br /><br />
<p>Background-image must be fully contained inside content box. There could be some white space or margins, as a result, depending on the size of the element.</p>
</div>
<br />
<div class="div3">
<div><span style="font-size: 18px; font-weight: bold;">Using the "Cover" Keyword:</span>
<br />Background-image must cover the content box by scaling the image to size but one side of the image might spill out of the content box.</div>
</div>
</body>

Original Image:

No background-image size has been specified at all in this example.


Using the "Contain" Keyword:




Background-image must be fully contained inside content box. There could be some white space or margins, as a result, depending on the size of the element.


Using the "Cover" Keyword:
Background-image must cover the content box by scaling the image to size but one side of the image might spill out of the content box.

Back button Table of Contents Next button