I am having trouble finding a solid answer for this question. It may have been asked before but I cant find a working solution anywhere.
What I want is to make my image full width 100%, keep aspect ratio and center the image vertically with overflow hidden.
This is what I have:
HTML:
<div class="img-container">
<img src="myimgurl.jpg">
</div>
CSS:
.img-container {
width: 100%;
height: 200px;
max-height: 240px;
overflow: hidden;
margin: 0;
position: relative;
}
.img-container img {
position:absolute;
vertical-align: middle;
max-width: 100%;
}
If you really have to use an <img>
:
HTML:
<div class="img-container">
<img src="myimgurl.jpg">
</div>
CSS:
.img-container {
width: 100%;
height: 200px;
max-height: 240px;
overflow: hidden;
margin: 0;
position: relative;
}
.img-container img {
position:absolute;
top: 50%;
transform: translateY(-50%);
max-width: 100%;
}
This use of transform; translateY() is a convenient way to center vertically items.
Live demo (thanks to @dsfq) : http://jsfiddle.net/rrLyopxe/
Bonus : When should you use an img element ? When can you simply put a background ?
If the image you use as an editorial/informational content, this should be an <img>
element, so you can provide an alt attribute and a title to add information about it.
If the image is only here for graphical purposes (background, decoration, etc.) this is a case to use background-image property.
Do you have to use an <img>
?
<div class="img-container"></div>
<style>
.img-container{
background-image: url('myimg.png');
background-size: cover;
background-position: center;
/* Don't forget to add height and width,
Without content, the div won't have any height and with */
height: 10em; width 10em;
}
</style>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With