takeradi takeradi - 4 months ago 19
CSS Question

Limit width of children in vertical flexbox

How can I limit the child width to the content in a vertical flexbox? As you can see by the cyan background, the child width occupies the width of the container. I want it to occupy only the width that it needs.



.container{
display: flex;
background: yellow;
flex-direction: column;
padding: 5px;
}

.content{
background: cyan;
margin: 5px;
}

<div class="container">
<div class="content">hello whats up</div>
<div class="content">hello whats up</div>
</div>




Answer

An initial setting of a flex container is align-items: stretch.

This setting causes flex items to expand the full length of the container's cross axis. (This setting is what allows for equal height columns in flexbox.)

When you're in flex-direction: column the cross axis is horizontal, and children will expand the container's full width by default.

You can override the default with align-items: flex-start on the container, or align-self: flex-start on each flex item.

.container{
  display: flex;
  background: yellow;
  flex-direction: column;
  padding: 5px;
}

.content{
  background: cyan;
  margin: 5px;
  align-self: flex-start; /* NEW */
  
}
<div class="container">
  <div class="content">hello whats up</div>
  <div class="content">hello whats up</div>
</div>

References:

Comments