0

The inner divs will be thumbs that are being continuously added and eventually wrap to next row.

The space between divs should be 20px. I want four divs in one row.

Two constraints:

  1. Ideally no flexbox space-between, due to last row looking weird with only two divs.
  2. Adding margin only between inner divs not a good option (unless there’s an easy way to do this for dynamically added content?).

Is there a way to accomplish this?

#outer {
  width: 460px;
  display: inline-block;
}

.inner {
  width: 100px;
  height: 100px;
  float: left;
}
<div id="outer">
  <div class="inner">1</div>
  <div class="inner">2</div>
  <div class="inner">3</div>
  <div class="inner">4</div>
</div>

Codepen example

David Thomas
  • 249,100
  • 51
  • 377
  • 410
Chris K.
  • 75
  • 6
  • `#outer > div:nth-child(n+2) { margin-left: 20px }`, oh and what's the point of the float here? – Chris W. Sep 20 '19 at 17:54
  • "*I want four divs in one row.*" - will new elements be added four at a time? If not, what should happen in the event of one, two or three new elements being added? – David Thomas Sep 20 '19 at 18:02
  • @DavidThomas Elements don't have to be added four at a time. In any case elements should wrap to next row. Yazans and Ibrahims solutions are great. – Chris K. Sep 20 '19 at 19:13

4 Answers4

1

Try this. Hope, it will work.

I used the CSS grid. By using grid-template-columns, I have declared how four children elements of outer ID take the same area in a row. After that, I used grid-gap: 20px for giving space between four children block.

#outer {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-gap: 20px;
}
Ibrahim Hasnat
  • 935
  • 1
  • 8
  • 16
1

You can use this code:

.inner {
  display: inline-block;
}

.inner:not(:last-child){
  margin-right: 20px;
}
<div id="outer">
  <div class="inner">1</div>
  <div class="inner">2</div>
  <div class="inner">3</div>
  <div class="inner">4</div>
</div>

Read a reference here: css-protips

Kevin Hernández
  • 704
  • 10
  • 25
Mohammad
  • 183
  • 1
  • 10
0

You may need to use nth-child(4n)

.inner {
  margin-right: 20px;
}
.inner:nth-child(4n){
  margin-right:0px;
}

Codepen: https://codepen.io/abozanona/pen/RwbqmZb

Abozanona
  • 2,261
  • 1
  • 24
  • 60
-1

You could use a margin and avoid the last one:

.inner:not(:last-of-type) {
  margin-right: 20px;
}
Josh Davis
  • 157
  • 3
  • 10