Search code examples
pythonhtmlcssimagecrop

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


I have a for loop in Flask (Python) that creates a div for every post, that includes an image. I want it to be a square. This is how it is written now:

  <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>

The problem is: this stretches the image into a box. How can I make it crop the image?


Solution

  • You should try like this-

    Add a custom class (cropImg) and remove height and width on the img.

    .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>