Reputation: 3610
Here is a fiddle I made:
I have searched for answers but all of them only applies to an image which has less height than the container. My problem is vertically aligning an image which has larger height than the container, which has variable height, using only CSS (if this is possible only with css).
Thanks for your help.
<div class="img-container">
<img src="http://www.placehold.it/600x500" alt="">
</div>
CSS:
.img-container {
height: 300px;
overflow: hidden;
}
img {
width: 100%;
}
Upvotes: 0
Views: 43
Reputation: 1
Try this will help you resolve your issue
HTML:
<div class="img-container">
<img src="" alt="">
</div>
CSS:
.img-container {
height: 300px;
overflow: hidden;
position: relative;
}
.img-container > img {
width: 100%;
position: absolute;
left: 50%;
top: 50%;
transform: translateX(-50%) translateY(-50%);
}
See Demo on jsfiddle: https://jsfiddle.net/amsarvaiya/rp1fu3kn/
See Demo Full Screen: https://jsfiddle.net/amsarvaiya/rp1fu3kn/embedded/result/
Upvotes: 0
Reputation: 7122
I hope it will helps you.
.img-container {
height: 300px;
overflow: hidden;
position: relative;
}
img {
position: absolute;
top: 50%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
width:100%;
}
<div class="img-container">
<img src="http://www.placehold.it/600x500" alt="">
</div>
Upvotes: 1
Reputation: 663
I think the problem is the width property set on the image. Usually using width the image tries to occupy any available space given to it. So try using max-width 100% and then the exact maximum width of the image will be placed in the container.
Upvotes: 0