How to Fill a div with an img Without Using a Background
To fill a block with an image without using background-image, combine object-fit with width and height set to 100%. This fits the image to the block without using a background.
Example code:
Available values:
Back to blog
Example code:
<div class="wrapper">
<img src="/path/to/your/image.jpg" alt="Изображение" class="image">
</div>
Styles:
.wrapper {
width: 300px;
height: 300px;
border: 5px solid #515151;
}
.image {
object-fit: cover; /* Или contain, в зависимости от желаемого эффекта */
width: 100%;
height: 100%;
}
Here, object-fit: cover scales the image to fill the entire block without leaving empty space, while preserving its aspect ratio. If you want the image to retain its proportions and extend beyond the block, use object-fit: contain.
Available values:
- fill — the default value. The image fills the specified dimensions without preserving its aspect ratio, often causing noticeable distortion.
- contain — scales the image to fit entirely within the specified dimensions while preserving its aspect ratio.
- cover — fills all the available space while preserving the image's aspect ratio, cropping any excess.
- none — displays the image without changing its aspect ratio or size.
- scale-down — the browser compares the image sizes produced by none and contain, then selects one of them and sizes the image accordingly.