Search code examples
csscss-selectors

:root, html, * selector. Any differences?


Is there any difference between those three CSS rules ?

* {
  font-size: 24px
}
:root {
  font-size: 24px
}
html {
  font-size: 24px
}


Solution

  • Yes there is a difference. Below some examples where the result isn't the same

    Using *

    * {
      font-size: 24px
    }
    
    p {
      font-size:2em;
    }
    <div>
      <p>some text <span>here</span></p>
    </div>

    Using html (or :root)

    html {
      font-size: 24px
    }
    
    p {
      font-size:2em;
    }
    <div>
      <p>some text <span>here</span></p>
    </div>

    Applying font-size to all the elements is different from applying the font-size to the html element and having all the elements inherit the value.

    In the first example, span will have a font-size equal to 24px because it was selected by *. In the second example, span will inherit the computed value of p since no selector is targetting it.


    between html and :root there is a specificity war where :root will be the winner:

    html {
      font-size: 999px;
    }
    
    :root {
      font-size:24px;
    }
    <div>
      <p>some text <span>here</span></p>
    </div>

    :root {
      font-size:24px;
    }
    
    html {
      font-size: 999px;
    }
    <div>
      <p>some text <span>here</span></p>
    </div>