Migrate to Netlify Today

Netlify announces the next evolution of Gatsby Cloud. Learn more

Styled Components

Examples

  • Using Styled Components

In this guide, you will learn how to set up a site with the CSS-in-JS library Styled Components.

Styled Components lets you use actual CSS syntax inside your components. Styled Components is a variant on “CSS-in-JS”—which solves many of the problems with traditional CSS.

One of the most important problems they solve is selector name collisions. With traditional CSS, you have to be careful not to overwrite CSS selectors used elsewhere in a site because all CSS selectors live in the same global namespace. This unfortunate restriction can lead to elaborate (and often confusing) selector naming schemes.

With CSS-in-JS, you avoid all that as CSS selectors are scoped automatically to their component. Styles are tightly coupled with their components. This makes it much easier to know how to edit a component’s CSS as there’s never any confusion about how and where CSS is being used.

Video hosted on egghead.io.

First, open a new terminal window and run the following to create a new site:

Second, install the necessary dependencies for styled-components, including the Gatsby plugin.

And then add it to your site’s gatsby-config.js:

Then in your terminal run gatsby develop to start the Gatsby development server.

Now create a sample Styled Components page at src/pages/index.js:

Creating Global Styles

Styled-components are primarily used for a single CSS class that is isolated from other components. In some cases, you want to override global styling — for example, the default margins of your body element. Styled-components has your back. You can use the createGlobalStyle to accomplish this. It’s advised to use createGlobalStyle in Layout components, which are shared over multiple pages rather than using it on a single page.

The example below shows how to create a GlobalStyle (which is a StyledComponent) for the color purple by importing createGlobalStyle from styled-components.

Enabling user stylesheets with a stable class name

Adding a persistent CSS className to your styled components can make it easier for end users of your website to take advantage of user stylesheets for accessibility.

Here’s an example where the class name container is added to the DOM along with the Styled Components’ dynamically-created class names:

An end user of your site could then write their own CSS styles matching HTML elements using a class name of .container. If your CSS-in-JS style changes, it will not affect the end user’s stylesheet.

Start building today on Netlify!
Edit this page on GitHub
© 2024 Gatsby, Inc.