Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a 3x3 grid via CSS?

Tags:

html

css

flexbox

Given 9 divs one after another, I want to create a grid 3X3 via CSS.

How do I do that?

.cell {
  height: 50px;
  width: 50px;
  background-color: #999;
  display: inline-block;
}

.cell:nth-child(3n) {
  background-color: #F00;
  /* what property should I use to get a line break after this element? */
}

/* this doesn't work; at least not in safari */
.cell:nth-child(3n)::after {
  display: block;
}
<div class="grid">
  <div class="cell"></div>
  <div class="cell"></div>
  <div class="cell"></div>
  <div class="cell"></div>
  <div class="cell"></div>
  <div class="cell"></div>
  <div class="cell"></div>
  <div class="cell"></div>
  <div class="cell"></div>
</div>

Note: I don't want float/clear solution. Focus is on CSS and not HTML restructure.

If I add content: '\A'; white-space: pre; to ::after output comes out to be ugly.

.cell {
  height: 50px;
  width: 50px;
  background-color: #999;
  display: inline-block;
}

.cell:nth-child(3n) {
  background-color: #F00;
  /* what property should I use to get a line break after this element? */
}

.cell:nth-child(3n)::after {
  display: inline;
  content: '\A';
  white-space: pre;
}
<div class="grid">
  <div class="cell"></div>
  <div class="cell"></div>
  <div class="cell"></div>
  <div class="cell"></div>
  <div class="cell"></div>
  <div class="cell"></div>
  <div class="cell"></div>
  <div class="cell"></div>
  <div class="cell"></div>
</div>

How do I go about getting all div in a 3X3 row-column layout?


1 Answers

02/2022 Update: As David mentioned in the comments, grid-gap is now deprecated and was replaced with the tidier gap. I've updated the code snippet below to reflect this.


Now that CSS Grid is fairly very well supported, I thought I'd supplement the other answers with a more modern solution.

.grid {
  display: grid;
  gap: 1px;
  grid-template-columns: repeat(3, 1fr);
}

div > div {
  padding: 10px;
  background-color: #ccc;
}
<div class="grid">
  <div>item</div>
  <div>item</div>
  <div>item</div>
  <div>item</div>
  <div>item</div>
  <div>item</div>
  <div>item</div>
  <div>item</div>
  <div>item</div>  
</div>
like image 68
Andy Hoffman Avatar answered Sep 06 '25 21:09

Andy Hoffman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!