LoginSignup
1
1

More than 5 years have passed since last update.

CSSのnext-sibling combinator

Posted at

A + Bというセレクタは、Aの兄弟でAの直後にあるBにマッチする。

/* .fooの直後にある.barのcolorをredにする。 */
.foo + .bar {
  color: red;
}
<div class="foo">foo</div>
<div class="bar">bar</div>
<div class="bar">bar</div>

デモ

+next-sibling combinator(※1)という名前である。直訳すれば「次兄弟組合せ子」だろうか。

※1 昔の仕様書ではadjacent sibling combinatorと呼ばれていた。日本語の資料では「隣接兄弟結合子」や「隣接セレクタ」と呼ばれているのをよく見る。

よくある使い道

同種の要素が連続している状況で、要素間の間隔を空けたり、要素間にボーダーを引くときによく使う。

/* .fooが連続しているとき、2つ目以降の.fooの上マージンを20pxにする。 */
.foo + .foo {
  margin-top: 20px;
}
<div class="foo">foo</div>
<div class="foo">foo</div>
<div class="foo">foo</div>

デモ

上記のCSSは、SCSSだと次のようにも書ける。

.foo {
  & + & {
    margin-top: 20px;
  }
}
1
1
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
1
1