72

Ordinarily, when using pure CSS, I have a style sheet that contains:

html {
    height: 100%;
}

body {
    font-size: 14px;
}

When using styled-components in my React project, how do I set styles for the html or body tags? Do I maintain a separate CSS file just for this purpose?

Soroush Chehresa
  • 5,490
  • 1
  • 14
  • 29
JoeTidee
  • 24,754
  • 25
  • 104
  • 149

2 Answers2

124

You can, of course, maintain a separate CSS file that you include in your HTML via a <link> tag.

For v4:

Use createGlobalStyle from Styled-components.

import { createGlobalStyle } from 'styled-components'

const GlobalStyle = createGlobalStyle`
  body {
    color: ${props => (props.whiteColor ? 'white' : 'black')};
  }
`

<React.Fragment>
  <GlobalStyle whiteColor />
  <Navigation /> {/* example of other top-level stuff */}
</React.Fragment>

Pre v4:

Styled-components also exports an injectGlobal helper to inject global CSS from JavaScript:

import { injectGlobal } from 'styled-components';

injectGlobal`
  html {
    height: 100%;
    width: 100%;
  }
`

See the API documentation for more information!

brettinternet
  • 546
  • 7
  • 21
mxstbr
  • 11,087
  • 4
  • 39
  • 37
  • Looking at this you can only hard code the HTML and BODY elements. If you wanted to allow for varying background colors on the BODY element how would you be able to dynamically set them? – Jeff L Sep 17 '18 at 19:58
  • One should add that the correct way of using global styles is not wrapping your components in it but rather calling it as an independent component. – ArchNoob Dec 27 '19 at 10:03
25

As of Oct, 2018.

NOTE

The injectGlobal API was removed and replaced by createGlobalStyle in styled-components v4.

According to docs createGlobalStyle is

A helper function to generate a special StyledComponent that handles global styles. Normally, styled components are automatically scoped to a local CSS class and therefore isolated from other components. In the case of createGlobalStyle, this limitation is removed and things like CSS resets or base stylesheets can be applied.

Example

import { createGlobalStyle } from 'styled-components'

const GlobalStyle = createGlobalStyle`
  body {
    color: ${props => (props.whiteColor ? 'white' : 'black')};
  }
`

// later in your app

<React.Fragment>
  <Navigation /> {/* example of other top-level stuff */}
  <GlobalStyle whiteColor />
</React.Fragment>

Read more on official docs.

Madan Bhandari
  • 2,094
  • 2
  • 26
  • 46