LoginSignup
26

More than 5 years have passed since last update.

CSS を使って長文最後を「・・・」で省略する方法(複数行対応)

Last updated at Posted at 2016-11-14

CSS を使って長文最後を「・・・」で省略する方法(複数行対応)

単行だと簡単にかけたり、-webkit対応だと簡単にかけたりするのだが、
色々なブラウザでの複数行だとちょっと面倒だったのでメモ。

対応方法

htmlに長文を用意

<p class="cut_txt">長文xx~xx。<p>

上記htmlの長文に対応するCSSを用意

.cut_txt {
    position: relative;
    overflow: hidden;
    /** 行数設定 **/
    height: 3em;
    line-height: 1.5;
}
.cut_txt:before, .cut_txt:after {
    position: absolute;
    /** 塗りつぶし背景色 **/
    background: #f7f6ec;
}
.cut_txt:before {
    /** 語尾文字 **/
    content: "・・・";
    bottom: 0;
    right: 0;
}
.cut_txt:after {
    content: "";
    width: 100%;
    height: 100%;
}

最初に、height と line-height を指定して何行表示するかを決めます。
後は overflow: hidden; して隠します。

:before というのが「・・・」文字を表示する擬似要素です。
bottom と right を指定して強制的に右下に置きます。(absoluteで絶対位置になる)

:after 擬似要素は、「・・・」を消す用の疑似要素です。
親要素の最後から要素と同じ幅と高さを背景色で隠します。
文字列が短い場合に「・・・」を隠します。
文字列が長い場合は見えない領域を背景色で隠します。(元から隠れてますが・・・)

サンプル

1.森のくまさん(short ver):末尾まで行かない場合。
2.森のくまさん(改行 ver):複数行で3行以上の場合。(改行有り)
3.森のくまさん(full ver):複数行で3行以上の場合。(改行無し)
css.png

欠点

・途中で改行されている場合でも「・・・」が右下に離れて存在する。
・「・・・」が絶対位置なので、文字の途中でも関係なく「・・・」になります。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
26