Skip to main content

The CSS background-size Property

Background images need not appear at their natural dimensions, because background-size can change them.

It accepts a length, a percentage, or one of three keywords: auto, contain and cover.

Background size with pixels

Pixel values shrink the background image here until it is far smaller than the source file.

Prompt
Create a page with a div that has a background image set to a small size using pixels (100px by 80px). Position the image at the right top with no repeat. Include some Lorem Ipsum text inside the div.
Output: complete HTML page

Background size with contain, cover and auto

auto is what you get without setting anything: the image keeps its original dimensions.

contain resizes the image, up or down, so that it fits within the content area.

cover makes the image big enough to leave no part of the content area uncovered.

Prompt
Create a page with three divs showing different background-size keyword values: contain, cover, and auto. Each div should have the same flower background image with no-repeat and a visible border, so the difference between the three values is clear.
Output: complete HTML page

Define Sizes of Multiple Background Images

When an element has several backgrounds, give background-size a comma-separated list of values.

Example

Each of the three background images here gets its own background-size value.

Prompt
Create a page with a div that has three background images. Use different background-size values for each: contain for the first, 150px for the second, and auto for the third. Set appropriate positions and repeat values for each image.
Output: complete HTML page

CSS Full Size Background Image

Styling the <html> element is how you make a background image fill the browser window at all times. The goal is a centered image that scales when it must, fills the page without any white space, and never triggers scrollbars.

Example

On the <html> element, center and fix the background, then let background-size: cover stretch it across the window.

Prompt
Create a page where the html element has a full-size background image that covers the entire browser window. The image should be centered, fixed, not repeat, and use background-size: cover. Include a heading on the page.
Output: complete HTML page

CSS Hero Image

A hero image is a large picture with text on top of it, and a <div> with a few background properties is enough to build one.

Example

Prompt
Create a page with a hero image section using a div with a background image. The hero should use background-size: cover, be 500px tall, and have centered text overlay with a heading and paragraph.
Output: complete HTML page