Cover vs Contain in CSS: Key Differences and Usage
cover scales the background image to fully cover the container, possibly cropping parts of the image, while contain scales the image to fit entirely inside the container without cropping, possibly leaving empty space. Both keep the image's aspect ratio but differ in how they fill the container.Quick Comparison
Here is a quick side-by-side comparison of cover and contain in CSS background sizing.
| Factor | cover | contain |
|---|---|---|
| Image scaling | Scales to cover entire container | Scales to fit inside container |
| Aspect ratio | Preserved | Preserved |
| Image cropping | Possible cropping of image edges | No cropping, whole image visible |
| Empty space in container | No empty space, container fully covered | May have empty space around image |
| Use case | Fill container fully with image | Show full image without cropping |
Key Differences
The cover value makes the background image scale so it completely fills the container. This means the image might be zoomed in and some parts on the edges can be cut off. It ensures no empty space is visible, which is great for backgrounds that must fill the entire area.
On the other hand, contain scales the image so the entire image fits inside the container. It never crops the image but may leave empty space if the container's shape does not match the image's aspect ratio. This is useful when you want to show the whole image clearly without cutting anything.
Both keep the image's original proportions, so the image won't look stretched or squished. The main difference is whether you want to fill the container fully (cover) or show the entire image inside it (contain).
Cover Example
This example uses background-size: cover; to fill the container fully with the image, cropping edges if needed.
body {
margin: 0;
height: 100vh;
background-image: url('https://via.placeholder.com/600x400');
background-repeat: no-repeat;
background-position: center;
background-size: cover;
}Contain Equivalent
This example uses background-size: contain; to show the entire image inside the container without cropping, possibly leaving empty space.
body {
margin: 0;
height: 100vh;
background-image: url('https://via.placeholder.com/600x400');
background-repeat: no-repeat;
background-position: center;
background-size: contain;
background-color: #ddd;
}When to Use Which
Choose cover when you want the background image to fill the entire container area, such as for hero sections or full-screen backgrounds, and cropping edges is acceptable.
Choose contain when you need to display the entire image without cropping, like logos or product images, even if that means showing empty space around it.
Key Takeaways
cover fills the container fully but may crop image edges.contain shows the whole image without cropping but may leave empty space.cover for full backgrounds and contain for full image visibility.