これさえあれば大丈夫!「Overflow:hidden dots at the end」のサンプルコード集
HTMLとCSSにおける「Overflow:hidden dots at the end」
「Overflow:hidden dots at the end」は、HTMLとCSSを用いて、テキストが要素の幅を超えた場合に、末尾に省略記号(…)を表示するテクニックです。これは、長い見出しや文章を短く表示したい場合に有効です。
仕組み
このテクニックは、以下の2つのCSSプロパティを組み合わせて実現します。
- overflow: hidden: 要素の幅を超えたコンテンツを隠します。
- text-overflow: ellipsis: 省略記号を表示します。
コード例
<div class="text-container">
<p>This is a long text that will overflow the container.</p>
</div>
.text-container {
width: 200px;
overflow: hidden;
}
.text-container p {
text-overflow: ellipsis;
white-space: nowrap;
}
注意点
- text-overflow: ellipsis は、すべてのブラウザでサポートされているわけではありません。
- 省略記号は、テキストの最後にのみ表示されます。
- 省略記号の前に表示されるテキストの長さは、ブラウザによって異なります。
応用例
- 見出しを短く表示する
- 長い文章を要約する
- リスト項目を短く表示する
HTML
<div class="container">
<h1>This is a long heading that will overflow the container.</h1>
<p>This is a long paragraph that will also overflow the container.</p>
</div>
CSS
.container {
width: 300px;
border: 1px solid #ccc;
padding: 10px;
}
h1 {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
p {
overflow: hidden;
text-overflow: ellipsis;
}
結果
上記のコードを実行すると、以下のようになります。
This is a long heading...
This is a long paragraph...
ポイント
container
要素にwidth
プロパティを設定して、幅を制限しています。h1
要素にwhite-space: nowrap
プロパティを設定して、テキストが折り返されないようにしています。
このサンプルコードを参考に、さまざまな要素に「Overflow:hidden dots at the end」テクニックを適用してみてください。
テキストが要素の幅を超えた場合に末尾に省略記号を表示する他の方法
- text-overflow: clip: 省略記号ではなく、テキストを切り取ります。
- word-break: break-all: 長い単語を折り返します。
JavaScript
String.prototype.slice()
メソッドを使用して、テキストを必要な長さに切り取ります。...
演算子を使用して、テキストを必要な長さに切り取ります。
各方法の比較
方法 | メリット | デメリット |
---|---|---|
text-overflow: ellipsis | 簡単 | 省略記号の前に表示されるテキストの長さがブラウザによって異なる |
text-overflow: clip | 省略記号の前に表示されるテキストの長さが一定 | テキストが途切れてしまう |
word-break: break-all | 長い単語を折り返せる | 見た目が崩れることがある |
JavaScript | 柔軟性が高い | コード量が少し増える |
ライブラリ | 簡単 | ライブラリの読み込みが必要 |
html css