Standard Styling with Global CSS Files
Traditionally, websites are styled using global CSS files.
The best way to add global styles is with a shared layout component. This layout component is used for things that are shared throughout the site, including styles, header components, and other common items.
NOTE: This pattern is implemented by default in the default starter.
To create a shared layout with global styles, start by creating a new Gatsby site with the hello world starter.
Open your new site in your code editor and create a new directory at
/src/components. Inside, create two new files:
src/components/layout.css, add some global styles:
src/components/layout.js, include the stylesheet and export a layout component:
src/pages/index.js to use the new layout component:
npm run develop and you’ll see the global styles applied.
In some cases, using a shared layout component is not desirable. In these cases, you can include a global stylesheet using
NOTE: This approach does not work with CSS-in-JS. Use shared components to share styles in CSS-in-JS.
First, open a new terminal window and run the following commands to create a new default Gatsby site and start the development server:
Second, create a CSS file and define any styles you wish. An example:
Then, include the stylesheet in your site’s
Note: You can use Node.js require or import syntax. Additionally, the placement of the example css file in a
src/stylesfolder is arbitrary.
You should see your global styles taking effect across your site:
It is also possible to break up your CSS styles into separate files so that team members can work independently while still using traditional CSS. You can then import files directly into pages, templates, or components:
This approach can simplify integration of CSS or Sass styles into your Gatsby site by allowing team members to write and consume more traditional, class-based CSS. However, there are trade-offs that must be considered with regards to web performance and the lack of dead code elimination.
className prop instead, which will render as the browser-supported
class attribute in your HTML output.
The biggest problem with global CSS files is the risk of name conflicts and side effects like unintended inheritance.
Edit this page on GitHub