Search code examples
reactjsstyled-components

Global Styles don't work on resetting the margins


I am using styled-components in a react app. For the global styles I have the following code

import { createGlobalStyle } from 'styled-components';
import normalize from 'normalize.css';

export default createGlobalStyle`
    ${normalize}

    *, *::after, *::before{
        margin:0;
        padding:0;
        box-sizing: border-box;
    }
`;

but when I use h1 in the App component like so

function App() {
  return <h1>Hello</h1>;
}

export default App;

there will be margin on h1.

In the DevTools in styles I have the following css rule

h1 {
    font-size: 2em;
    margin: 0.67em 0;
}

from normalize.css:40, and the margin in the Global Styles is overwritten because it's crossed through. Why? and how to force the margin on all elements to be 0 as I wish it to be?

EDIT: this is the code on codesandbox


Solution

  • From css-tricks.com/specifics-on-css-specificity:

    The universal selector (*) has no specificity value (0,0,0,0)

    This is why the selector h1 from normalize is applied since it has a higher specificity of (0,0,0,1)

    You could update your selector like the following to ensure it overrides normalize:

    export default createGlobalStyle`
    ${normalize}
    
    *, *::after, *::before, h1:is(h1){
        margin:0;
        padding:0;
        box-sizing: border-box;
    }
    `;
    

    The :is(h1) part is added only to increase specificity of selector.

    Edit relaxed-glade-y6f99