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

前端 未结 3 469
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-28 19:46

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:

3条回答
  •  孤独总比滥情好
    2020-12-28 20:02

    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.

提交回复
热议问题