首页 > 解决方案 > 我如何获得这个布局(使用 CSS flexbox)?

问题描述

我有以下标记:

<div class="container">
    <div class="strip">
    </div>
    <div class="content">
    </div>
    <div class="footer">
    </div>
</div>

我试图弄清楚我需要添加什么 CSS 以使内容区域填充条带或页脚未占用的任何垂直空间。

请注意,容器position: fixed带有top: 0和 ,bottom: 0因此容器占据了浏览器窗口高度的 100%。此外,条带具有设定的高度,但页脚没有(也不能,因为内容有些动态)。但是,我希望页脚占用所需的最小空间,并让内容区域填满页面上其余的垂直空间。

我在想我需要使用 flexbox 来做到这一点,但我不确定。

这是我到目前为止的CSS:

.container {
    bottom: 0;
    left: 0;
    position: fixed;
    top: 0;
}

.strip {
    background: red;
    height: 5px;
}

.content {
}

.footer {
}

标签: htmlcsslayoutflexboxvertical-alignment

解决方案


我希望这是您想要的 :) 没有widthright设置您的容器基本上将具有 0 宽度。.strip位于容器的开头和.footer结尾。.content允许拉伸,但不会比他的邻居拉伸得更多,如果没有这个flex-grow属性,当分配正的可用空间时,该属性决定了弹性项目相对于弹性容器中的其余弹性项目将增长多少。

.container {
  bottom: 0;
  left: 0;
  position: fixed;
  top: 0;
  right: 0;
  display: flex;
  flex-direction: column;
}

.strip {
  justify-self: flex-start;
  background: red;
  height: 5px;
}

.content {
  justify-self: stretch;
  background: blue;
  flex-grow: 1;
}

.footer {
  justify-self: flex-end;
  background: yellow
}
<div class="container">
  <div class="strip">
  </div>
  <div class="content">
    test
  </div>
  <div class="footer">
    footer
  </div>
</div>


推荐阅读