2

I'm trying to make a number pad with 3 columns on 4 rows. I've used flexbox with flex-wrap and flex-basis: 33.33%.

The problem is that I need some margin between my columns, but as soon as I put like margin: 0.5em it pushes one item down making it only 2 per row.

Padding doesn't work, margin doesn't work, border doesn't work for my transparent background.

.digit-grid {
  display: flex;
  flex-wrap: wrap;
  font-size: 2em;
}

.box {
  flex-basis: 33.33%;
  margin: 0.5em;
  background: gray;
  height: 50px;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
}
<div class="digit-grid">
   <div class="box box1">1</div>
   <div class="box box2">2</div>
   <div class="box box3">3</div>
   <div class="box box4">4</div>
   <div class="box box5">5</div>
   <div class="box box6">6</div>
   <div class="box box7">7</div>
   <div class="box box8">8</div>
   <div class="box box9">9</div>
   <div class="box box10">10</div>
   <div class="box box11">11</div>
   <div class="box box12">12</div>
</div>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415
piedude
  • 111
  • 1
  • 10

1 Answers1

3

You can adjust for the margin using calc in flex-basis like calc(33.33% - 1em) - see demo below:

.digit-grid {
  display: flex;
  flex-wrap: wrap;
  font-size: 2em;
  background: black;
}

.box {
  flex-basis: calc(33.33% - 1em);
  margin: 0.5em;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
}
<div class="digit-grid">
  <div class="box box1">1</div>
  <div class="box box2">2</div>
  <div class="box box3">3</div>
  <div class="box box4">4</div>
  <div class="box box5">5</div>
  <div class="box box6">6</div>
  <div class="box box7">7</div>
  <div class="box box8">8</div>
  <div class="box box9">9</div>
  <div class="box box10">10</div>
  <div class="box box11">11</div>
  <div class="box box12">12</div>
</div>
kukkuz
  • 41,512
  • 6
  • 59
  • 95
  • Thanks! Also, how can I make the .box class a perfect square? i tried setting a height but it becomes distorted – piedude Apr 06 '19 at 15:51
  • for squares, try this: https://stackoverflow.com/questions/29307971/css-grid-of-squares-with-flexbox – kukkuz Apr 06 '19 at 15:54