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

时间:2017-03-08 19:20:05

标签: css image twitter-bootstrap twitter-bootstrap-4

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

还记得Instagram仅显示缩略图的方形图像吗?我想实现这一目标。我已经做了一些研究并尝试了一些由其他人写下来的东西,但唯一能够接近这一点的是这一个: https://stackoverflow.com/a/23518465/1067213

但结果不是我真正希望它做的: Here you can see the difference in the three images

正如您所看到的那样,图像不是正方形,并且第一个图像下方有一个间隙,因此它与其他两列对齐(我确实希望所有列的宽度和高度相同)。

我使用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;
}

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

desired result 如果您需要更多信息,请与我们联系。

提前致谢!

2 个答案:

答案 0 :(得分:2)

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

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

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

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

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

答案 1 :(得分:0)

您可以使用包装并播放宽度,最大宽度和最小高度:

<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%);
}

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

你也可以使用背景大小:封面和背景位置。

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

此致

相关问题