0
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で同じclass名を何度も指定すると優先順位が変わる

Posted at

状況

調べものをしている最中、以下のようなclass指定の記述を見つけた。

.larger-text.larger-text{
  font-size: 32px;
}

なんで???

なぜ同じclass名を何度も指定しているんだろう...

実験

実際にcssを書いてみて挙動を確かめたいと思います。

上記サイトにアクセス後、下記のcssをコピペ

.larger-text {
  font-size: 32px;
}

/* スタイル1 */
@media only screen and (max-width: 620px) {
  .larger-text.larger-text.larger-text.larger-text.larger-text.larger-text {
    font-size: 16px;
    color: red;
  }
}

/* スタイル2 */
@media only screen and (max-width: 620px) {
  .larger-text.larger-text {
    font-size: 48px;
    color: blue;
  }
}

「スタイル1」と「スタイル2」、画面幅を620px以下にした場合にどちらが優先されるかを調べると、結果は以下のようになった。

621px以上
image.png

620px以下
image.png

スタイル1が優先された。

次に、スタイル2で指定するclass名を増やして実験するため、以下のように修正する。

.larger-text {
  font-size: 32px;
}

/* スタイル1 */
@media only screen and (max-width: 620px) {
  .larger-text.larger-text {
    font-size: 16px;
    color: red;
  }
}

/* スタイル2 */
@media only screen and (max-width: 620px) {
  .larger-text.larger-text.larger-text.larger-text.larger-text.larger-text {
    font-size: 48px;
    color: blue;
  }
}

以下のように表示された。

621px以上
image.png

620px以下
image.png

結論

重複したclass名をスタイルに適用した場合、より多くのclass名を記述した方が優先される。

!importantを使いたくない場合などに使えるかもしれない...?
使いどころは模索中です

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