PXProLearnX
Sign in (soon)
HTML/CSSmediumconcept

How does CSS specificity work?

Explanation:

CSS specificity determines which style rules apply to an element when there are conflicting rules. It assigns weight to different types of selectors to determine precedence. The more specific a selector, the higher its priority.

Key Talking Points:

  • CSS specificity is calculated based on the types of selectors used.
  • Specificity is determined by counting each type of selector in a rule.
  • The order from highest to lowest specificity is: inline styles, IDs, classes/attributes/pseudo-classes, and elements/pseudo-elements.
  • When selectors have the same specificity, the last one defined takes precedence.

NOTES:

Reference Table:

Selector TypeSpecificity Value
Inline Styles1000
ID Selector (#id)0100
Class/Attribute/Pseudo-Class0010
Element/Pseudo-Element0001

Pseudocode:

Although this question typically doesn't require a code snippet, here's an example showcasing specificity:

   /* Specificity: 0001 */
   p {
       color: blue;
   }

   /* Specificity: 0010 */
   .text {
       color: green;
   }

   /* Specificity: 0100 */
   #unique {
       color: red;
   }

   /* Specificity: 1000 */
   <p style="color: orange;">This is a paragraph.</p>

In this example, the inline style will take precedence and the paragraph will be orange.

Follow-Up Questions and Answers:

  • Question: How can you increase the specificity of a selector?

    • Answer: You can increase specificity by adding more specific selectors. For example, using an ID selector or combining multiple classes can increase specificity.
  • Question: What happens when two selectors have the same specificity?

    • Answer: When two selectors have the same specificity, the one that appears later in the CSS file will take precedence.
  • Question: How do !important declarations affect specificity?

    • Answer: The !important declaration overrides normal specificity rules, giving the declaration the highest priority. However, if multiple !important rules apply, the one with the higher specificity still takes precedence.
Want all 100 questions?
Get the full book on Amazon — paperback, Kindle, or hardcover.