I want to show images on my website with the following logic:
- If the image fits within the maximum size of the container (240 pixels tall, 100% width), just show it as-is
- Otherwise show it using the
object-fit: cover
style
So for huge images, they would be constrained to 240 pixels tall, and the full width of the container. But small images wouldn't be blown up, they would show with their actual size. A 50x50 pixels image would show as 50x50 pixels.
I hope all that makes sense so far.
So the basic idea would be this:
<style>
.image img {
width: 100%;
max-height: 240px;
object-fit: cover;
}
</style>
<div class="image">
<img src="https://via.placeholder.com/150">
</div>
<div class="image">
<img src="https://via.placeholder.com/500">
</div>
The problem with this approach is that while large images are indeed constrained to be 240 pixels tall, small images are now stretched and also 240 pixels tall:
I have a demo here, where you can play with the code: https://svelte.dev/repl/1edc77418be748269860fb3dfb866b20?version=3.53.1.
The problem is that I am showing remote images (the img src could be anything), so I don't know the size beforehand. If I knew the size I could apply the classes/styles conditionally but that's not going to be possible unless I add more JS into the mix (which I might end up doing unless there is a CSS-only way).