【问题标题】:CSS: Image is stretched to square, how to crop it?CSS:图像被拉伸为正方形,如何裁剪它?
【发布时间】:2016-03-27 05:19:08
【问题描述】:

我在 Flask (Python) 中有一个 for 循环,它为每个帖子创建一个 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>

问题是:这会将图像拉伸成一个盒子。如何让它裁剪图像?

【问题讨论】:

    标签: python html css image crop


    【解决方案1】:

    你应该这样尝试-

    添加自定义类 (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>

    【讨论】:

      【解决方案2】:

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

      CSS

      img {
       object-fit: cover;
      }
      

      但 IE 不支持。查看caniuse上的支持

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

      CSS

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

      【讨论】:

        猜你喜欢
        • 2011-02-07
        • 2017-05-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-10-31
        • 2012-04-23
        • 2023-03-21
        • 2013-02-16
        相关资源
        最近更新 更多