What is background-size contain in CSS: Explanation and Example
background-size: contain scales the background image to fit entirely inside the element without cropping. It keeps the image's aspect ratio and ensures the whole image is visible, even if it leaves empty space around it.How It Works
Imagine you have a picture that you want to fit inside a frame. Using background-size: contain is like resizing the picture so it fits completely inside the frame without cutting any part off. The picture keeps its original shape and proportions, so it doesn't look stretched or squished.
If the frame is wider or taller than the picture, you might see some empty space around the picture inside the frame. This empty space is normal because the picture is scaled to fit fully inside, not to fill the entire frame.
Example
This example shows a square box with a background image. The image is scaled using background-size: contain so it fits fully inside the box without cropping or stretching.
html, body {
height: 100%;
margin: 0;
display: flex;
justify-content: center;
align-items: center;
background: #f0f0f0;
}
.box {
width: 300px;
height: 200px;
border: 2px solid #333;
background-image: url('https://via.placeholder.com/400x300.png?text=Sample+Image');
background-repeat: no-repeat;
background-position: center;
background-size: contain;
}
When to Use
Use background-size: contain when you want the entire background image to be visible inside an element without any part being cut off. This is useful for logos, icons, or decorative images where seeing the full image is important.
It works well when the element size might change, like on different screen sizes, because the image will always scale to fit inside without distortion. However, it may leave empty space if the element's shape doesn't match the image's shape.
Key Points
- Preserves aspect ratio: The image keeps its original shape.
- Fits inside element: The whole image is visible without cropping.
- May leave empty space: If element and image shapes differ, space appears around the image.
- Good for logos and icons: Ensures full visibility of important images.