html - 如何让元素扩展直到其容器到达边界(使用 flex 布局)?

标签 html css layout flexbox

(跟进 this question 及其有用的答案)

我正在尝试创建带有页眉和页脚的容器,以及可以根据需要扩大/缩小的主要内容区域。事先不知道尺寸。应该允许整个东西垂直增长,直到容器使用 max-height 达到设定的限制。

理想情况下,页眉和页脚的高度永远不会改变;文章只增长到它需要显示其内容的高度,但受到其容器大小的限制。

这可以只用 CSS 实现吗?

截图

enter image description here

演示

  • 使用固定容器大小:Fiddle
  • 同上,交互:Fiddle
  • 使用 max-height 而不是 height 的损坏版本:Fiddle

HTML

<div>
    <header>header 1<br>header 2<br>header 3</header>
    <article>content 1<br>content 2<br>content 3 ...</article>
    <footer>footer 1<br>footer 2<br>footer 3</footer>
</div>

CSS

div {
    display: flex;
    flex-flow: column;
    max-height: 300px; /* this makes the article content disappear */
}
article {
    flex: 2;
    overflow: auto;
    background: gold;
}

我在 flex: 属性中尝试了各种值,包括 0%、100% 或 main-size 作为 flex-basis,但无法得到我想要的结果为。

最佳答案

看起来你没有正确使用 flexbox:

http://jsfiddle.net/7RB2h/1/

div {
    display: flex;
    flex-direction: column; /* We set the direction as column */
    width: 300px;
    max-height: 300px; /* The max height you require */
}
article {
    flex-grow: 1; /* Article will then become flex */
    overflow: auto;
    background: gold;
}

/* (colors, not important) */
div { background: #eee; }
header { background: tomato; }
article { background: gold; }
footer { background: lightgreen; }

关于html - 如何让元素扩展直到其容器到达边界(使用 flex 布局)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25105765/

相关文章:

java - 如何在 xml 布局中拉伸(stretch) Imageview 并在其左侧显示其他按钮

javascript - 在页面加载之前触发 jQuery 代码,这可能吗?

html - Bootstrap 粘性页脚

css - HTML5 : &lt;! DOCTYPE html> 更改页面布局

html - 带有选择和清除图标的 Bootstrap 搜索框

css - <div> 中的垂直居中对齐

css - 位置为 : relative 的同位素网格项

javascript - 如何隐藏多个图像容器的垂直滚动条?

javascript - 禁用 ng-autocomplete (或一般禁用 div 属性)

css - 多div居中