CSS缩放图像并填充容器

时间:2014-12-13 11:10:51

标签: jquery html css image css3

图像尺寸有3个案例:

  1. image width > image height
  2. image width < image height
  3. image width == image height
  4. 我需要使用img来显示div内的图片。

    <div class="container">
        ...
        <img class="scale-and-fill" src="..." />
        ...
    </div>
    

    如何:

    1. 如果图像的两个尺寸都小于容器,请在保持其比例的同时将其放大,并让较短的尺寸与容器的尺寸相匹配。
    2. 如果图像的两个尺寸都大于容器,请在保持其比例的同时缩小尺寸,让较短的尺寸与容器的尺寸相匹配。
    3. 如果图像的一个维度较大但另一个维度小于容器,则缩小较小的维度以匹配容器维度,并裁剪溢出图像的剩余部分。
    4. 下面的CSS类应该输入什么?

      .container {
         ...
      }
      .scale-and-fill {
         ...
      }
      

      更新

      包含屏幕截图以清楚地说明我的问题。

      Screenshot illustrating my problem

5 个答案:

答案 0 :(得分:0)

你最好的选择是缩减规模。让我们假设高度不合适。如果是这种情况,下面的内容将会很有用

.container {
   width: 250px; /* Adjust as needed */
   height: 200px; /* Must be a litle smaller than the images original height */
   overflow: hidden;
}

.scale-and-fill {
   width: 100%;
   height: auto; /* The image will now fit since 
  .container is smaller than the original size */
}

webdesignsharepoint

查看有关图像控制的本教程

答案 1 :(得分:0)

您可以设置.container的宽度/高度,例如:

.container {
width: 300px;
height: 250px;
}

并设置图像样式:

.scale-and-fill {
display: block;
width: 100%;
max-width: 100%;
max-height: 100%;
}

答案 2 :(得分:0)

你不能只用css做这件事。您描述的问题有以下形式:

IF (image-dimensions) THEN (css-rule)

为此你需要编写脚本。

答案 3 :(得分:0)

你需要在不同的情况下应用两个不同的类:

.scale-and-fill1 {
  width: 100%;
  height: auto;
  position: relative;
}

.scale-and-fill2 {
  width: auto;
  height: 100%;
  position: relative;
}

.container {
  overflow: hidden;
}

这应该保持比例,但是为了获得正确的课程你应该使用一点点javascript。

我会添加这个jquery javascript:

$(document).ready(
  $('.container img').each(function() {
    var ratio = $(this).width() / $(this).height();
    if (ratio > 1) {
      $(this).attr('çlass','.scale-and-fill2');
      $(this).attr('left',$('. container').width()/2 - $(this).width() / 2);
    } else {
      $(this).attr('çlass','.scale-and-fill1');
      $(this).attr('top',$('. container').height()/2 - $(this).height() / 2);
    }
  });
)

答案 4 :(得分:0)

使用您选择的宽高比。 16/9用于高清显示器。

.container {
  width: 300px;
  height: 250px;
}

.scale-and-fill {
  width: 100%;
  height: unset;
  object-fit: cover;
}

@media (max-aspect-ratio: 16/9) {
  .scale-and-fill {
    width: unset;
    height: 100%;
  }
}