user7376146
user7376146

Reputation: 63

CSS image grid - dealing with padding

I have created this grid:

* {
  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.sstatic.net/a6Ieo.jpg" alt="">
  </div>
  <div class="col-4">
    <img src="https://i.sstatic.net/a6Ieo.jpg" alt="">
  </div>
  <div class="col-4">
    <img src="https://i.sstatic.net/a6Ieo.jpg" alt="">
  </div>
</div>

With padding for last .col-4 I have every time last image larger than others. My question is what can I do to display last image at the same height as the others, but retain no padding-right for .col-4 for images with unknown height?

Upvotes: 0

Views: 727

Answers (3)

dippas
dippas

Reputation: 60573

I would use flexbox if I were you.

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;
}
<div class="grid">
  <div class="col-4">
    <img src="https://i.sstatic.net/a6Ieo.jpg" alt="">
  </div>
  <div class="col-4">
    <img src="https://i.sstatic.net/a6Ieo.jpg" alt="">
  </div>
  <div class="col-4">
    <img src="https://i.sstatic.net/a6Ieo.jpg" alt="">
  </div>
</div>

Upvotes: 1

Martins
Martins

Reputation: 508

Add margin: /*some value in px*/;

Upvotes: 0

Michael Coker
Michael Coker

Reputation: 53709

You can remove 1em from the image's width so it scales like the rest.

* {
  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;
}
<div class="grid">
   <div class="col-4">
      <img src="https://i.sstatic.net/a6Ieo.jpg" alt="">
   </div>
   <div class="col-4">
      <img src="https://i.sstatic.net/a6Ieo.jpg" alt="">      
   </div>
   <div class="col-4">
      <img src="https://i.sstatic.net/a6Ieo.jpg" alt="">
  </div>
</div>

Upvotes: 0

Related Questions