3

I basically have a group of images of unknown sizes. Some may have a width > height and vice versa.

I need to display these items scaled to fit in a 300x300 box. Some of these images are smaller than 300x300 and need scaled up and some are larger and need scaled down.

So basically if I have an image that is 100x200, I need it to display at 150x300 and if I have an image that is 800x400 it needs to display as 300x150.

ie one of the dimension need to be fit on the box and other dimension need to be resize as aspect ratio.

Since this is a user selected object in a database, I initially tried this in javascript but I'm struggling. I'm curious if there's a purely CSS way to do this.

5 Answers5

3

Hello You can use below code only use css and javascript

which will maintain your aspect ration also

<style type="text/css">
    .image_box{
        width: 300px;
        height: 300px;
        background: #FF0;
    }
</style>
<div class="image_box">
    <img src="1.jpg"  id="imageid">
</div>
<script type="text/javascript">
    var img = document.getElementById('imageid'); 
    //or however you get a handle to the IMG
    var width = img.clientWidth;
    var height = img.clientHeight;
    //alert(width);
    //alert(height);
    if(width>height){
         img.style.width = '300px';
    }else{
        img.style.height = '300px';
    }
</script>
  • I've long looked for a solution to his, and whether there is a CSS only way. Short answer: no! This, and only this solution is the single only way, so that the element is scaled according to it's intrinsic size. (yes, the intrinsic property could also be read) in any case, it is mandatory to make a comparison between w<>h and depending on the result set the major axis. many solutions suggest 100% 100% and object-fit: contain, which in some cases may _visually_ help but **not technically** make the **element** the desired size, there will always be a letter-box and border radius cannot be used. – somedotnetguy Aug 11 '22 at 08:50
1

There are 2 ways you can do this with pure CSS.

Option 1: CSS Background-Image (Recomended)

You can set the image to the background of a div and then set the div's height to the desired dimensions.

<div class="background"></div>

.background {
  background-image: url("SOMEURL");
  background-size: cover;
  background-position: center center;
  width: 150px;
  height: 300px;
}

You can set the background-size to cover to scale the background image so it takes up the available width or height.

This method is recommended due to better browser support (IE 9+)

Demo: http://codepen.io/aaronvanston/pen/NbrYWM

Option 2: Using an Image and setting object-fit

You can use a normal image instead

<img src="SOMEURL" class="fit-image" >

.fit-image {
  width: 150px;
  height: 300px;
  object-fit: cover;
}

Demo: http://codepen.io/aaronvanston/pen/gLMeMX

This does the same thing as the background image however it's using an image element. However, this method isn't as supported. (no support for IE) http://caniuse.com/#feat=object-fit

Community
  • 1
  • 1
Aaron Vanston
  • 755
  • 7
  • 19
  • 1
    no support in Edge either - and surely the OP would want `contain` with width and height 300px, not `cover` with width 150px!! – Jaromanda X Nov 15 '16 at 05:20
  • Correct :) With cover/contain I wasn't sure if OP wanted it to crop or simply include the image and restrict it to the bounding box. – Aaron Vanston Nov 15 '16 at 05:26
0

Method1 with simple css: (this way small pics will not scale up to container)

<div style="width:300px; height:300px; border:2px solid black;">
    <img src="images/p1.jpg" style="max-width:300px; max-height:300px;" />
</div>

Update Method 2: (this use background-image and works also for small pics, it is ok for modern browsers including IE9+)

<html>
<head>
<style type="text/css">
.divImg {
  width:300px; height:300px; border:2px solid black;
  background-repeat: no-repeat;
  background-size: contain; /* IE9+ compatible */
}
</style>
</head>
<body>  
    <div class="divImg" style="background-image:url(p1.jpg)">
    </div>
</body>
</html>
S.Serpooshan
  • 7,608
  • 4
  • 33
  • 61
0

The solution is a combination of two main features;

  1. Using a transparent gif or png image, sized at 300x300px
  2. css for the background image and using the background-size:contain property value.

Here's an example where i have used a 100x200 image and a 800 x 400 image. http://codepen.io/partypete25/pen/ZBOxKg/

The benefit of not specifying the width and height (using a transparent image to maintain the correct aspect ratio) is that you can use this implementation in a responsive build.

partypete25
  • 4,353
  • 1
  • 17
  • 16
0

I would do something like this. I hope this solution helps.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
  .img-cont {
    border: solid 1px red;
    width: 300px; /* reference border */
    height: 300px;
  }
</style>
</head>
<body>
<!-- images with different dimensions -->
<div class="img-cont"><img src="https://dummyimage.com/800x400/000/fff" alt=""/></div>
<div class="img-cont"><img src="https://dummyimage.com/400x800/000/fff" alt=""/></div>
<div class="img-cont"><img src="https://dummyimage.com/100x200/000/fff" alt=""/></div>
<div class="img-cont"><img src="https://dummyimage.com/200x100/000/fff" alt=""/></div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript">     
  (function($) {
    // max image width/height that we want
    var maxWidthAllowed = 300,
        maxHeightAllowed = 300;        
    function loadImg(imgObj) {        
      $('.img-cont img').one("load", function() {

        var imgWidth = $(this).get(0).naturalWidth,
            imgHeight = $(this).get(0).naturalHeight,
            coeff = imgWidth/imgHeight; // get image proportion
        if(parseFloat(coeff) > 1) {
          // wide image
          // resize proportionately
          $(this).css({
            'max-width': maxWidthAllowed,
            'width': '100%',
            'height' : 'auto'
          });
        } else {
          // thin image
          // resize proportionately
          $(this).css({
            'max-height': maxHeightAllowed,
            'height': '100%',
            'width' : 'auto'
          });
        }
      }).each(function() {
        if(this.complete) $(this).load();
      });
    }
    loadImg();
  })(jQuery);
    </script>
</body>
</html>
dinesh
  • 342
  • 2
  • 13