Kekhususan CSS dan Bilakah Menggunakan Tag Penting CSS

Kekhususan CSS adalah topik penting untuk difahami jika anda ingin menjadi lebih baik di CSS. Ini adalah set peraturan yang diterapkan pada pemilih CSS yang menentukan gaya mana yang diterapkan pada elemen.

Untuk memahami perkara ini dengan lebih baik, penting bagi kita untuk memahami topik yang berkaitan - merangkumi CSS.

Cascading Nature of CSS

CSS bermaksud Cascading Style Sheets. "Cascading" bermaksud bahawa susunan peraturan CSS yang diterapkan pada elemen penting .

Sebaik-baiknya, jika dua peraturan diterapkan pada elemen yang sama, yang terakhir akan digunakan adalah yang akan digunakan. Mari gunakan contoh untuk memahami perkara ini.

Kami akan menerapkan dua kelas pada elemen dan memberi setiap kelas berbeza background-color.

This is a test paragraph

Inilah CSS:

.style2 { background-color: red; } .style1 { background-color: yellow; }

Inilah hasilnya:

Perhatikan bahawa style1yang terakhir muncul dalam helaian gaya diterapkan pada elemen. Sekarang anda mungkin mengharapkan agar CSS menerapkan gaya pada elemen, tetapi tidak selalu berlaku.

Ambil contoh berikut.

This is a test paragraph

CSS kelihatan seperti ini:

#paragraph { background-color: red; } .style1 { background-color: yellow; }

Gaya mana yang anda harapkan untuk diterapkan pada elemen tersebut? The #paragraphatau yang .style1?

Inilah hasilnya:

Perhatikan bahawa yang pertama digunakan. Ini #paragraphadalah pemilih id, sementara style1pemilih kelas. Ini kerana lata berfungsi dengan spesifik untuk menentukan nilai mana yang diterapkan pada elemen.

Jadi, apakah kekhususan CSS?

Kekhususan CSS dijelaskan

Menurut MDN, Kekhususan adalah cara penyemak imbas memutuskan nilai harta CSS mana yang paling relevan dengan elemen dan, oleh itu, akan diterapkan.

Ringkasnya, jika dua pemilih CSS berlaku untuk elemen yang sama, yang menggunakan kekhususan yang lebih tinggi digunakan.

Itulah sebabnya dalam contoh sebelumnya, nilai harta tanah pemilih id digunakan kerana mempunyai nilai kekhususan yang lebih tinggi.

Jadi bagaimana pengkhususan pemilih dikira?

Hierarki Kekhususan

Mengira nilai kekhususan pemilih agak sukar. Salah satu cara untuk menghitungnya adalah dengan menggunakan sistem berat untuk memberi peringkat kepada pemilih yang berbeza untuk membuat hierarki.

Kami akan memberikan bobot kepada setiap pemilih agar kami lebih memahami bagaimana kedudukan setiap pemilih. Mari kita mulakan dengan sedikit.

Unsur dan unsur Pseudo

Kami menggunakan pemilih elemen seperti a, pdan divuntuk menggayakan elemen yang dipilih, sementara elemen pseudo suka ::afterdan ::beforedigunakan untuk menggayakan bahagian tertentu elemen.

 p { color: red; }  p::before { color: red; }

Pemilih elemen dan pseudo-elemen mempunyai kekhususan terendah. Dalam sistem berat kekhususan, mereka mempunyai nilai 1.

Kelas, Atribut dan kelas Pseudo

Berikut adalah contoh kelas, atribut, dan kelas pseudo:

 .person { color: red; }  [type="radio"] { color: red; }  :focus { color: red; }

Mereka mempunyai kekhususan yang lebih tinggi daripada pemilih elemen dan pseudo-elemen. Dalam sistem kekhususan berat badan kita, mereka mempunyai nilai 10.

Pemilih ID

Pemilih ID digunakan untuk menargetkan elemen menggunakan ID elemen.

 #header { color: red; }

Pemilih ID mempunyai kekhususan yang lebih tinggi daripada kelas dan elemen. Dalam sistem berat kekhususan kami, mereka mempunyai nilai 100.

Gaya Sebaris

Gaya sebaris diterapkan secara langsung pada elemen dalam dokumen HTML. Ini adalah contoh:

This is a paragraph

