如何使图像显示为正方形?

How do I make images display as a square?

我最近一直在使用 bootstrap 4 alpha 版本来创建一个项目,经过大量尝试后,我无法让上传的不同尺寸的图像在显示时显示为正方形。

还记得 Instagram 如何只显示缩略图的方形图像吗?我想实现这一目标。我做了一些研究并尝试了其他人写下的一堆东西,但唯一接近的是这个:

但结果并不是我真正想要的:

如您所见,图片不是正方形的,第一张图片下方有一个空隙,因此它与其他两列对齐(我希望所有列的宽度和高度都相同)。

我使用 Django 创建图像文件的 URL。

这是我的 html:

<div class="row">
    {% if competition_list %}
    {% for competition in competition_list %}

        <div class="col-md-4">
          <div class="card">
            <div class="image">
            <img class="card-image-top img-fluid" src="/{{competition.image.url}}" >
            </div>
            <div class="card-block">
              <h4 class="card-title">{{competition.name}}</h4>
              <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>
              <p><a class="btn btn-secondary" href="https://v4-alpha.getbootstrap.com/examples/jumbotron/#" role="button">View details »</a></p>
            </div>
            </div>
        </div>

    {% endfor %}
    {% else %}
    <p>No competitions in this category, please try an other category</p>
    {% endif %}
    </div>

这是我的 CSS:

.card {
    margin-bottom: 10px;
}

.image{
    position:relative;
    overflow:hidden;
    padding-bottom:100%;
}
.image img{
    position:absolute;
}

理想的结果看起来有点像这样:

如果您需要更多信息,请告诉我。

提前致谢!

这真的与 Django 或 Bootstrap 无关。您需要将图像设置为 .image 上的背景,以便将它们裁剪成正方形。

<div class="image" style="background-image: url(/{{competition.image.url}});" ></div>

还要确保您已应用 CSS 以使用背景图片填充元素:

.card .image {
    background-size: cover;
}

你也可以尝试强制图片拉伸到.image高度的100%并隐藏水平溢出,但背景方法更简单。

您可以使用包装器并调整宽度、最大宽度和最小高度:

<div class="image-wrapper">
  <img src="http://placehold.it/350x300">
</div>

<div class="image-wrapper">
  <img src="http://placehold.it/500x350">
</div>

<div class="image-wrapper">
  <img src="http://placehold.it/300x500">
</div>

您将宽度设置为 100%,它会缩放高度。

.image-wrapper {
  width: 300px;
  height: 300px;
  overflow: hidden;
  position: relative;
  background: rgba(0, 0, 0, 0.5);
  margin: 10px 0;
}
.image-wrapper img {
  width: 100%;
  position: absolute;
  left: 0;
  top: 50%;
  transform: translateY(-50%);
}

添加、顶部、左侧和变换,使图像垂直居中。

你也可以使用 background-size: cover and play with background-position.

<div class="use-cover-background square" style="background-image: url(http://placehold.it/350x300)"></div>

<div class="use-cover-background square" style="background-image: url(http://placehold.it/500x300)"></div>

<div class="use-cover-background square" style="background-image: url(http://placehold.it/300x500)"></div>

// CSS

.use-cover-background {
  background-size: cover;
  background-position: center;
}
.square {
  margin: 10px 0;
  width: 300px;
  height: 300px;
}

看到他们工作:https://jsfiddle.net/mcgnyfw9/

此致,