Overview
This lecture explains the CSS background-size property, which controls how background images are sized within an element and details its usage, values, behavior, and examples.
What is background-size?
- The
background-size property sets the size of an element's background image.
- Background images can remain at their natural size, be stretched, or scaled to fit the available space.
- Areas not covered by the image are filled with the background color.
Syntax and Values
- Common keywords:
cover (fills container, may crop) and contain (fits image fully inside, no cropping).
- Accepts one value (width; height is auto) or two values (width and height).
- Values can be length (e.g., px, em), percentage, or
auto.
- For multiple backgrounds, values are comma-separated.
- Supports global values: inherit, initial, revert, revert-layer, unset.
Value Details
contain: Image scaled as large as possible without cropping or stretching.
cover: Image scaled to cover the container, may crop if proportions differ.
auto: Maintains intrinsic image proportions in the given direction.
<length>: Image dimension set to specified length; negative values not allowed.
<percentage>: Dimension is a percent of the background positioning area; no negatives.
Behavior with Intrinsic Dimensions and Proportions
- Bitmap images always have intrinsic dimensions and proportions.
- SVG and gradients may lack intrinsic size; behavior falls back to container or
contain.
- If both dimensions are given (not
auto), the image is that size.
- If one value is
auto, the other value or the image's proportion determines the size.
Usage Example
- To tile a large image in a small box, set
background-size to a fixed value (e.g., 150px) with suitable element dimensions.
- Example:
.tiledBackground { background-image: url(...); background-size: 150px; width: 300px; height: 300px; }
Additional Info and Compatibility
- Applies to all elements including
::first-letter and ::first-line.
- Percentages are relative to the background positioning area.
- Well supported in browsers since July 2015.
Key Terms & Definitions
- background-size — CSS property to define background image size.
- contain — Scales image to fit container without cropping or stretching.
- cover — Scales image to fill container, possibly cropping the image.
- background positioning area — The area (usually the padding box) over which the background image is positioned and sized.
Action Items / Next Steps
- Practice using
background-size with various values in code.
- Test
background-size behavior with images lacking intrinsic dimensions.
- Review examples of resizing background images for more details.