I'm struggling to arrange a list of divs in a grid layout using only CSS, but I can't seem to make it work properly. I've explored using white-space: wrap
, but that's supposed to be applied to the parent element, so it doesn't solve my problem. I also experimented with clear
, but had no success. Can anyone suggest an approach that would work for any number of elements per row? The code provided is intended for three elements per line.
The reason for sticking to CSS is that this code is designed to allow users to display entries horizontally, vertically, or as a customizable grid (with 'n' representing the configurable value of elements per row).
Intended grid view display (when n=3):
Entry 1 | Entry 2 | Entry 3
--------+---------+--------
Entry 4 | Entry 5 | Entry 6
--------+---------+--------
Entry 7 | Entry 8 | Entry 9
#results.grid {
padding-top: 40px;
}
#results.grid .entry {
display: inline-block;
}
#results.grid .entry:nth-child(3n+1) {
background-color: yellow;
display: block;
}
<div id="results" class="results grid">
<div class="entry">Entry 1</div>
<div class="entry">Entry 2</div>
<div class="entry">Entry 3</div>
<div class="entry">Entry 4</div>
<div class="entry">Entry 5</div>
<div class="entry">Entry 6</div>
<div class="entry">Entry 7</div>
<div class="entry">Entry 8</div>
<div class="entry">Entry 9</div>
</div>
Check out the JSFiddle here: https://jsfiddle.net/rn05gns1/