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

后端 未结 4 756
清酒与你
清酒与你 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:38

    Have you tried :

    img {
        width: 100%;
    }
    
    0 讨论(0)
  • 2021-01-03 06:41

    Try:

    img {
      max-width: 100%; 
      max-height: 100%;
    }
    figure {
      height: 100%;
      width: 100%;
      margin: 0;
    }
    

    figure is the parent element, so you need to set it's height/width as well. Also, the default styling on figure includes a margin, so you need to remove that to keep the image inside of the parent div. Also, you may need to make the max-height smaller to account for the caption if you want to keep that inside of the parent div.

    You can also use width and height instead of max-* if you want the image to always fill the parent regardless of its native size.

    0 讨论(0)
  • 2021-01-03 06:45

    make image background-image: url(..img);

    and apply background-size: cover; on the same div.

    The key here is cover property value as it tells browser to resize image while keeping aspect ratio to fit all sides.

    @Sphinxxx suggested to use background-size: contain; which solved OP problem;`

    0 讨论(0)
  • 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
    0 讨论(0)
提交回复
热议问题