1
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 1 year has passed since last update.

CSSスタイルの優先順位(詳細度)の基本概念

Last updated at Posted at 2022-05-23

優先順位(詳細度)の基本概念

それぞれ0から始まる4つのスロットで構成されてます。
0 0 0 0
左スロットが1番強く、右スロットが1番弱く、10進法のように機能します。
例)1000は0100より大きいです。

優先順位の点数と計算方法

スロット1

セレクタがタグ、擬似要素の場合このスロットに増加します、複数の場合どんどん加算します。

slot1
p {}             /* 0 0 0 1 */
span {}          /* 0 0 0 1 */
p span {}        /* 0 0 0 2 */
p > span {}      /* 0 0 0 2 */
div p > span {}  /* 0 0 0 3 */

スロット2

classセレクタ、属性セレクタの場合このスロットに増加します、複数の場合どんどん加算します。

slot2
.name {}                /* 0 0 1 0 */
.users .name {}         /* 0 0 2 0 */
[href$='.pdf'] {}       /* 0 0 1 0 */
:hover {}               /* 0 0 1 0 */
.pictures img:hover {}  /* 0 0 2 1 */

スロット3

idセレクタの場合このスロットに増加します、CSSファイル内の記述では一番強いです。

slot3
#name {}          /* 0 1 0 0 */
.users #name {}   /* 0 1 1 0 */
#name span {}     /* 0 1 0 1 */

スロット4

インラインCSSはCSSファイル内の記述より優先されます。

slot4
<p style="color: red;">名前</p>

例外

必殺技 !importantだけは例外でどのスタイルよりも優先されます。
あまり使うことをお勧めしません。

点数表

指定方法 点数
style属性 style="color: red;" 1000点
ID #hoge 100点
クラス .hoge 10点
属性セレクタ a[href*="google"] 10点
要素名(タグ) ul 1点
擬似要素 :first-child 1点
ユニバーサルセレクタ * 0点

参考

http://creator.aainc.co.jp/archives/4947
https://www.w3.org/TR/CSS21/cascade.html#specificity

1
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
1
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?