Reputation: 14727
I have the following code:
<div class="image-container">
<img src="myimage.jpg">
</div>
img {
height: 400px;
}
The size of the image is 800px X 400px. On desktop, the image can be displayed in full. When I reduce the browser width and make the viewport smaller than 800px in width, the image's height is kept, but it's compressed horizontally, resulting in a distorted image. How can I add CSS to the image or its container to hide its overflow part so that I can see a clipped image without distortion? Hopefully the image is always centered in the container.
Upvotes: 0
Views: 3309
Reputation: 1
Being able to specify width: 100%
simplifies right-sizing in many situations.
Upvotes: 0
Reputation:
.image-container {
overflow:hidden;
height: 350px;
width: 450px;
display:block;
}
img {
height: 400px;
width: 800px;
}
<div class="image-container">
<img src="https://placekitten.com/g/800/400">
</div>
Try this code use overflow:hidden
on the container
Upvotes: 2
Reputation: 42374
If you want to simply cut some of the image off at smaller widths, you can set an overflow: hidden
on the parent, along with specifying both a height
and width
for the parent:
.image-container {
max-width: 300px;
max-height: 200px;
overflow: hidden;
}
.image-container > img {
width: 800px;
height: 400px;
}
<div class="image-container">
<img src="https://placekitten.com/g/800/400">
</div>
However, I'd suggest scaling the image (maintaining its aspect ratio) so that it can be entirely contained within the container / viewport. This can be achieved by setting a width
of 100%
on the image, and not specifying a height:
.image-container {
max-width: 300px;
}
.image-container > img {
width: 100%;
}
<div class="image-container">
<img src="https://placekitten.com/g/800/400">
</div>
Upvotes: 4