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?

リセットCSS・ノーマライズCSSは@layerで囲うといいよ。という提案

Posted at

課題

以下のHTMLでは可読性のため、

  • reset.cssまたはnormalize.css
  • style.css

にわけて記載するCSSをstyleタグに集約して記載していますが、分けていても同じ結果になります。

例えば、以下のHTMLコードにおいて「Link Text」はコメントにある通り「赤太文字」で記載されます。

a:linkへの書き方はリセットCSSでも見かける記述です。また、詳細度を比較すると「0-1-1」と「0-1-0」なので赤太文字が適用されるのはおかしくありません。
しかし、ページの編集者としては下の「青イタリック体」を適用してほしい、という状況が多いと思います。
なぜなら、リセットCSS・ノーマライズCSSは「共通CSSやページ側のCSSで何も指定していないときに適用されるスタイル」を定義するファイルだからです。

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>@layerのテスト</title>
  <style>
    /* リセットCSS または ノーマライズCSS */
    /* 赤太文字 → こちらが適用される */
    a:link,
    a:active,
    a:visited{
      color: red;
      font-weight: bold;
    }

    /* ページ用のCSS */
    /* 青イタリック体 */
    .inlineLink{
      color: blue;
      font-style: italic;
    }
  </style>
</head>
<body>
  <a class="inlineLink" href="https://example.com">Link Text</a>
</body>
</html>

解決策

以下のように無名の@layerで囲うと「青イタリック体」が適用されます。
@layerで囲ったルールと囲っていないルールでは、詳細度に関係なく囲っていないルールが優先されるからです。
!importantしたときは別ですが。
名前付きにして、共通CSSなどでレイヤーの順番をあらかじめ定義しておいてもいいかと思います。

<!DOCTYPE html>
<html lang="ja">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>@layerのテスト</title>
  <style>
    /* リセットCSS または ノーマライズCSS */
-   /* 赤太文字 → こちらが適用される */
+   /* 赤太文字 */
+ @layer {
    a:link,
    a:active,
    a:visited{
      color: red;
      font-weight: bold;
    }
+ }

-   /* ページ用のCSS */
+   /* ページ用のCSS → こちらが適用される */
    /* 青イタリック体 */
    .inlineLink{
      color: blue;
      font-style: italic;
    }
  </style>
</head>
<body>
  <a class="inlineLink" href="https://example.com">Link Text</a>
</body>
</html>

以上

参考

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?