Gaya sebaris mempunyai kekhususan tertinggi. Dalam sistem berat kekhususan kami, mereka mempunyai nilai 1000.

Berikut adalah ringkasan berat:

Inline Styles - 1000 ID selectors - 100 Classes, Attributes and Pseudo-classes - 10 Elements and Pseudo-elements - 1 

Mari cuba masuk akal.

The property values of selectors with a higher weight will always be applied over a selector with a lower weight.

Inline styles have the highest weight and their property value overrides every other selector's value applied to an element.

For example, if we have an element and for the same property color, there's an inline style. If the class and id selectors also have values for the same property, the inline style wins.

This is a paragraph

The stylesheet:

#paragraph { color: green; } .yellow { color: yellow; }

This is the result:

The same thing happens when an ID selector and class selector have values for the same property. The property value of the ID selector will apply.

Note that the weights only apply when different selectors have values for the same property.

Multiple Element Selectors

There are times when more than one selector is used to target an element. For example, for a list like this:


    
  • First item
  • Second item
  • Third item

You may target the list items like this:

.list > li { color: green; }

or like this:

ul > li { color: red; }

In a case where both selectors are used on the same stylesheet, which style will be applied to the list items?

Let's go back to our weight system to calculate the specificity of both selectors.

For .list > li, the weight of one class selector is 10 and the weight of an element selector is 1. Combined their sum is 11.

For ul > li, the weight of one element selector is 1. There are two element selectors used, so their sum is 2.

Which of the color values do you will think will be applied?

If you said the color of the .list>li selector will be applied, you got it right. It has a higher specificity value than the other selector.

Let's try another example. Given this element:

This is a paragraph

and these styles

#div-1 > .second-block > .text { color: blue } .first-block > #div-2 > #paragraph { color: red }

Try to calculate the specificity and guess which color value will apply.

This is the result:

Let's use our weight system to understand why the color value of the second selector is applied.

For #div-1 > .second-block > .text, we have one ID selector and two class selectors. The sum of their weights is 100 + 10 + 10 = 120.

For .first-block > #div-2 > #paragraph, we have one class selector and two ID selectors. The sum of their weights is 10 + 100 + 100 = 210.

That's why the value of latter selector is used.

You can try this example on your own to be sure that you get the hang of it.


    
  • First item

Which color will be applied to the span if the following styles are in the stylesheet?

div#div1 > .first-list > #list-item > span { color: red; } #list > #list-item > #span { color: purple; } #div1 > #list > .first-list-item > .first-span { color: light-blue; }

Try to calculate the specificity and compare it with the result you get when you run the code.

Before we conclude this article, there are some important points to note.

Important Points about CSS Specificity

The weight assigned to a selector just gives us an idea of which rules get applied to an element. However, this does not always suffice.

For instance, you may assume that if you use more than 10 classes (weight >= 100) to target an element, the property values will override that of one ID selector. But this is not true. As long as the selector with more than 10 classes have no ID selector, the one ID selector will always take precedence over it.

Applying !important to the property value of any selector makes it the value that will be applied to the element. This happens regardless of the rank of the selector on the Specificity hierarchy.

Let's use an example to understand this.

This is a paragraph

If the following styles are applied

p { color: red !important; } .blue { color: blue; } #paragraph { color: purple; }

The value of the element selector p will be used because of the !important attached to the value.

However, if another selector has the !important tag attached to the same property, the value of the later selector is used.

That's why !important should be avoided because it makes it difficult override a style.

Generally, to style a specific element, it is more advisable to use a class. This makes it easier to override the styles if you ever need to do so.

Summary

From this article, we can see that CSS specificity is an important topic to understand because it can save you hours of debugging.

With this knowledge, you can easily find out why your styles are not being applied.

Here are the major points to take out of this article:

  • Due to the cascading nature of CSS, if two rules are applied to the same element, the one that comes last is the one that will be used.
  • CSS specificity is a set of rules that determine which style is applied to an element.
  • The weight system is one way of calculating the specificity of different selectors. Here's a summary of the weights:
Inline Styles - 1000 ID selectors - 100 Classes, Attributes and Pseudo-classes - 10 Elements and Pseudo-elements - 1 
  • !important overrides all other styles regardless of the specificity of the selector where it is used.

I hope you enjoyed reading this article.