【问题标题】:CSS: Fit image by its smaller sideCSS:以较小的一侧适合图像
【发布时间】:2015-04-29 18:26:53
【问题描述】:

我正在尝试创建一个可以显示任何图像大小(长或宽)的图标容器。

图片应以较小的一面适合容器,而额外的将在容器之外。在应用溢出之前:隐藏它应该像这样工作。

用 js 做起来似乎相当容易,但我很想找到一个 css 解决方案。

<div class="container">
   <img src="test.png"/>
</div>

.container {
   width: 30px;
   height: 30px;
}
.container img {
   position: relative;
   left: 50%;
   top: 50%;
   transform: translateY(-50%) translateX(-50%);
}

【问题讨论】:

  • background-size: cover 怎么样? jsfiddle.net/cqns0e24
  • @AlexeyLebedev 似乎工作得很好!谢谢!
  • 很乐意选择它作为接受的答案,但它不适用于 cmets

标签: html css


【解决方案1】:

如果您不想使用background-size:cover 使用 CSS 背景(尽管这也不是一个糟糕的解决方案),这是一项相当具有挑战性的任务,因为有一个关键因素:横向与纵向图像。没有办法在 CSS 中检测图像的方向。这是一个问题,因为您不能只将heightwidth(或max-heightmax-width)分配给100% 并期望它能够工作。它会扭曲图像并失去纵横比。在这种情况下,我建议使用一些 javascript 来区分两者。这很不幸,但如果您想使用 HTML img 元素实现此效果,这是必要的(再次强调,这不是唯一的解决方案。背景图像仍然可行)。

这是我想出的实现这种效果的方法:

var images = document.querySelectorAll('.container img');
for(var i = 0, len = images.length; i < len; i++) {
  images[i].addEventListener('load', function() { 
    this.className += (this.width > this.height) ? ' landscape' : ' portrait';
  });
}
.container {
    position: relative;
    width: 50px;
    height: 50px;
    margin: 3em auto;
}
.container:after {
    content: '';
    position: absolute;
    width: 100%;
    height: 100%;
    left: 0;
    top: 0;
    border: 2px solid;
    box-sizing: border-box;
}
.container img {
    position: absolute;
    max-width: 100%;
    max-height: 100%;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    padding: 2px;
    box-sizing: border-box;
}

.container img.landscape {
    max-width: none;
}
.container img.portrait {
    max-height: none;
}
<div class="container">
    <img src="//placehold.it/200x300"/>
</div>

<div class="container">
    <img src="//placehold.it/300x200"/>
</div>

<div class="container">
    <img src="//placehold.it/200x200"/>
</div>

<div class="container">
    <img src="//placehold.it/500x100"/>
</div>

【讨论】:

    【解决方案2】:

    https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit

    原来还有另一种方法可以做到这一点。

    <img style='height: 100%, width: 100%, object-fit: cover'/> 
    

    将完成这项工作。这是 CSS3 的东西。

    小提琴:http://jsfiddle.net/mbHB4/3/

    【讨论】:

      【解决方案3】:

      使用这个 css 属性

          .container img
      {
      height:100%;
      width:100%;
      }
      

      【讨论】:

        猜你喜欢
        • 2019-05-03
        • 1970-01-01
        • 2015-09-01
        • 1970-01-01
        • 2021-01-14
        • 2016-01-06
        • 1970-01-01
        • 2015-11-13
        • 1970-01-01
        相关资源
        最近更新 更多