Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS image to full width and center vertically?

Tags:

html

css

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%;
}
like image 438
BGecko Avatar asked Dec 02 '22 15:12

BGecko


2 Answers

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.

like image 98
enguerranws Avatar answered Dec 21 '22 03:12

enguerranws


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>
like image 40
I wrestled a bear once. Avatar answered Dec 21 '22 03:12

I wrestled a bear once.