css強さ選手権
1. そもそも強さって?基本的にhtmlやjavascript等は, 後に書いたものが優先されて反映される. cssも同様なのだが, たとえば
<div class="test_1" id="mytest_1">
テスト1
</div>
<style>
#mytest_1{color: red;}
.test_1{color: blue;}
</style>
このように書いたとき, どちらも同じdivを指すため, 基本にのっとれば文字は, あとに指定した通り青くなるはず
しかし,
テスト1
赤くなる( ゚д゚ )
これが, 強さによってcssが上書きされる現象である.
2. 強さの順位
では順位はどうなっているのか
| 順位 | 名前 | 例 |
|---|---|---|
| 1位 | 直書き | <div style="width: 100%"></div> |
| 2位 | id | #id |
| 3位 | class | .class |
| 3位 | 属性セレクタ | img[alt] |
| 3位 | 疑似クラス | li:first-child |
| 6位 | 要素名 | body |
| 7位 | 全選択 | * |
だいたいこんな感じ
但し単体での強さでの話
組み合わせることで
<div class="test_2" id="mytest_2">
テスト2
</div>
<style>
div.test_2{color: red;}
.test_2{color: blue;}
</style>
テスト2
あとに書いたはずの青ではなく, 先に書いた赤になる. これは, それぞれの指定が
赤 → 要素名(6位) + クラス名(3位)
青 → クラス名(3位)
となっており、より多く条件を付けた方が強く反映されるのである.
ちなみに強さを重ねて同列だった場合は…?
<div class="test_3 test_4" id="mytest_3">
テスト3
</div>
<br />
<style>
.test_3.test_4{color: red;}
.test_3[id]{color: blue;}
</style>
テスト3
赤 → クラス名(3位) + クラス名(3位)
青 → クラス名(3位) + 属性セレクタ(3位)
とした実験。結果は下に書いた青の勝利
最後の実験。classを重ねたらidに勝てるのか?
<div class="test_4 test_5 test_6 test_7 test_8 test_9 test_10" id="mytest_4">
テスト4
</div>
<style>
#mytest_4{color: red;}
.test_4{color: blue;}
.test_4.test_5{color: blue;}
.test_4.test_5.test_6{color: blue;}
.test_4.test_5.test_6.test_7{color: blue;}
.test_4.test_5.test_6.test_7.test_8{color: blue;}
.test_4.test_5.test_6.test_7.test_8.test_9{color: blue;}
.test_4.test_5.test_6.test_7.test_8.test_9.test_10{color: blue;}
.test_4.test_5.test_6.test_7.test_8.test_9.test_10[id]{color: blue;}
</style>
結果は…
テスト4
…うん(・ω・`)
まず一番強いやつがさらっていくんだね…
3. おまけ
それでも上の奴に勝ちたい、そんなcssに最終兵器。
<div class="test_11" id="mytest_5">
テスト5
</div>
<style>
#mytest_5{color: red;}
.test_11{color: green!important}
</style>
idとclassの一騎打ち。但しclassには!importantが設定されている。これが切り札。
テスト5
と、クラスによる指定にも関わらず緑になっている。後に設定したimportantのおかげだけど、あくまで最終手段。これは、<div class="test_12" id="mytest_6">
テスト6
</div>
<style>
#mytest_6{color: red;!important}
.test_12{color: green!important}
</style>
テスト6
からわかる通り、強さの順位どうこうをなくし、単純に書かれた順に上書きになっていく模様。ちなみに
<div class="test_13" id="mytest_7">
テスト7外
<div class="test_14" id="mytest_8">
テスト7
</div>
</div>
<style>
#mytest_7{color: red;!important}
.test_14{color: green}
</style>
テスト7外
さすがに親の影響より、直接指定されたものが優先されるみたい。
テスト7
css等はこの場で実験もできるから面白い+(・ω・0)*