Large first item with a flexbox layout?

南楼画角 提交于 2019-12-05 06:54:49

So it's pretty clear that flexbox can't produce a layout like this. So I'll answer this part of the question:

If not, then I would be interested in a CSS grid workaround

With the CSS Grid Layout Module this is surprisingly easy to produce:

Basically the relevant code boils down to this:

Codepen Demo (Resize to see the effect)

ul {
  display: grid; /* (1) */
  grid-template-columns: 120px 120px repeat(auto-fill, 120px); /* (2) */
  grid-template-rows: repeat(auto-fill, 150px); /* (3) */
  grid-gap: 1rem; /* (4) */
  justify-content: space-between; /* (5) */
}
li:first-child {
  grid-column: 1 / 4; /* (6) */
  grid-row:  1 / 3; /* (7) */
}

1) Make the container element a grid container

2) Set the grid with at least 3 columns of width 120px. (The auto-fill value is used for responsive layouts).

3) Set the grid with 150px high rows.

4) Set gaps/gutters for the grid rows and columns - here, since want a 'space-between' layout - the gap will actually be a minimum gap because it will grow as necessary.

5) Similar to flexbox.

6) occupy the first three columns

7) occupy the first two rows

body {
  margin: 0;
}
ul {
  display: grid;
  grid-template-columns: 120px 120px repeat(auto-fill, 120px);
  grid-template-rows: repeat(auto-fill, 150px);
  grid-gap: 1rem;
  justify-content: space-between;
  
  /* boring properties: */
  list-style: none;
  width: 90vw;
  height: 90vh;
  margin: 4vh auto;
  border: 5px solid green;
  padding: 0;
  overflow: auto;
}
li {
  background: tomato;
  min-height: 150px;
}
li:first-child {
  grid-column: 1 / 4;
  grid-row:  1 / 3; 
}
<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
  <li>7</li>
  <li>8</li>
  <li>9</li>
  <li>10</li>
  <li>11</li>
  <li>12</li>
  <li>13</li>
  <li>14</li>
  <li>15</li>
  <li>16</li>
  <li>17</li>
  <li>18</li>
  <li>19</li>
  <li>20</li>
</ul>


Browser Support - Caniuse

Currently supported by Chrome (Blink) and Firefox, with partial support from IE and Edge (See this post by Rachel Andrew)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!