Force an image to fit and keep aspect ratio

前端 未结 2 670
天涯浪人
天涯浪人 2020-11-30 03:58

I want an image to fill the 100% of its container\'s width, and I want it to have a max-heigth property set to it, all this keeping the aspect ratio but allowing to lose any

相关标签:
2条回答
  • 2020-11-30 04:49

    You can try CSS3 object-fit, and see browser support tables.

    CSS3 object-fit/object-position Method of specifying how an object (image or video) should fit inside its box. object-fit options include "contain" (fit according to aspect ratio), "fill" (stretches object to fill) and "cover" (overflows box but maintains ratio), where object-position allows the object to be repositioned like background-image does.

    JSFIDDLE DEMO

    .container {
      width: 200px; /*any size*/
      height: 200px; /*any size*/
    }
    
    .object-fit-cover {
      width: 100%;
      height: 100%;
      object-fit: cover; /*magic*/
    }
    <div class="container">
      <img class="object-fit-cover" src="https://i.stack.imgur.com/UJ3pb.jpg">
    </div>


    Related Info:

    • Exploring object-fit ★ Mozilla Hacks

    • Polyfill for CSS object-fit property

    0 讨论(0)
  • 2020-11-30 04:58

    You can achieve this using css flex properties. Please see the code below

    .img-container {
      width: 150px;
      height: 150px;
      border: 2px solid red;
      justify-content: center;
      display: flex;
      flex-direction: row;
      overflow: hidden;
      
    }
    .img-container .img-to-fit {
      flex: 1;
      height: 100%;
    }
    <div class="img-container">
      <img class="img-to-fit" src="https://images.pexels.com/photos/8633/nature-tree-green-pine.jpg" />
    </div>

    0 讨论(0)
提交回复
热议问题