CSS图像网格 - 处理填充

时间:2017-04-23 20:31:53

标签: html css

我创建了这个网格:

* {
  box-sizing: border-box;
  position: relative;
}

.grid>* {
  float: left;
  padding-right: 1em;
}

.grid>*:last-of-type {
  padding-right: 0;
}

.grid:after {
  content: "";
  display: table;
  clear: both;
}

.col-4 {
  width: 33.3333333333%;
}

img {
  display: block;
  width: 100%;
  border-radius: 5px;
}
<div class="grid">
  <div class="col-4">
    <img src="https://i.stack.imgur.com/a6Ieo.jpg" alt="">
  </div>
  <div class="col-4">
    <img src="https://i.stack.imgur.com/a6Ieo.jpg" alt="">
  </div>
  <div class="col-4">
    <img src="https://i.stack.imgur.com/a6Ieo.jpg" alt="">
  </div>
</div>

对于最后.col-4的填充,我每次最后一张图像都比其他图像大。我的问题是,如何才能将最后一张图像显示在与其他图像相同的高度上,但对于padding-right,对于未知高度的图像,不保留.col-4

3 个答案:

答案 0 :(得分:1)

如果我是你,我会使用flexbox。

&#13;
&#13;
body {
  margin: 0
}

.grid {
  display: flex;
  flex-wrap: wrap;
  width: 100%
}

.col-4 {
  flex: 0 calc((100%/3) - .67em);
  margin-right: 1em
}

.col-4:last-of-type {
  margin-right: 0
}

img {
  display: block;
  width: 100%;
  border-radius: 5px;
}
&#13;
<div class="grid">
  <div class="col-4">
    <img src="https://i.stack.imgur.com/a6Ieo.jpg" alt="">
  </div>
  <div class="col-4">
    <img src="https://i.stack.imgur.com/a6Ieo.jpg" alt="">
  </div>
  <div class="col-4">
    <img src="https://i.stack.imgur.com/a6Ieo.jpg" alt="">
  </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以从图片的宽度中移除1em,使其像其他图片一样缩放。

&#13;
&#13;
* {
  box-sizing: border-box;
    position: relative;
}
.grid > * {
  float: left;
  padding-right: 1em;
}
.grid > *:last-of-type {
  padding-right: 0;
}
.grid > *:last-of-type img {
  width: calc(100% - 1em);
}
.grid:after {
  content: "";
  display: table;
  clear: both;
}

.col-4 {
  width: 33.3333333333%;
}

img {
  display: block;
  width: 100%;
  border-radius: 5px;
}
&#13;
<div class="grid">
   <div class="col-4">
      <img src="https://i.stack.imgur.com/a6Ieo.jpg" alt="">
   </div>
   <div class="col-4">
      <img src="https://i.stack.imgur.com/a6Ieo.jpg" alt="">      
   </div>
   <div class="col-4">
      <img src="https://i.stack.imgur.com/a6Ieo.jpg" alt="">
  </div>
</div>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

添加margin: /*some value in px*/;