treznik
treznik

Reputation: 8134

Stretch flex parent to (variable) children width in scrollable container

Here's what I have (from outer to inner):

  1. A parent element with overflow: scroll and fixed width.
  2. A vertical list of elements with variable width
  3. List items have display: flex and flex-direction: row
  4. Inside each list item there is an icon and a label side by side horizontally

I want the list items to take as much width as they need to container their flexed children, as the root parent is scrollable. I can make the icon and label take as much width as they need with flex-shrink: 0.

Problem is: List items (#3 in the list above) have their width limited to the width of the scrollable parent container, instead of their children.

This is bad because list items have padding and a colored background. Here is an example on CodePen. Scroll horizontally where it says "Lorem ipsum" to see what I mean.

Thanks!

Upvotes: 1

Views: 1258

Answers (1)

Temani Afif
Temani Afif

Reputation: 274355

Simply make list an inline-block element and it won't get limited by its parent width and will expand to fit the longest item:

.nav {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  width: 200px;
  background: #f1f1f5;
  overflow: scroll;
}
.list {
  display:inline-block;
}

.item-container {
  padding: 0 16px;
  background: #222225;
  color: #e1e1e8;
}

.item {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.icon {
  flex-shrink: 0;
}

.label {
  flex-shrink: 0;
  white-space: nowrap;
}
<div class="nav"> 
  <div class="list">
    <div class="item-container">
      <div class="item">
        <div class="icon">🎄</div>
        <div class="label">Lorem ipsum dolor sit amet yata yata yata</div>
      </div>
    </div>
    <div class="item-container">
      <div class="item">
        <div class="icon">🎄</div>
        <div class="label">Lorem ipsum</div>
      </div>
    </div>
  </div>
</div>

Upvotes: 1

Related Questions