如何实现这个嵌套的flexbox

fro*_*end -1 html css flexbox

[![查看布局][1]: https://i.stack.imgur.com/AJABl.png

我的弹性容器的左右弹性基础均为 50%。现在我想实现左 Flex 在第一行有两个输入,每个输入在单独的行中,如何设计布局?

tac*_*shy 5

不要flex-basis在这里使用。简单的解决方案是将输入的宽度设置为 100%。然后使用 来寻址前 2 个输入:nth-child(-n +2)。给它们一个不同的宽度,其计算公式为(100% - gap-width) / 2(也适用于:nth-child(n + 3)):

:root {
  --gap: 1rem;
}

section {
  display: flex;
  flex-wrap: wrap;
  gap: var(--gap);
}

input {
  box-sizing: border-box;
  width: 100%;
}

input:nth-child(-n + 2) {
  width: calc((100% - var(--gap)) / 2);
}
Run Code Online (Sandbox Code Playgroud)
<section>
  <input placeholder="firstname">
  <input placeholder="lastname">
  <input placeholder="email adress">
  <input placeholder="phone number">
</section>
Run Code Online (Sandbox Code Playgroud)

@OskarGrosser 提到你也可以使用 CSS Grid 来实现这一点。虽然您的问题专门询问了 Flexbox,但考虑到兼容性和使用/工作量,我不认为这是更好的解决方案。

在网格布局中,您可以使用 . 创建一个 2 列网格display: grid; grid-template-columns: repeat(2, 1fr);。然后,您可以使用 使除前 2 个输入之外的每个输入跨越 2 列grid-column: span 2。为此,您可以将上面提到的nth-child选择器与:not选择器结合起来。

:root {
  --gap: 1rem;
}

section {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: var(--gap);
}

input:not(:nth-child(-n + 2)) {
  grid-column: span 2;
}
Run Code Online (Sandbox Code Playgroud)
<section>
  <input placeholder="firstname">
  <input placeholder="lastname">
  <input placeholder="email adress">
  <input placeholder="phone number">
</section>
Run Code Online (Sandbox Code Playgroud)