0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

インライン要素をCSSだけで区切って表示する方法

Last updated at Posted at 2020-08-07

例えば次のようなHTML要素があったとします。

<div class="contents">
  <span>テキスト1</span>
  <span>テキスト2</span>
  <span>テキスト3</span>
  <span>テキスト4</span>
</div>

必ずテキストが存在する要素のみで構成されたHTMLであれば次のCSSで問題ありません。

.contents > span:not(:nth-child(1))::before {
  content: "、"
}

結果
テキスト1、テキスト2、テキスト3、テキスト4

class="contents"の配下のspanタグの先頭要素を除く、全ての要素の直前に読点を表示させるというCSSになります。

しかし、次のように要素数は決まっているが、値が入っているかどうかはランダムである場合はどうでしょう?

パターン①

<div class="contents">
  <span>テキスト1</span>
  <span></span>
  <span>テキスト3</span>
  <span></span>
</div>

結果
テキスト1、、テキスト3、

本当はこうなってほしい
テキスト1、テキスト3

パターン②

<div class="contents">
  <span></span>
  <span>テキスト2</span>
  <span></span>
  <span>テキスト4</span>
</div>

結果
テキスト2、、テキスト4

本当はこうなってほしい
テキスト2、テキスト4

そのような場合はこのCSSを試してください

.contents > span:not(:empty) ~ span:not(:empty)::before {
  content: "、"
}

E ~ Fは、E要素の後ろにある同じ階層のF要素にスタイルを適用する際に使用します。
http://www.htmq.com/selector/precede.shtml
テキストが存在するspanタグの後ろにある同じ階層の全てのspanタグでテキストが存在ものに対して、
その要素の直前(疑似要素:before)に読点を表示するというのがこのCSSの内容になります。

0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?