Skip to content Skip to sidebar Skip to footer

Fitting Child Into Parent

I have nested flex elements with a text at the bottom. The top element has fixed width that is smaller than text: I can fix this by applying overflow: hidden; to all elements: Bu

Solution 1:

An initial setting on flex items is min-width: auto. This means that flex items cannot be shorter than the width of their content.

You have white-space: nowrap on the text element. As a result, all flex item ancestors must expand (in a domino effect) to accommodate the length of the text.

The affected flex items are:

  • .list-component
  • .header-container
  • .header-text

Therefore, in order to prevent the text from overflowing the primary container, you need to override the min-width: auto default. The flexbox spec provides two methods for doing this:

  1. Add min-width: 0 to flex items
  2. Add overflow with any value other than visible to flex items. (This is why you were able to fix the problem by adding overflow: hidden. It's actually a clean and valid solution.)

This behavior is explained in more detail in this post:

.list-header {
  display: flex;
  width: 150px;
  height: 80px;
  background-color: #ececec;
}

.list-component {
  display: flex;
  flex: 1;
  padding-left: 24px;
  padding-right: 24px;
  min-width: 0;         /* NEW */
}

.header-container {
  display: flex;
  flex: 1;
  min-width: 0;         /* NEW */
}

.header-text {
  display: flex;
  flex-direction: column;
  justify-content: center;
  min-width: 0;         /* NEW */
}

span {
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}
<div class="list-header">
  <div class="list-component">
    <div class="header-container">
      <div class="header-text">
        <span>long long long long long long text</span>
      </div>
    </div>
  </div>
</div>

Post a Comment for "Fitting Child Into Parent"