コンピュータクワガタ

かっぱのかっぱによるコンピュータ関連のサイトです

CSSの複数クラスによる絞り込み

今日、Googleのサイトの構造を見ていて、以下の様なCSSセレクタが設定されている事に気づきました。

.hoge.foo {
  // CSS
}

.hogeと.fooの間にはスペースは空いておらず連結して使われていました。

まさかと思って、CSSの仕様を確認したところ仕様として定義されていました。今日まで知りませんでした。以下、該当部分の引用です。

To match a subset of "class" values, each value must be preceded by a ".".

For example, the following rule matches any P element whose "class" attribute has been assigned a list of space-separated values that includes "pastoral" and "marine":

p.marine.pastoral { color: green }

This rule matches when class="pastoral blue aqua marine" but does not match for class="pastoral blue".

http://www.w3.org/TR/CSS2/selector.html#class-html

要は、.hoge.fooと書くとHTMLでclass="hoge foo"ないし、hogeとfooを含む要素のみに適用できるということです。

非常に簡単な例で確認してみました。

<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8">
  <title>スタイルのテスト</title>
  <style>
p.warning {
  color: red;
}

p.info {
  color: blue;
}

p.warning.info {
  background-color: yellow;
}
  </style>
 </head>
 <body>
  <p class="warning">warning</p>
  <p class="info">info</p>
  <p class="warning info">warning info</p>
 </body>
</html>

実行結果は以下です。

この辺りのベーシックな部分は殆ど知っているものと思っていましたが、まだまだ甘いようです。