How to let an element expand until its container r

2020-07-18 04:53发布

(following up on this question and its helpful answer)

I'm trying to create container with a header and a footer, and a main content area which can grow/shrink as necessary. No sizes are known in advance. The whole thing should be allowed to grow vertically until the container hits a set limit using max-height.

Ideally, the header and footer height never change; the article grows only as high as it needs to display its contents, but is limited by the size of its container.

Can this be achieved with only CSS?

Screenshot

enter image description here

Demo

  • working with a fixed container size: Fiddle
  • same as above, interactive: Fiddle
  • broken version using max-height instead of 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;
}

I've tried various values in the flex: property, including 0%, 100%, or main-size as the flex-basis, but couldn't get the result I'm looking for.

1条回答
一夜七次
2楼-- · 2020-07-18 05:50

Looks like your are not using flexbox properly:

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; }
查看更多
登录 后发表回答