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 3 years have passed since last update.

CSSの詳細度について

Last updated at Posted at 2021-06-08

はじめに

cssで装飾する場合に詳細度というものがあり、どのCSSプロパティが適用されるかを決める手段があるのでアウトプットしていきます。

適用されるstyleについて spanタグ 

まずは簡単に記述していきます。

index.html
<!DOCTYPE html>
<html lang="en">

<head>
    <!-- 省略 -->
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <span>こんにちは! </span>
    <span>こんにちは! </span>
</body>
</html>
style.css
span {
   width: 100px;
   height: 200px;
   background-color: darkgray;
}

このような形でタグ全ての大きさや色を変える事ができます。

では1つだけ変えたい場合がどのようにするのか。
classidを使います。

適用されるstyleについて class id

index.html
    <!-- 省略 -->
<body>
    <span class="first">こんにちは! </span>
    <span id="first">こんにちは! </span>
</body>

classに名前をつけてそれだけを指定する事ができます。
ポイントはclassの場合は . が先頭に必要になります。

style.css
.first {
   width: 100px;
   height: 200px;
   background-color: darkgray;
}

またidの場合は先頭に#が必要になります。

style.css
# first {
   width: 100px;
   height: 200px;
   background-color: red;
}

今回はあえて同じ名前にしましたが同じ名前でもclassとidは別ものなので適用されます。

同じ要素に対して複数のstyleが適用された場合

index.html
<!-- 省略 -->
<body>
    <span class="first" id="second">こんにちは! </span>
    <span>こんにちは! </span>
</body>
style.css
.first {
   width: 100px;
   height: 200px;
   background-color: darkgray;
}

# second {
   width: 100px;
   height: 200px;
   background-color: red;
}

このように同じ要素に複数のstyleが適用された場合どうなるのか。

結論、*id="second"*が適用されます。

これは詳細度を元にしてどのstyleが当たるのかが決定されます。

MDN Web Docsに記載されています。

詳細度Specificityは、どの CSS プロパティが要素に最も関係があるか、すなわち適用されるかをブラウザーが決定する手段です。詳細度は様々な組み合わせの CSS セレクターで構成される一致規則に基づいています。

以下のリストは、セレクターを詳細度の小さな順に並べたものです。

  • 要素型セレクター (例えば h1) と 擬似要素 (例えば ::before)
  • クラスセレクター (例えば .example)、属性セレクター (例えば [type="radio"])、擬似クラス (例えば :hover)
  • ID セレクター (例えば #example)

以下の場合はどうなるでしょうか。

style.css
.first {
   width: 100px;
   height: 200px;
   background-color: darkgray;
}

span {
   width: 100px;
   height: 200px;
   background-color: red;
}

classの方がより詳細度があるので適用されます。

 

0
0
1

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?