Be the first user to complete this post
|
Add to List |
css specificity interview question
- Specificity allows browsers to decide which CSS property values are the most relevant to an element and, therefore, will be applied.
- Specificity only applies when the same element is targeted by multiple declarations.
- Inline Styles > ID Selectors > Classes, Pseudo Elements > Attributes > Elements > Inheritance
In this example, as there is one css selector. So, browser can not apply specificity. [codepen_embed height="265" theme_id="0" slug_hash="PGEyvA" default_tab="html,result" user="kavitshah8"]See the Pen specificity-1 by Kavit Shah (@kavitshah8) on CodePen.[/codepen_embed]
Here, we have two css selectors which targets the same element. But the css selector with the id has higher specificity. Hence, the
"color : red"
will be applied.
[codepen_embed height="265" theme_id="0" slug_hash="Egodqo" default_tab="css,result" user="kavitshah8"]See the Pen specificity-2 by Kavit Shah (@kavitshah8) on CodePen.[/codepen_embed]
Inline styles always have the higher priority than the external style sheet. Hence, the
"color: green"
will be applied. You can override
[codepen_embed height="265" theme_id="0" slug_hash="kkvQNy" default_tab="html,result" user="kavitshah8"]See the Pen specificity-3 by Kavit Shah (@kavitshah8) on CodePen.[/codepen_embed]
One can override the inline styles with the
!important
flag in the external style sheet. Hence, the "color : red"
will be applied.
[codepen_embed height="265" theme_id="0" slug_hash="gwoQbV" default_tab="html,result" user="kavitshah8"]See the Pen specificity-4 by Kavit Shah (@kavitshah8) on CodePen.[/codepen_embed]
Also Read:
- Difference between async and defer attributes in script tags
- Default function parameters
- Using css3 calc in an attribute value to compute its value at runtime
- Understanding the CSS 3 transition property syntax
- box-sizing