As long as the flex container has no height itself, you can set height: 0% on the first flex item. Because it has no height to inherit from its parent, any percentage height will cause it to collapse. It will then grow with its contents.
Use the flex-grow property to make a flex item consume free space on the main axis. This property will expand the item as much as possible, adjusting the length to dynamic environments, such as screen re-sizing or the addition / removal of other items.
default flex-shrink: 1; If there's not enough space available in the container's main axis, the element will shrink by a factor of 1, and will wrap its content. flex-shrink: 0; The element will not shrink: it will retain the width it needs, and not wrap its content.
The align-items
, or respectively align-content
attribute controls this behaviour.
align-items
defines the items' positioning perpendicularly to flex-direction
.
The default flex-direction
is row
, therfore vertical placement can be controlled with align-items
.
There is also the align-self
attribute to control the alignment on a per item basis.
#a {
display:flex;
align-items:flex-start;
align-content:flex-start;
}
#a > div {
background-color:red;
padding:5px;
margin:2px;
}
#a > #c {
align-self:stretch;
}
<div id="a">
<div id="b">left</div>
<div id="c">middle</div>
<div>right<br>right<br>right<br>right<br>right<br></div>
</div>
css-tricks has an excellent article on the topic. I recommend reading it a couple of times.
When you create a flex container various default flex rules come into play.
Two of these default rules are flex-direction: row
and align-items: stretch
. This means that flex items will automatically align in a single row, and each item will fill the height of the container.
If you don't want flex items to stretch – i.e., like you wrote:
make its height the minimum required for holding its content
... then simply override the default with align-items: flex-start
.
#a {
display: flex;
align-items: flex-start; /* NEW */
}
#a > div {
background-color: red;
padding: 5px;
margin: 2px;
}
#b {
height: auto;
}
<div id="a">
<div id="b">left</div>
<div>
right<br>right<br>right<br>right<br>right<br>
</div>
</div>
Here's an illustration from the flexbox spec that highlights the five values for align-items
and how they position flex items within the container. As mentioned before, stretch
is the default value.
Source: W3C
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With