{"id":196150,"date":"2015-02-17T14:58:38","date_gmt":"2015-02-17T21:58:38","guid":{"rendered":"http:\/\/css-tricks.com\/?page_id=196150"},"modified":"2021-05-20T10:39:00","modified_gmt":"2021-05-20T17:39:00","slug":"background-size","status":"publish","type":"page","link":"https:\/\/css-tricks.com\/almanac\/properties\/b\/background-size\/","title":{"rendered":"background-size"},"content":{"rendered":"\n

The background-size<\/code> property in CSS is one of the most useful \u2014 and most complex \u2014 of the background properties. There are many variations and different syntaxes you can use for this property, all of which have different use cases. Here\u2019s a basic example:<\/p>\n\n\n\n

html {\n  background: url(greatimage.jpg);\n  background-size: 300px 100px;\n}<\/code><\/pre>\n\n\n\n

That’s an example of the two-value syntax for background size. There are four different syntaxes you can use with this property: the keyword syntax, the one-value syntax, the two-value syntax, and the multiple background syntax.<\/p>\n\n\n

Keywords<\/h3>\n\n\n

In addition to the default value (auto<\/code>), there are two keywords you can use with background-size<\/code>: cover<\/code> and contain<\/code><\/p>\n\n\n\n

\"\"
The difference<\/figcaption><\/figure>\n\n\n\n

cover<\/code> tells the browser to make sure the image always<\/em> covers the entire container, even if it has to stretch the image or cut a little bit off one of the edges. contain<\/code>, on the other hand, says to always<\/em> show the whole image, even if that leaves a little space to the sides or bottom.<\/p>\n\n\n\n

The default keyword \u2014 auto<\/code> \u2014 tells the browser to automatically calculate the size based on the actual size of the image and the aspect ratio.<\/p>\n\n\n

One value<\/h3>\n\n\n

If you only provide one value (e.g. background-size: 400px<\/code>) it counts for the width, and the height is set to auto<\/code>. You can use any CSS size units<\/a> you like, including pixels, percentages, ems, viewport units, etc.<\/p>\n\n\n

Two values<\/h3>\n\n\n

If you provide two values, the first sets the background image’s width and the second sets the height. Like the single value syntax, you can use whatever measurement units you like.<\/p>\n\n\n

Multiple images<\/h3>\n\n\n

You can also combine<\/em> any of the above methods and apply them to multiple images, simply by adding commas between each syntax. Example:<\/p>\n\n\n\n

html {\n  background: url(greatimage.jpg), url(wonderfulimage.jpg);\n  background-size: 300px 100px, cover;\n  \/* first image is 300x100, second image covers the whole area *\/\n}<\/code><\/pre>\n\n\n\n

Keep background image stacking order<\/a> in mind when using multiple images.<\/p>\n\n\n

Demo<\/h3>\n\n\n

This demo shows examples of cover<\/code>, contain<\/code>, and multiple background images with a mix of pixel and keyword values.<\/p>\n\n\n\n