使用CSS保持宽高比居中并裁剪缩略图?

时间:2019-01-03 20:48:23

标签: html css css3

我想创建一个缩略图图像,但问题是在调整屏幕大小时,图像会保留粉红色(白色)背景。如何迫使图像裁剪?

我想要的效果的一个很好的例子是从这个网站,当查看开发人员工作缩略图时,他们会调整大小!: http://riccardozanutta.com/

我的CodePen: https://codepen.io/MariusZMM/pen/MZQrVv

.project-content {
    display: flex;
    justify-content: center;
    flex-flow: row wrap;
}

.proCont {
    position: relative;
    margin: 10px;
    height: 270px;
    width: 420px;
    flex-grow: 1;
    width: 30%;
    overflow: hidden;
    background-color: #b44dc2;
}

.proCont img {
    position: absolute;

    /* width: 100%;
    height: auto; */

    width: auto;
    height: 100%;

    /* display: inline-block; */
    /* overflow: hidden; */
    vertical-align: middle;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    /* background-position: 50%; */
    /* background-size: cover;
    background-repeat: no-repeat;
    background-position: center; */
}

2 个答案:

答案 0 :(得分:0)

object-fit:封面;确实有效,我还需要将宽度更改为100%

https://codepen.io/MariusZMM/pen/gZvvPM

width: 100%;
height: 100%;

答案 1 :(得分:0)

使图像100%宽高,并使用object-fit: cover

.project-content {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: center;
}

.proCont {
  width: 30%;
  height: 270px;
  margin: 1%;
  background-color: #b44dc2;
}

.proCont img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
<div class="project-content">
  <a class="proCont" href="#"><img src="https://i.imgur.com/bpnac5F.jpg" alt=""></a>
  <a class="proCont" href="#"><img src="https://i.imgur.com/bpnac5F.jpg" alt=""></a>
  <a class="proCont" href="#"><img src="https://i.imgur.com/bpnac5F.jpg" alt=""></a>
  <a class="proCont" href="#"><img src="https://i.imgur.com/bpnac5F.jpg" alt=""></a>
  <a class="proCont" href="#"><img src="https://i.imgur.com/bpnac5F.jpg" alt=""></a>
  <a class="proCont" href="#"><img src="https://i.imgur.com/bpnac5F.jpg" alt=""></a>
  <a class="proCont" href="#"><img src="https://i.imgur.com/bpnac5F.jpg" alt=""></a>
  <a class="proCont" href="#"><img src="https://i.imgur.com/bpnac5F.jpg" alt=""></a>
</div>