1

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>
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701
takeradi
  • 3,661
  • 7
  • 29
  • 53

1 Answers1

2

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:

Community
  • 1
  • 1
Michael Benjamin
  • 346,931
  • 104
  • 581
  • 701