CSS: 图片被拉伸成正方形,如何裁剪?

CSS: Image is stretched to square, how to crop it?

我在 Flask (Python) 中有一个 for 循环,它为每个包含图像的 post 创建一个 div。我希望它是一个正方形。 现在是这样写的:

  <div class="row">
  {% for post in posts.items %}
    <div class="col-xs-6 col-sm-4">
      {% if post.image %}
        <h4 class="col-centered"><a href="{{ url_for('article', slug=post.slug) }}" class="link">
          <img src="{{ post.imgsrc }}" height="370px" width="370px" class="img-rounded">
        </h4>
      {% endif %}
      <h3>
        <h4><a href="{{ url_for('article', slug=post.slug) }}">{{     post.title }}</a></h4>
      </h3>
  </div>

问题是:这会将图像拉伸成一个方框。我怎样才能让它裁剪图像?

你应该这样尝试-

添加自定义 class (cropImg) 并删除 img 上的 heightwidth

.cropImg{
  overflow:hidden;
}
.cropImg h4 img{
  width:auto;
  max-width:auto
}
<div class="row">
  {% for post in posts.items %}
    <div class="col-xs-6 col-sm-4 cropImg">
      {% if post.image %}
        <h4 class="col-centered"><a href="{{ url_for('article', slug=post.slug) }}" class="link">
          <img src="{{ post.imgsrc }}" height="" width="" class="img-rounded">
        </h4>
      {% endif %}
      <h3>
        <h4><a href="{{ url_for('article', slug=post.slug) }}">{{post.title }}</a></h4>
      </h3>
  </div>

您可以使用 object-fit 属性 如下:

CSS

img {
 object-fit: cover;
}

但IE不支持。检查对 caniuse

的支持

如果您想要其他解决方案,可以将图像包裹在 div 中,并从 HTML 中删除宽度和高度属性。

CSS

.img-wrapper {
  width: 200px;
  height: 200px;
  overflow: hidden;
}

img {
  width: 100%;
}