调整未知大小和宽高比的图像

3
我有一组未知大小的图像,其中一些可能具有宽度>高度或相反。
我需要将这些项显示为缩放到300x300的框中。其中一些图像比300x300小,需要放大,而其他一些则比较大,需要缩小。如果我有一个100x200的图像,则需要将其显示为150x300,如果我有一个800x400的图像,则需要显示为300x150
换句话说,一个维度需要适合盒子,而另一个维度需要按比例调整大小。
由于这是数据库中用户选择的对象,因此我最初尝试在javascript中实现,但我遇到了困难。 我想知道是否有纯CSS的方法来实现此目的。

你需要一个纯CSS的解决方案还是JavaScript也可以接受? - S.Serpooshan
为什么不只设置高度或宽度?而不是同时设置高度和宽度。 - Anant Dabhi
将图片设置为 div 的背景而不是显示为图像,使用 background-size: cover; background-position: center; 可以将图像适应到背景中心,并进行缩放。 - santosh
5个回答

3

你好,您可以仅使用CSS和JavaScript来使用以下代码

这将保持您的宽高比例,并使内容更加易于理解。

<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>

我长期以来一直在寻找解决方案,是否有纯CSS的方法。简短的回答是:没有!这个解决方案是唯一的方法,使元素根据其固有大小进行缩放。(是的,固有属性也可以被读取)无论如何,必须对w<>h进行比较,并根据结果设置主轴。许多解决方案建议使用100% 100%和object-fit: contain,在某些情况下可能会在视觉上有所帮助,但从技术上讲并不能使元素达到所需的大小,始终会有一个字母盒子,而且无法使用边框半径。 - somedotnetguy

1

您可以通过纯CSS的两种方式来实现此目标。

选项1:CSS背景图片(建议使用)

您可以将图像设置为div的背景,然后将div的高度设置为所需尺寸。

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

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

你可以将background-size设置为cover,以缩放背景图像,以便占用可用的宽度或高度。

由于浏览器支持更好(IE 9+),因此建议使用此方法。

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

选项2:使用图像并设置object-fit

您可以使用普通图像代替

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

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

演示: http://codepen.io/aaronvanston/pen/gLMeMX

这与背景图像的效果相同,但它使用的是图像元素。然而,这种方法的支持程度不如背景图像。(不支持IEhttp://caniuse.com/#feat=object-fit


1
在Edge中也没有支持,而且肯定是帖子作者想要宽度和高度为300px的contain,而不是宽度为150px的cover - Jaromanda X
正确 :) 对于“cover/contain”,我不确定OP是否希望裁剪图像或仅包含图像并将其限制在边界框内。 - Aaron Vanston

0

该解决方案是由两个主要特性组合而成的:

  1. 使用一个透明的gif或png图像,大小为300x300像素
  2. 使用css作为背景图片,并使用background-size:contain属性值。

这里有一个例子,我使用了一个100x200像素的图像和一个800 x 400像素的图像。 http://codepen.io/partypete25/pen/ZBOxKg/

不指定宽度和高度(使用透明图像来保持正确的长宽比)的好处是,您可以在响应式构建中使用此实现。


0

使用简单的CSS的Method1: (这样小图片就不会扩展到容器大小)

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

更新方法2:(这个使用背景图片,适用于小图片,对于包括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>

使用maxes函数,100x200的图像仍保持为100x200。 - insertusernamehere
@ThomasAnthony 是的,你说得对,我已经更新了我的答案以支持小图片。 - S.Serpooshan

0
我会这样做。希望这个解决方案能够有所帮助。
<!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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接