【问题标题】:Crop image to size of <div>将图像裁剪为 <div> 的大小
【发布时间】:2014-09-19 22:07:39
【问题描述】:

我网站上的一些图片有点问题。我有一个 280x310 的 div 容器,但我所有的图像都比这个容器大。我想保持图像的纵横比,并将它们适合 div 的整个高度,裁剪左右图像的任何额外部分(保持图像居中)。这在css中可能吗?感谢您的帮助。

【问题讨论】:

  • 是什么阻止你在 CSS 中使用背景图片?
  • 如果你愿意,你的图片可以正确地适合你的 div .

标签: css html image


【解决方案1】:

将此添加到您的 css 代码中

.imgfit { width: 250px; height:500px; object-fit: cover}

Object-fit 将为您完成这项工作。

【讨论】:

【解决方案2】:

将图像作为 div 的背景图像并使用 background-size: contains(查看所有图像)或 background-size:cover(缩放和裁剪)

查看Set size on background image with CSS?

【讨论】:

    【解决方案3】:

    这可以通过一点 jQuery 来实现:

    通过将overflow:hidden 设置为包含图像的div,并将height:100% 设置为图像,它将调整大小以填充div 的高度,而不会变形。然后我们使用 jQuery 以position:absolute 将图像居中。

    (http://jsfiddle.net/kK4ZV/)

    HTML:

    <div class="container">
       <img src="http://placehold.it/350x150">
    </div>
    
    <div class="container2">
        <img src="http://placehold.it/350x150" class="imageid">
    </div>
    
    <div class="container2">
        <img src="http://placehold.it/600x300" class="imageid">
    </div>
    

    CSS:

    .container {
        border:1px solid red;
        width: 280px;
        height:310px;
    }
    .container2 {
        border:1px solid blue;
        width: 280px;
        height:310px;
        overflow: hidden;
        position:relative;
    }
    .container2 img {
        height:100%;
    }
    .js-fix {
      position:absolute;
      top:0;
     left:50%;
    }
    

    jQuery:

    $(".imageid").each(function(){
      var hWide = ($(this).width())/2; //half the image's width
      hWide = '-' + hWide + 'px';
      $(this).addClass("js-fix").css({
        "margin-left" : hWide,
      });
    });
    

    (借用here的jQuery代码)

    【讨论】:

      【解决方案4】:
      position: fixed; 
      x-overflow: hidden;
      max-width: 100%
      

      【讨论】:

        【解决方案5】:

        您可以使用 html 做到这一点:

        <img src='image.jpg' alt='Image' width='240' height='310'/>
        

        您可以在http://www.w3schools.com/tags/att_img_height.asp查看更多内容


        此外,使用 css 您可以为图像本身创建一个类或 ID:

        img.sized{
            height:310px;
            width:210px;
            }
        

        然后在你的 img 标签中使用类:

        <img src='image.jpg' class='sized'/>
        

        您可以在 http://www.w3schools.com/css/css_dimension.asp 上阅读有关 CSS 大小调整的更多信息

        【讨论】:

          猜你喜欢
          • 2012-03-12
          • 2020-06-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-02-02
          • 2011-11-11
          • 1970-01-01
          相关资源
          最近更新 更多