5
3

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

はじめに

CSSのセレクタによって、どちらのスタイルの指定が優先されるのかにはルールがあります。
「id > class > 要素名」の順に優先されます。

例えば、

<!doctype html>
<style>
  #bar { color: red; }
  .foo { color: green; }
  p    { color: blue; }
</style>
<p class=foo id=bar>TEST

このような、HTMLの場合、「TEST」の文字は赤く表示されます。
ここまでは基礎なのでたぶん誰でも知ってると思います。

属性セレクタ

CSS3から属性セレクタというものが使えます。
elemName[attrName=attrValue]のようなやつです。

今までは、属性セレクタで優先順位は変化しないものだと勝手に思っていました。
実際に書いてみたところ、

<!doctype html>
<style>
  .foo      { color: red; }
  [data-my] { color: blue; }
</style>
<p class=foo data-my=bar>TEST

このHTMLでは「TEST」の文字が青く表示されます。
どうやら、属性セレクタの優先順位はclassの指定と同じなんですね。

仕様

仕様を調べてみたら、普通に書かれてました。当然ですよね。
(それにしても、仕様にあるidは100倍、classは10倍の例えは間違っているので、いい加減修正すべきだと思う)

  • count the number of ID selectors in the selector (= a)
  • count the number of class selectors, attributes selectors, and pseudo-classes in the selector (= b)
  • count the number of type selectors and pseudo-elements in the selector (= c)
  • ignore the universal selector
  1. IDセレクタ
  2. classセレクタ、属性セレクタ、疑似クラスセレクタ
  3. 要素名セレクタ(この名称でいいのかな)、疑似要素セレクタ

の順ですね。

5
3
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
5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?