Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a flex item not fill the height of the flex container? [duplicate]

Tags:

html

css

flexbox

People also ask

How do you decrease your flex height?

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.

How do you make a flex item occupy remaining space?

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.

How do I make my flex element not shrink?

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.

enter image description here Source: W3C