How to cover a div with an img tag (like background-image does)?

If you want to recreate the background-size: cover; look without using a CSS background image, you can use the following to achieve the desired result. Keep in mind, however, that there will always need to be a container holding the image.

div {
    position: relative;
    overflow: hidden;
}
img {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    min-width: 100%;
    min-height: 100%;
    height: auto;
    width: auto;
}

Depending on your additional CSS, you might want to use max-width and max-height.


Try this:

div {
    position:relative;
}
img {
    max-height: 100%;
    max-width: 100%;
    margin: auto;
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
}

This assumes you have given a size to the div.


Use object-fit:cover to not lose ratio.

div {
  border: black solid;
  width: 400px;
  height: 400px;
}

img {
  width: 100%;
  height: 100%;
  object-fit: cover
}
<div>
  <img src="//lorempixel.com/100/100" />
</div>

NOTE: this is not supported in IE


P.S. - For those who like to downvote (and are downvoting) just for the simple reason that "It doesn't work in IE" (by the way, it is an outdated browser, so please educate your clients to use at least the upgraded browser EDGE), there are a few object-fit polyfills out there that will make object-fit work.

Here are a few examples:

  • object-fit-images
  • constancecchen /object-fit-pollyfill
  • Polyfill for CSS object-fit property

Or if you think its an overkill using a polyfill just for that property, here is simple snippet that will make this work in IE.

You can use a simple JS snippet to detect if the object-fit is supported and then replace the img for a svg

//for browsers which doesn't support object-fit (you can use babel to transpile to ES5)

if ('objectFit' in document.documentElement.style === false) {
    document.addEventListener('DOMContentLoaded', () => {
        document.querySelectorAll('img[data-object-fit]').forEach(image => {
            (image.runtimeStyle || image.style).background = `url("${image.src}") no-repeat 50%/${image.currentStyle ? image.currentStyle['object-fit'] : image.getAttribute('data-object-fit')}`
            image.src = `data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='${image.width}' height='${image.height}'%3E%3C/svg%3E`
        })
    })
}
img {
  display: inline-flex;
  width: 175px;
  height: 175px;
  margin-right: 10px;
  border: 1px solid red
}

/*for browsers which support object fit */

[data-object-fit='cover'] {
  object-fit: cover
}

[data-object-fit='contain'] {
  object-fit: contain
}
<img data-object-fit='cover' src='//picsum.photos/1200/600' />
<img data-object-fit='contain' src='//picsum.photos/1200/600' />
<img src='//picsum.photos/1200/600' />

Tags:

Html

Css

Image