I would like to take an aleatory image and having it scale up / down to use the whole space of the parent div
, while maintaining its original proportions. I expect the image to be cropped (it's ok, as long it's centered both vertically and horizontally).
I've tried this code:
<div class="container" style="width: 800px">
<div class="row">
<div style="
height:340px;
width: 100%;
overflow: hidden;
border: 3px solid red;
">
<img src="http://via.placeholder.com/500x500" style="
object-position: center;
object-fit: cover;
">
</div>
</div>
</div>
Why isn't it scaling up, centering and cropping the image?
See this example,
Give the image some dimensions (compare to the second image, which has no defined dimensions)
When dealing with images of various sizes I always opt for setting the image URL in CSS rather than an IMG tag. The IMG tag is very limiting in terms of telling the browser how to render it in a container. In CSS you have far greater control.
So if you use background-image: url('{path/url}'); in your CSS then you can now use background-size: cover; or background-size: contain;
You can also control where the image is centered via
I find that cover really shines when responsiveness is a requirement of your site/app.