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

Viewed 33488

As discussed here I am trying to get an image to be covered within a div. With just these simple lines I was able to achieve this via background-image:

div{
    width: 172px;
    height: 172px;
    border-style: solid;
    background-image: url('../images/img1.jpg');
    background-size: cover;
    background-repeat: no-repeat;
    background-position: center;
}

In result the image was centered within the div and was resized so it would fit the width or the height of the div (depending if the image was wide or not). Now I would like to achieve the same result with the image tag within the div.

<div>
  <img src="images/img1.jpg"/>
</div>

Is there any way to get through this with plain CSS?

3 Answers

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.

Related