【问题标题】:Two column flexbox layout with fixed div具有固定 div 的两列 flexbox 布局
【发布时间】:2017-09-21 20:30:00
【问题描述】:

我正在尝试学习 flexbox,我正在尝试实现以下布局。

+----------+----------+
|          |nav       |
|  header  +----------+
|          |section   |
+----------+----------+

HTML 结构

<header></header>
<nav></nav>
<section></section>

布局要求

  1. 每个元素的宽度正好是 50vw(或 50%)
  2. 标题内容始终居中且固定。占用 100vh。
  3. 导航内容已修复
  4. 部分内容可滚动,溢出被隐藏。

这甚至可以通过 flexbox 实现吗?

在移动设备上,我希望将这三个都放在一个列中,但这部分很简单。

【问题讨论】:

  • 如果你可以在容器上设置一个固定的高度,那么你的布局可以通过使用column wrap的flexbox来实现。如果无法设置高度,则需要将navsection 元素包装在嵌套容器中。如果你不能这样做,那么不,flexbox 是不可能的......
  • 你会使用 CSS Grid Layout 吗?
  • 我猜我可以将容器设置为 100vh。如果可能,我不想将 nav 和 section 包装到嵌套容器中,因此我不会使移动样式复杂化。 CSS 网格布局不起作用,我需要一些向后兼容性。

标签: html css flexbox


【解决方案1】:

body {
  display: flex;
  flex-flow: column wrap;
  height: 100vh; /* key rule; this tells flex items where to wrap
                    to form second column */
}

header {
  flex: 0 0 100%;
  width: 50%;

  /* center content */
  display: flex;
  justify-content: center;
  align-items: center;
}

nav, section {
  flex: 0 0 50%;
  width: 50%;
}

/* non-essential decorative styles */
*       { box-sizing: border-box; margin: 0; }
header  { background-color: aqua; }
nav     { background-color: tomato; }
section { background-color: lightgreen; }
<header>header</header>
<nav>nav</nav>
<section>section</section>

有关详细解释和替代方法,请参见我的回答:

【讨论】:

  • 谢谢,这几乎解决了我的问题 :-) 我有两个问题,我还没有看到一个好的解决方案。我正在阅读一些 flexbox 教程,也许我会看到解决方案。我的问题是我希望中殿有一个固定的高度,抱歉,我的问题没有说清楚。此外,当我在部分 div 中的内容溢出时,整个 div 就会消失。
  • 我认为可以解决的溢出问题。但总的来说,flexbox 并不是为构建完美的网格而设计的,因为 flex 项可以跨越 行,但不能同时跨越两者。这就是 CSS Grid 非常适合的原因,但我知道你不能使用它。请参阅我在答案末尾发布的链接以获取替代方案。
【解决方案2】:

如果你想使用 flexbox,你可以做一个双容器布局。

HTML

<div class="flex-container">
<header>Something</header>
<div class="flex-child-container">
<nav>nav</nav>
<section>section</section>
</div>
</div>

CSS

div {
display: flex;
width: 100%;
height: 100%
}

.flex-child-container {
flex-direction: column;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-30
    • 2021-12-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多