overexchange overexchange - 3 months ago 18
CSS Question

Order of precedence of CSS rules

If more than one CSS rule applies to an element and specifies the same property,
then CSS gives priority to the rule that has the more specific selector.

That means,
An ID selector is more specific than a class selector, which in turn is more
specific than a tag selector, as shown below,

/* html code */
<p class="class1" id="id1">
Sham
</p>

/* css code */
#id1{
color: blue;
}
.class1{
color: red;
}

p{
color: green;
}


the output is, paragraph text in
blue
color

For the below code,

/* html code */
<p class="class1" id="id1" colour>
Sham
</p>

/* css code*/
p[colour]{
color: yellow;
}

#id1{
color: blue;
}
.class1{
color: red;
}

p{
color: green;
}


What does the CSS rule specificity says?

Answer

It is still blue. Attribute selectors are on the same level as classes. For more information see: https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity

Comments