How can I fill a div with an image while keeping it proportional?

前端 未结 15 1363
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-28 00:56

I found this thread — How do you stretch an image to fill a

while keeping the image's aspect-ratio? — that is not entirely the thing that I want.

I h

相关标签:
15条回答
  • 2020-11-28 01:26

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

    .img-container {
      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)
  • 2020-11-28 01:26

    Consider using background-size: cover (IE9+) in conjunction with background-image. For IE8-, there is a polyfill.

    0 讨论(0)
  • Here is an answer with support to IE using object-fit so you won't lose ratio

    Using a simple JS snippet to detect if the object-fit is supported and then replace the img for a svg

    //ES6 version
    if ('objectFit' in document.documentElement.style === false) {
      document.addEventListener('DOMContentLoaded', () => {
        document.querySelectorAll('img[data-object-fit]').forEach(image => {
          (image.runtimeStyle || image.style).background = `url("${image.src}") no-repeat 50%/${image.currentStyle ? image.currentStyle['object-fit'] : image.getAttribute('data-object-fit')}`
          image.src = `data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='${image.width}' height='${image.height}'%3E%3C/svg%3E`
        })
      })
    }
    
    //ES5 version
    if ('objectFit' in document.documentElement.style === false) {
      document.addEventListener('DOMContentLoaded', function() {
        Array.prototype.forEach.call(document.querySelectorAll('img[data-object-fit]').forEach(function(image) {
          (image.runtimeStyle || image.style).background = "url(\"".concat(image.src, "\") no-repeat 50%/").concat(image.currentStyle ? image.currentStyle['object-fit'] : image.getAttribute('data-object-fit'));
          image.src = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='".concat(image.width, "' height='").concat(image.height, "'%3E%3C/svg%3E");
        }));
      });
    }
    img {
      display: inline-flex;
      width: 175px;
      height: 175px;
      margin-right: 10px;
      border: 1px solid red
    }
    
    
    /*for browsers which support object fit */
    
    [data-object-fit='cover'] {
      object-fit: cover
    }
    
    [data-object-fit='contain'] {
      object-fit: contain
    }
    <img data-object-fit='cover' src='//picsum.photos/1200/600' />
    <img data-object-fit='contain' src='//picsum.photos/1200/600' />
    <img src='//picsum.photos/1200/600' />


    Note: There are also a few object-fit polyfills out there that will make object-fit work.

    Here are a few examples:

    • object-fit-images
    • constancecchen /object-fit-pollyfill
    • Polyfill for CSS object-fit property
    0 讨论(0)
  • 2020-11-28 01:36

    If I correctly understand what you want, you may leave the width and height attributes off the image to maintain aspect ratio and use flexbox to do the centering for you.

    .fill {
        display: flex;
        justify-content: center;
        align-items: center;
        overflow: hidden
    }
    .fill img {
        flex-shrink: 0;
        min-width: 100%;
        min-height: 100%
    }
    <div class="fill">
        <img src="https://picsum.photos/id/237/320/240" alt="" />
    </div>

    JSFiddle here

    I tested this successfully in IE9, Chrome 31, and Opera 18. But no other browsers were tested. As always you must consider your particular support requirements.

    0 讨论(0)
  • 2020-11-28 01:36

    Here you have my working example. I have used a trick that is setting the image as background of the div container with background-size:cover and background-position:center center

    I have placed the image with width:100% and opacity:0 making it invisible. Note that I am showing my image only because I have an special interest on calling the child click event.

    Please note that altought I am ussing angular it is completely irrelevant.

    <div class="foto-item" ng-style="{'background-image':'url('+foto.path+')'}">
        <img class="materialboxed" ng-class="foto.picid" ng-src="{{foto.path}}" style="opacity: 0;filter: alpha(opacity=0);" width="100%" onclick="$('.materialboxed')/>
     </div>
    <style>
    .foto-item {
    height: 75% !important;
    width: 100%;
    position: absolute;
    top: 0;
    left: 0;
    overflow:hidden;
    background-size: cover;
    background-position: center center;
    }
    </style>
    

    The result is the one that you define as optimal in all cases

    0 讨论(0)
  • 2020-11-28 01:37

    An old question but deserves an update as now there is a way.

    The correct CSS based answer is to use object-fit: cover, which works like background-size: cover. Positioning would be taken care of by object-position attribute, which defaults to centering.

    But there is no support for it in any IE / Edge browsers, or Android < 4.4.4. Also, object-position is not supported by Safari, iOS or OSX. Polyfills do exist, object-fit-images seems to give best support.

    For more details on how the property works, see CSS Tricks article on object-fit for explanation and demo.

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