Scale image to fit a bounding box

前端 未结 13 2088
轻奢々
轻奢々 2020-11-27 10:17

Is there a css-only solution to scale an image into a bounding box (keeping aspect-ratio)? This works if the image is bigger than the container:

img {
  max-         


        
13条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-27 11:01

    Here's a hackish solution I discovered:

    #image {
        max-width: 10%;
        max-height: 10%;
        transform: scale(10);
    }
    

    This will enlarge the image tenfold, but restrict it to 10% of its final size - thus bounding it to the container.

    Unlike the background-image solution, this will also work with elements.

    Interactive example:

     function step(timestamp) {
         var container = document.getElementById('container');
         timestamp /= 1000;
         container.style.left   = (200 + 100 * Math.sin(timestamp * 1.0)) + 'px';
         container.style.top    = (200 + 100 * Math.sin(timestamp * 1.1)) + 'px';
         container.style.width  = (500 + 500 * Math.sin(timestamp * 1.2)) + 'px';
         container.style.height = (500 + 500 * Math.sin(timestamp * 1.3)) + 'px';
         window.requestAnimationFrame(step);
     }
    
     window.requestAnimationFrame(step);
     #container {
         outline: 1px solid black;
         position: relative;
         background-color: red;
     }
     #image {
         display: block;
         max-width: 10%;
         max-height: 10%;
         transform-origin: 0 0;
         transform: scale(10);
     }

提交回复
热议问题