CSS特異性は、同じ要素に対して複数の宣言が競合する場合、ブラウザによって適用されるスタイル宣言を決定する一連のルールです。 CSSセレクターの特異性は、さまざまなタイプのセレクターの重みが異なる4部構成のランキングシステムを使用して計算されます。
1,0,0,0
.これは!important
によって上書きされない限り、どのインラインスタイルも外部または内部のスタイルシートで定義されたスタイルをオーバーライドすることを意味します。0,1,0,0
.たとえば、 #navbar
の特異性は0,1,0,0
です。0,0,1,0
です。 Examples include .btn
, [type="text"]
, and :hover
.0,0,0,1
で表されます。 Examples include div
, p
, and ::before
.特異性を比較すると、値は左から右に比較されます。たとえば、 0,1,0,0
の特異性を持つセレクターは0,0,1,0
の特異性を持つセレクターに常に勝ちます。 2つのセレクターが同じ特異性を持っている場合、CSSコードの後半に表示されるものが適用されます。
いくつかの要因は、CSSセレクターの特異性に影響します。
div#navbar
combines an element selector ( div
) with an ID selector ( #navbar
), resulting in a specificity of 0,1,0,1
.!important
!important
特異性が高いCSSスタイルをオーバーライドするには、いくつかの戦略を採用できます。
.btn
(specificity 0,0,1,0
), you could use .container .btn
(specificity 0,0,2,0
), or #navbar .btn
(specificity 0,1,1,0
).#navbar
has a higher specificity than .navbar
.!important
: As a last resort, you can use the !important
declaration to override other styles. For example, color: blue !important;
will override any other color
declarations for that element.ただし、 !important
を使用することは、一般的にメンテナンスの問題につながる可能性があるため、一般的に落胆します。はい、CSSの特異性を管理するために!important
。 When a property is declared with !important
, it overrides any other declaration for the same property, regardless of the specificity of the selectors.
ただし、考慮すべき重要な意味があります。
!important
を使用すると、CSSの維持が難しくなります。 If multiple developers are working on the same project, they may not be aware of existing !important
declarations, leading to unexpected behavior.!important
は、開発者がますます多くの!important
宣言を追加して以前の宣言を加えて、逆効果であり、管理できないCSSにつながる可能性があります。!important
can disrupt the normal flow of CSS inheritance, making it harder to predict how styles will cascade.!important
goes against CSS best practices, which advocate for well-structured, modular CSS that can be easily managed without resorting to such overrides.結論として、 !important
は、特定の状況(サードパーティのライブラリスタイルを無効にするなど)で有用なツールになる可能性がありますが、控えめに慎重に使用する必要があります。より良いアプローチは、必要に応じてより具体的なセレクターを使用して、そのようなオーバーライドの必要性を最小限に抑える方法でCSSを構築することです。
以上がCSS特異性はどのように計算されますか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。