41
40

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 5 years have passed since last update.

隣接セレクタの使い時

Posted at

リストを並べる際に下記みたく仕切り線を引きたい。

A | B | C | D | E 

こんな表示をしたい時は隣接セレクタ「+」を使うと便利。

よく見る方法

list.html
<ul>
  <li>A</li>
  <li>B</li>
  <li>C</li>
  <li>D</li>
  <li class="last">E</li>
</ul>
style.css
li {
  display: inline-block;
  border-right: 1px solid #000;
}

li.last {
  border-style: none;
}
/*** CSS3対応ブラウザであれば .last は撤去し last-childに置き換え可能 ***
/*
li:last-child {
  border-style: none;
*/

隣接セレクタを使用した方法

list.html
<ul>
  <li>A</li>
  <li>B</li>
  <li>C</li>
  <li>D</li>
  <li>E</li>
</ul>
style.css
li {
  display: inline-block;
}

li + li {
  border-left: 1px solid #000;
}

メリット

  • クラスを付与しないので、htmlの更新が楽
  • CSS2なのでIE7にも対応ok ;)

ポイント

「最後の要素だけ打ち消し」
ではなく
「2番目以降は全て同じ」
ことに注目する。

リスト以外にも幅広く使えるので便利。

41
40
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
41
40

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?