Fill a div with an image respecting aspect ratio

后端 未结 4 1832
悲哀的现实
悲哀的现实 2020-12-04 03:51

Is it possible to fill a div with an image such that at least one image dimension is 100% and the other dimension is either wider or equal size as the div, whilst r

4条回答
  •  没有蜡笔的小新
    2020-12-04 03:56

    Consider using the CSS object-fit property.

    5.5. Sizing Objects: the object-fit property

    The object-fit property specifies how the contents of a replaced element should be fitted to the box established by its used height and width.

    Here are two of the values:

    • cover

      The replaced content is sized to maintain its aspect ratio while filling the element's entire content box.

    • contain

      The replaced content is sized to maintain its aspect ratio while fitting within the element's content box.

    So, with cover the image retains its aspect ratio and covers all available space. Of course, this means that much of an image may be cropped off-screen.

    With contain the aspect ratio is also maintained, but the image scales to fit within the box. This means that an image may have whitespace on the left and right, or top and bottom.


    Browser Compatibility

    As of this writing, object-fit is not supported by Internet Explorer. For a workaround see:

    • Neat trick for CSS object-fit fallback on Edge (and other browsers)
    • fitie - An object-fit polyfill for Internet Explorer
    • object-fit-images - Adds support for object-fit on IE9, IE10, IE11, Edge and other old browsers
    • Polyfill (mostly IE) for CSS object-fit property to fill-in/fit-in images into containers.

    More information

    • MDN object-fit property
    • CSS-Tricks object-fit property
    • object-fit browser support @ caniuse.com

提交回复
热议问题