CSS Specificity Demo

posted on

I built an interactive demo to illustrate how specificity in CSS works.

Press the “Add selector” and “Remove selector” buttons to add or remove a selector in the list of declarations and see how the background color changes accordingly. Each selector will be added to the top of the list to prove that it has a higher specificity than the previous selector.

/* !important overwrites everything */
body {
  background: rebeccapurple !important;
}
/* Animation declarations take precedence over normal
 declarations */
body {
  animation: bg 0s forwards;
}

@keyframes bg {
  to {
    background: yellow;
  }
}
/* any selector with higher specificity, even if it doesn't 
match any element, inside :is() overwrites id + id */
#body:is(#body, #bla#bla) {
  background: hotpink;
}
/* id + id overwrites id + class */
#body#body {
  background: aqua;
}
/* id + class overwrites id + tag */
.body#body {
  background: salmon;
}
/* id + tag overwrites id */
body#body {
  background: fuchsia;
}
/* id overwrites classes */
#body {
  background: brown;
}
/* class + class overwrites tag + class */
.body.body {
  background: orange;
}
/* tag + class overwrites class */
body.body {
  background: green;
}
/* class overwrites tag */
.body {
  background: blue;
}
/* tag selector overwrites universal :where() selector */
body {
  background: red;
}
/* universal :where() selector */
:where(body) {
  background: #efefef;
}

Resources