带有flexbox布局的大型第一项?

Dan*_*eld 6 css flexbox css-grid

我有一个布局,包含一个包含一堆项目的有序列表.

所有项目都具有一致的宽度和高度 - 除了第一项 - 宽(3x)和(2x)更高.它看起来像这样:

在此输入图像描述

ol {
  padding:0;
  margin:0;
  min-width: 488px;
}
li {
  list-style: none;
  width: 150px;
  padding-bottom: 16.66%;
  border: 5px solid tomato;
  display: inline-block;
}
li:first-child {
  float:left;
  width: 478px;
  border-color: green;
  padding-bottom: 34.25%;
  margin: 0 4px 4px 0;
}
Run Code Online (Sandbox Code Playgroud)
<ol>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
  <li></li>
</ol>
Run Code Online (Sandbox Code Playgroud)

Codepen演示(调整视口大小以查看效果)

目前,我正在使用浮动和内联块来实现布局,但我想使用flexbox,因为flexbox提供了一些额外的功能.

我做了几次尝试,但没有成功 -

尝试#1 - Codepen

ol {
  /* ... */
  display: flex;
  flex-wrap: wrap;
}
Run Code Online (Sandbox Code Playgroud)

尝试#2 - Codepen

在列表前使用浮动以确保第一个大型列表项的空间

然后在第一个列表项上设置显示绝对值.

在两次尝试中,第一行中的红色框都会拉伸以填充第一个项目的高度.

这可能吗?

(如果没有,那么我会对CSS网格解决方案感兴趣)

Dan*_*eld 5

因此,很明显,flexbox无法产生这样的布局。因此,我将回答问题的这一部分:

如果没有,那么我会对CSS网格解决方法感兴趣

使用CSS网格布局模块,可以轻松实现以下目的:

基本上,相关代码可以归结为:

Codepen演示(调整大小以查看效果)

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) */
}
Run Code Online (Sandbox Code Playgroud)

1)使容器元素成为网格容器

2)设置至少3列宽度为120px的网格。(该auto-fill值用于响应式布局)。

3)将网格设置为150px高的行。

4)为网格的行和列设置间隙/装订线-在这里,由于需要“间隔”布局-间隙实际上是最小间隙,因为它会根据需要增大。

5)类似于flexbox。

6)占据前三列

7)占据前两行

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) */
}
Run Code Online (Sandbox Code Playgroud)
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; 
}
Run Code Online (Sandbox Code Playgroud)


浏览器支持-Caniuse

目前受Chrome(Blink)和Firefox支持,IE和Edge支持部分支持(请参阅Rachel Andrew的这篇文章