Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
430 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

.grid {
  display: grid;
  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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...