
今回は、固定幅の要素内で、文字が横にはみ出させずに折り返したいときに、word-wrap: break-word
と word-break: break-all
を使うことが多いかと思います。body
に記述して、すべての要素に適用するようにしていることも多いかと思います。
結局どっちがいいのか、ということを解決したいと思います。
hogehogehogehogehogehoge
↑こういうやつ
word-wrap: break-word と word-break: break-all の2つのざっくりした違い
word-wrap: break-word(overflow-wrap: break-word)
- 単語があふれないように適切な位置で改行
word-break: break-all
- 問答無用で改行
word-wrap: break-word でダメな場合
「内容が定まるまで幅の決まらない要素」がある場合に word-wrap: break-word
は効きません。
以下のような場合です(テーブルは、あふれはしませんが、固定している幅が広がってしまいます)。
display: inline-block で囲まれたラベル(バッジ)やボタン
hogehogehogehogehogehoge
テーブル
hogehogehogehogehogehoge
Flexbox(親要素が display: flex)
hogehogehogehogehogehoge
hogehogehogehogehogehoge
float や position: absolute での使用
hogehogehogehogehogehoge
hogehogehogehogehogehoge
よくある過ち
word-wrap: break-word
が効かず、安易に word-break: break-all
を使いがちになるのをよく見かけます。検索をすると、word-break: break-all
で解決しようという記事が多いからだと思います。
各ブラウザの対応を調べてみた
「○ ×」の順番:「Edge」「IE11」「Chrome(Windows、Mac、Android)」「Firefox(Windows、Mac)」「Safari(Mac、iPhone)」
未指定
英数字の連続 | 「、。…」の連続 | 「、。…」の禁則処理 | |
---|---|---|---|
内容の幅が決まる要素 | × × × × × | × × × × × | ○ ○ ○ ○ ○ |
内容が定まるまで 幅の決まらない要素 |
× × × × × | × × × × × | ○ ○ ○ ○ ○ |
word-wrap: break-word
英数字の連続 | 「、。…」の連続 | 「、。…」の禁則処理 | |
---|---|---|---|
内容の幅が決まる要素 | ○ ○ ○ ○ ○ | ○ ○ ○ ○ ○ | ○ ○ ○ ○ ○ |
内容が定まるまで 幅の決まらない要素 |
× × × × × | × × × × × | ○ ○ ○ ○ ○ |
word-break: break-all
英数字の連続 | 「、。…」の連続 | 「、。…」の禁則処理 | |
---|---|---|---|
内容の幅が決まる要素 | ○ ○ ○ ○ ○ | × × × ○ ○ | ○ ○ ○ × × |
内容が定まるまで 幅の決まらない要素 |
○ ○ ○ ○ ○ | × × × ○ ○ | ○ ○ ○ × × |
こうして見てみると、word-break: break-all
の禁則処理関連がまちまちですね。
英数字の連続の解決策
基本的に `word-wrap: break-word` のみを使用
display: inline-block
で囲まれたラベル(バッジ)やボタン
hogehogehogehogehogehoge
word-break: break-all
を指定
テーブル
hogehogehogehogehogehoge
親要素に table-layout: fixed
を指定
Flexbox
hogehogehogehogehogehoge
hogehogehogehogehogehoge
min-width
や width
を指定
float
や position: absolute
での使用
hogehogehogehogehogehoge
hogehogehogehogehogehoge
width
を指定
「、。…」の連続の解決策
- 連続することが少ないため放置
「、。…」の禁則処理
word-break: break-all;
を基本的に使用しないが、禁則処理の発生しないURLやラベルやボタン等に部分的に使用