Make image scale with parent container when screen is re-sized

后端 未结 4 776
清酒与你
清酒与你 2021-01-03 06:23

In my liquid layout, my div elements have the property position-fixed. This means that as I re-size the browser, all the elements remain in the sam

4条回答
  •  情话喂你
    2021-01-03 06:47

    Try this:

    img {
        height: 100%;
        width: 100%;
        object-fit: contain;
    }
    

    object-fit is a pretty cool CSS3 property.

    Used with the contain value the image will increase or decrease in size within its container while maintaining its aspect-ratio.

    Here's how CSS-Tricks describes it:

    The object-fit property defines how an element responds to the height and width of its content box. It's intended for images, videos and other embeddable media formats in conjunction with the object-position property. Used by itself, object-fit lets us crop an inline image by giving us fine-grained control over how it squishes and stretches inside its box.

    Because browser support for this property is still somewhat weak, here's a polyfill that covers all major browsers including IE9: Polyfill for CSS object-fit property

    For a deeper look here are a few references:

    • W3C CSS Image Values and Replaced Content Module Level 3
    • MDN object-fit
    • CSS-Tricks `object-fit

提交回复
热议问题