CSS
 Computer >> コンピューター >  >> プログラミング >> CSS

CSSのtext-overflowプロパティで、表示されないあふれたコンテンツをユーザーに通知する方法を指定する

CSSのtext-overflowプロパティは、要素からあふれて表示されなかったコンテンツを、ユーザーにどのように知らせるかを決定するために使用します。たとえば、あふれたテキストをそのまま切り取るか、省略記号(…)を表示して続きがあることを伝えるかなどを制御できます。

text-overflowを使うための前提条件

text-overflowプロパティを正しく機能させるには、通常以下のスタイルと組み合わせて指定します。

  • white-space: nowrap; … テキストを折り返さず、1行で表示する
  • overflow: hidden; … 要素からはみ出した部分を非表示にする
  • width … 要素の幅を固定して、あふれが発生する状態を作る

主な値の違い

  • clip:あふれたテキストを単純に切り取ります。続きのテキストがあることはユーザーには分かりません。
  • ellipsis:切り取られた位置に省略記号(…)を表示し、テキストの続きがあることを視覚的にユーザーへ通知します。

サンプルコード

以下のコードを実行すると、CSSでtext-overflowプロパティを実装した動作を確認できます。

<html>
   <head>
      <style>
         p.text1 {
            white-space: nowrap;
            width: 200px;
            border: 1px solid #000000;
            overflow: hidden;
            text-overflow: clip;
         }
         p.text2 {
            white-space: nowrap;
            width: 200px;
            border: 1px solid #000000;
            overflow: hidden;
            text-overflow: ellipsis;
         }
      </style>
   </head>
   <body>
      <b>元のテキスト:</b>
      <p>Tutorials Point originated from the idea that there exists a class of
      readers who respond better to online content and prefer to learn new skills at
      their own pace from the comforts of their drawing rooms.</p>
      <b>text-overflow: clip の場合:</b>
     
      <p class = "text1">Tutorials Point originated from the idea that there exists
      a class of readers who respond better to online content and prefer to learn
      new skills at their own pace from the comforts of their drawing rooms.</p>
      <b>text-overflow: ellipsis の場合:</b>
     
      <p class = "text2">Tutorials Point originated from the idea that there exists
      a class of readers who respond better to online content and prefer to learn
      new skills at their own pace from the comforts of their drawing rooms.</p>
   </body>
</html>

実行結果

上記コードをブラウザで表示すると、clipを指定した段落ではテキストが境界線の位置で無音に切り取られるのに対し、ellipsisを指定した段落では行末に「…」が表示され、テキストが途中で省略されていることがひと目で分かります。長いタイトルや見出しをレイアウト内に収めたい場合などに、このプロパティは非常に便利です。

CSSのtext-overflowプロパティで、表示されないあふれたコンテンツをユーザーに通知する方法を指定する

  1. CSSでスクロールバーを非表示にする方法をわかりやすく解説

    CSSでスクロールバーを非表示にする基本の方法Webページや特定の要素からスクロールバーを非表示にしたい場合、CSSのoverflowプロパティを使うのが最もシンプルな方法です。overflow: hidden;を指定すると、コンテンツが領域からあふれてもスクロールバーが表示されなくなります。実装例<!DOCTYPE html> <html> <head> <style> body { height: 150vh; width: 200vw; overflow: hidden;

  2. CSSで矢印を作成する方法!borderとrotateを組み合わせた4方向矢印の実装テクニック

    CSSでは、画像やアイコンフォント、外部ライブラリに頼らなくても、border(境界線)とtransform: rotate()を組み合わせるだけで、上下左右どの方向の矢印でも簡単に作成できます。境界線でL字型の角を作り、それを回転させるのが基本的な考え方です。 サンプルコード <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1" /> <style>