Prevent a child element from overflowing its parent in flexbox [duplicate]

An initial setting on flex items is min-width: auto. This means that a flex item, by default, cannot be smaller than the size of its content.

Therefore, text-overflow: ellipsis cannot work because a flex item will simply expand, rather than permit an overflow. (Scroll bars will not render either, for the same reason.)

To override this behavior, use min-width: 0 or overflow: hidden. More details.

#container {
  display: flex;
  flex-wrap: wrap;
  border: thin solid gray;
}

.card-wrapper {
  width: 33.33%;
  display: flex;
  background: #e0e0ff;
}

.card {
  flex-grow: 1;
  margin: 7px;
  display: flex;
  flex-direction: column;
  border: thin solid gray;
  background: #e0ffff;
  overflow: hidden;        /* NEW */
}

.card div {
  border: thin solid gray;
}

.card div:nth-child(1) {
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;        /* NEW */
}

.card div:nth-child(2) {
  flex-grow: 2;
}
<div id="container">
  <div class="card-wrapper">
    <div class="card">
      <div>Title</div>
      <div>Multiline<br/>Body</div>
      <div>Footer</div>
    </div>
  </div>
  <div class="card-wrapper">
    <div class="card">
      <div>Really long rambling title that pushes beyond the bounds of the container, unless your screen is really, really wide</div>
      <div>Body</div>
      <div>Footer</div>
    </div>
  </div>
  <div class="card-wrapper">
    <div class="card">
      <div>Title</div>
      <div>Body</div>
      <div>Footer</div>
    </div>
  </div>
  <div class="card-wrapper">
    <div class="card">
      <div>Title</div>
      <div>Body</div>
      <div>Footer</div>
    </div>
  </div>
  <div class="card-wrapper">
    <div class="card">
      <div>Title</div>
      <div>Body</div>
      <div>Footer</div>
    </div>
  </div>
</div>

Leave a Comment