I found a simple solution to emulate both cover and contain, which is pure CSS, and works for containers with dynamic dimensions, and also doesn't make any restriction on the image ratio.
Note that if you don't need to support IE, or Edge before 16, then you better use object-fit.
.img-container {_x000D_
position: relative;_x000D_
overflow: hidden;_x000D_
}_x000D_
_x000D_
.background-image {_x000D_
position: absolute;_x000D_
min-width: 1000%;_x000D_
min-height: 1000%;_x000D_
left: 50%;_x000D_
top: 50%;_x000D_
transform: translateX(-50%) translateY(-50%) scale(0.1);_x000D_
z-index: -1;_x000D_
}
_x000D_
<div class="img-container">_x000D_
<img class="background-image" src="https://picsum.photos/1024/768/?random">_x000D_
<p style="padding: 20px; color: white; text-shadow: 0 0 10px black">_x000D_
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum._x000D_
</p>_x000D_
</div>
_x000D_
The 1000% is used here in case the image natural size is bigger than the size it is being displayed. For example, if the image is 500x500, but the container is only 200x200. With this solution, the image will be resized to 2000x2000 (due to min-width/min-height), then scaled down to 200x200 (due to transform: scale(0.1)
).
The x10 factor can be replaced by x100 or x1000, but it is usually not ideal to have a 2000x2000 image being rendered on a 20x20 div. :)
Following the same principle, you can also use it to emulate background-size: contain
:
.img-container {_x000D_
position: relative;_x000D_
overflow: hidden;_x000D_
z-index: 0;_x000D_
}_x000D_
_x000D_
.background-image {_x000D_
position: absolute;_x000D_
max-width: 10%;_x000D_
max-height: 10%;_x000D_
left: 50%;_x000D_
top: 50%;_x000D_
transform: translateX(-50%) translateY(-50%) scale(10);_x000D_
z-index: -1;_x000D_
}
_x000D_
<div style="background-color: black">_x000D_
<div class="img-container">_x000D_
<img class="background-image" src="https://picsum.photos/1024/768/?random">_x000D_
<p style="padding: 20px; color: white; text-shadow: 0 0 10px black">_x000D_
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum._x000D_
</p>_x000D_
</div>_x000D_
</div>
_x000D_