かもメモ

自分の落ちた落とし穴に何度も落ちる人のメモ帳

CSS Flexbox の子要素内でテキストの省略 (text-overflow: ellipsis) が効かないにハマる

レスポンシブな display: flex の子要素 (flex-item) 内のテキストの省略 (text-overflow: ellipsis) がうまくできずハマったのでメモ

<div class="flex">
  <label>LABEL TEXT</label>
  <div class="content">
    <p class="text-overflow--ellipsis">{content}</p>
  </div>
</div>

Flexbox になっている要素内にあるテキスト (.text-overflow--ellipsis) が画面幅からはみ出す場合はテキストが省略 (text-overflow: ellipsis) になって欲しい

結論 : 親要素の flex-itemoverflew: hidden をつければ良い

上記の例では flex-item である div.contentoverflow: hidden があれば良い

HTML

<div class="flex">
  <label>LABEL TEXT</label>
  <div class="content overflow--hidden">
    <p class="text-overflow--ellipsis">{content}</p>
  </div>
</div>

CSS

.flex {
  display: flex;
  width: 100%;
}
.overflow--hidden {
  overflow: hidden;
}
.text-overflow--ellipsis {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

Tips flex-item 内で更に入れ子になっている場合も flex-itemoverflow: hidden をつければ良い

🙅 テキスト省略 (text-overflow: ellipsis) したい親要素が flex-item でない場合 overflow: hidden をつけてもうまく行かない

<div class="flex">
  <label>LABEL TEXT</label>
  <div class="content">
    <div class="overflow--hidden">
      <p class="text-overflow--ellipsis">{content}</p>
    </div>
  </div>
</div>

これは {content} がボックスからはみ出して描画されてしまう

🙆 直近の親は関係なくテキスト省略 (text-overflow: ellipsis) したい要素を囲っている flex-itemoverflow: hidden があれば良い

<div class="flex">
  <label>LABEL TEXT</label>
  <div class="content overflow--hidden">
    <div class="">
      <p class="text-overflow--ellipsis">{content}</p>
    </div>
  </div>
</div>

{content} がボックスからはみ出す場合は text-overflow: ellipsis が効き ... になる

Sample

See the Pen Responsive Flexbox with text-overflow 'ellipsis' by KIKIKI (@kikiki_kiki) on CodePen.

text-overflow: ellipsis の挙動結構ムズい…


[参考]