0

So suppose I have the following HTML structure. Is there anyway I can create a responsive 'grid' type layout directly with CSS, without having to use Javascript to edit the DOM structure? As you can see by running the example, each row is displayed on a new row visually - what I would want, for example, is let's say the screen is wide enough to display 3 p elements, then that would mean that the 'visual' row display to the user would be p elements 1, 2 & 3 on row 1 (despite that fact that element 1 & 2 are in a different row class than element 3), then p elements 4, 5, 6 being on row 2 etc etc

*{
  margin: 0;
  padding: 0;
  color: white;
  font-family: sans-serif;
}

#wrapper{
  display: flex;
  flex-wrap: wrap;
  height: 100%;
  width: 100%;
  background: #333;
}

.row{
  display: flex;
  flex-wrap: wrap;
}

p{
  display: flex;
  justify-content: center;
  align-items: center;
  background: #555;
  outline: 1px solid white;
  width: 300px;
  height: 200px;
  font-size: 40px;
}
<div id='wrapper'>
  <div class='row'>
    <p>1</p>
    <p>2</p>
  </div>
  <div class='row'>
    <p>3</p>
    <p>4</p>
    <p>5</p>
  </div>
  <div class='row'>
    <p>6</p>
  </div>
  <div class='row'>
    <p>7</p>
    <p>8</p>
    <p>9</p>
    <p>10</p>
  </div>
  <div class='row'>
    <p>11</p>
    <p>12</p>
  </div>
  <div class='row'>
    <p>13</p>
    <p>14</p>
    <p>15</p>
  </div>
  <div class='row'>
    <p>16</p>
    <p>17</p>
    <p>18</p>
    <p>19</p>
    <p>20</p>
  </div>
</div>

I think it should be obvious what I am trying to achieve, but I know for myself, I find it much easier to visualise the desired result, rather than trying to understand what is desired from a description...so here is what I am trying to go for:

*{
  margin: 0;
  padding: 0;
  color: white;
  font-family: sans-serif;
}

#wrapper{
  height: 100%;
  width: 100%;
  background: #333;
}

.group{
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
}

p{
  display: flex;
  justify-content: center;
  align-items: center;
  background: #666;
  outline: 1px solid white;
  width: 300px;
  height: 200px;
  font-size: 40px;
}
<div id='wrapper'>
  <div class='group'>
    <p>1</p>
    <p>2</p>
    <p>3</p>
    <p>4</p>
    <p>5</p>
    <p>6</p>
    <p>7</p>
    <p>8</p>
    <p>9</p>
    <p>10</p>
    <p>11</p>
    <p>12</p>
    <p>13</p>
    <p>14</p>
    <p>15</p>
    <p>16</p>
    <p>17</p>
    <p>18</p>
    <p>19</p>
    <p>20</p>
  </div>
</div>

So I'm wondering, is there any way I could achieve this purely in CSS? Thanks!

Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
A Question
  • 26
  • 2

0 Answers0