LoginSignup
2
1

More than 5 years have passed since last update.

cssのimportantぐあい

Posted at

!importantは無限にimportantになっちゃってどうしようもなくなってしまう。
そのimportantよりも少しだけimportantなimportantを表現することができない。
世の中importantなものがたくさんあるので、importantの強弱具合をうまく表現したい。

どのスタイルが適用されるのか?

class指定よりid指定が強いというのは知っていましたが、「CSS 個別性」というのを初めて知りました。
idは1個100点でclassは1個10点、合計点で判定だそうで、
じゃあ、class11個つけたらidに勝てる?と思ったら勝てない。

image

(基数が大きい数値システムで)だそうです。

<body id="important" class="important">

bodyじゃなくてもimportantじゃなくてもいいんだけど、一番上の親要素のidとclassを連打してimportant具合を表現できそうです。

<body id="important" class="important">
  <div class="x1 x2 x3">
    A
  </div>

  <div id="yyy" class="zzz">
    B
  </div>

  <a class="qqq">C</a>

  <div id="foo" class="ppp">
    <div id="bar" class="ppp">
      <div id="baz" class="ppp">
        D
      </div>
    </div>
  </div>
</body>
div{ margin: 1em; }

/* class5個で50点 */
.important.important .x1.x2.x3{ background-color: red; }

/* class4個で40点 */
.x1.x1.x1.x1{ background-color: green; }

/* class3個で30点 */
.x1.x2.x3{ background-color: blue; }



/* id2個で200点 */
#important #yyy{ background-color: red; }

/* id1個+class2個で120点 */
.important.important #yyy{ background-color: green; }

/* id1個+class1個で110点 */
#yyy.zzz{ background-color: blue; }



/* class2個 + 要素1個 = 21点 */
.important.important a{ background-color: red; }

/* class1個 + 要素1個 = 11点 */
a.qqq{ background-color: blue; }



/* id4個 = 400点*/
#important#important#important #baz{
  background-color: red;
}

/* id3個 + class3個 + 要素3個 = 333点 */
div#foo.ppp div#bar.ppp div#baz.ppp{
  background-color: blue;
}

!important=∞点 #important=100点 .important=10点

  • 困ったらとりあえずimportantをつけて手っ取り早くごまかすことができる。
  • !importantがついてて上書きできない!お手上げ状態!!を回避。#importantか.importantを連打すれば上書きできる。
2
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
2
1