How to add 1px margin to a flex item that is flex: 0 0 25%?

You can use flex: 1 0 22% for example. This will allow your element to be defined by 22% as flex-basis (so only 4 elements per row) and they will grow to fill the remaining space left by margin (since flex-grow is set to 1)

#foto-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
  margin: 10px;
}

.foto {
  flex: 1 0 22%;
  min-height: 50px;
  margin: 1px;
  background-color: red;
}
<div id="foto-container">
  <div class="foto foto1">1</div>
  <div class="foto foto2">2</div>
  <div class="foto foto3">3</div>
  <div class="foto foto4">4</div>
  <div class="foto foto5">5</div>
  <div class="foto foto6">6</div>
  <div class="foto foto7">7</div>
  <div class="foto foto8">8</div>
  <div class="foto foto9">9</div>
  <div class="foto foto1">1</div>
  <div class="foto foto2">2</div>
  <div class="foto foto3">3</div>
</div>

The value of flex-basis should be bigger than (20% - margin * 2) and lower than (25% - margin * 2). The first value will allow you to have 5 elements per row, so having a bigger value will make them 4 and having a bigger value than the second one will make the number of element to be 3 per row.

#foto-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-around;
  margin: 10px;
}

.foto {
  flex: 1 0 21%;
  min-height: 50px;
  margin: 1px;
  background-color: red;
  animation: change 4s linear infinite alternate; 
}

@keyframes change {
  0%,40% {flex: 1 0 calc(20% - 2 * 1px);background:yellow;}
  41%,59% {background:red;}
  60%,100% {flex: 1 0 calc(25% - 2 * 1px + 1px);background:green;}
}
<div id="foto-container">
  <div class="foto foto1">1</div>
  <div class="foto foto2">2</div>
  <div class="foto foto3">3</div>
  <div class="foto foto4">4</div>
  <div class="foto foto5">5</div>
  <div class="foto foto6">6</div>
  <div class="foto foto7">7</div>
  <div class="foto foto8">8</div>
  <div class="foto foto9">9</div>
  <div class="foto foto1">1</div>
  <div class="foto foto2">2</div>
  <div class="foto foto3">3</div>
</div>

Leave a Comment