Home > Software engineering >  CSS: grid with different number of items per line
CSS: grid with different number of items per line

Time:01-06

I have this grid which is responsive and has 3 or 2 items per row, depending on the screen width.

enter image description here

I wonder how it would be possible to have 3 items on the first line and only 2 on the second line (and so on... 3:2) on screens that are large enough to show 3 items in a row. otherwise it should be 2:1 items

enter image description here

(These images dont show exactly what i mean because on image 2 two items are lost.

CodePudding user response:

By definition, CSS grid doesn't allow differing numbers of columns per row. With a little bit of planning, you could achieve the effect with flexbox. See the simple example below. Here, I used a basic flex-wrap with constant margins, and adjusted a side margin every nth item.

You might want to enter full screen mode and try adjusting browser window.

.container {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  width: 330px;
  padding: 5px;
  background-color:#333;
}

.item {
  width: 100px;
  height: 100px;
  margin: 5px;
  border-radius: 100px;
  background-color: #bada55;
  display: flex;
  justify-content: center;
  align-items: center;
}

.item:nth-of-type(5n) {
  margin-right: 10px;
}

.item:first-of-type {
  margin-right: 5px;
}

@media screen and (max-width: 800px) {
  .container {
    width: 220px;
  }
  .item:nth-of-type(5n) {
    margin-right: 5px;
  }
  .item:nth-of-type(3n) {
    margin-right: 10px;
  }
}
<div >
  <div >1</div>
  <div >2</div>
  <div >3</div>
  <div >4</div>
  <div >5</div>
  <div >6</div>
  <div >7</div>
  <div >8</div>
  <div >9</div>
  <div >10</div>
  <div >11</div>
  <div >12</div>
  <div >13</div>
  <div >14</div>
  <div >15</div>
  <div >16</div>
  <div >17</div>
  <div >18</div>
</div>

  • Related