html - How do I create a 3x3 grid via CSS? -
given 9 div
s 1 after another, want create grid 3x3 via css.
how do that?
.cell { height: 50px; width: 50px; background-color: #999; display: inline-block; } .cell:nth-child(3n) { background-color: #f00; /* property should use line break after element? */ } /* doesn't work; @ 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: don't want float/clear
solution. focus on css , not html restructure.
if add content: '\a'; white-space: pre;
::after
output comes out ugly.
.cell { height: 50px; width: 50px; background-color: #999; display: inline-block; } .cell:nth-child(3n) { background-color: #f00; /* property should use line break after 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 go getting div in 3x3 row-column layout?
besides excellent answer @michael_b use flexbox
, can use
css tables
or
float:left
both support old browsers such ie 8/9 ,
flexbox
won't support.
note ie8 won't support nth-child
supports first/last-child
option1 (css tables) : changes html, wrapping each 3 cells in row.
.grid { display: table; border-spacing: 5px } .row { display: table-row } .cell { width: 50px; height: 50px; background: grey; display: table-cell; } .row div:last-child { background: red }
<div class="grid"> <div class="row"> <div class="cell"></div> <div class="cell"></div> <div class="cell"></div> </div> <div class="row"> <div class="cell"></div> <div class="cell"></div> <div class="cell"></div> </div> <div class="row"> <div class="cell"></div> <div class="cell"></div> <div class="cell"></div> </div> </div>
update
option2 (float:left
): no changes html, using clear:left
@ each (4th)n item.
.cell { width: 50px; height: 50px; background: grey; float: left; margin: 5px } .cell:first-child + div+ div, .cell:first-child + div+ div + div + div + div, .cell:first-child + div+ div + div + div + div + div + div + div { background: red } .cell:first-child + div+ div + div, .cell:first-child + div+ div + div + div + div + div, .cell:first-child + div+ div + div + div + div + div + div + div + div { clear: left }
<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>
Comments
Post a Comment