Learn Gatsby Β· 3/12

Styling Your Gatsby Application

11 min read

🎨 Styling Your Gatsby Application

Welcome, fellow developer! You've built the structure of your Gatsby site, and it's looking... well, structural. It's time to give it some personality! Styling is what turns a plain HTML skeleton into a beautiful, engaging user experience.

But as you'll soon see, there's more than one way to apply styles in the modern web world. This guide will walk you through the most common and industry-standard approaches to styling in Gatsby. We'll start with the basics and move toward more advanced, component-based methods.

Let's imagine we're organizing a closet. At first, you might just have one big rule, but as your wardrobe grows, you'll need better systems to keep things tidy and avoid chaos. Styling a web application is surprisingly similar.


1. Standard CSS and Managing Global Styles πŸ‘•

This is the classic, foundational way of styling. You write plain CSS in a .css file, and those styles can apply to your entire site.

The Definition and The Problem

Global CSS refers to stylesheets that are loaded and applied across your entire application. Think of it as the master set of rules for your site's appearance.

The Problem: Imagine you have two different components, and in both of their stylesheets, you define a style for a class called .card.

css
/* component-one.css */
.card {
  background-color: blue;
}

/* component-two.css */
.card {
  background-color: red;
}

Whichever stylesheet gets loaded last will win, and all your cards will be red! This is called a global namespace collision. Your styles "pollute" the global scope and can unintentionally override each other, leading to unpredictable results and frustrating debugging sessions.

Global styles are necessary for setting foundational rules, but they are a clumsy tool for styling individual components.

The Solution: A Global Stylesheet for Base Styling

The best practice is to use a global stylesheet only for defining broad, site-wide styles. This includes:

  • CSS resets (like normalize.css)
  • Font definitions (@font-face)
  • Base styling for HTML elements (e.g., body, h1, a)
  • CSS variables for your design system (e.g., colors, spacing)

Hands-On: Adding a Global Stylesheet

Gatsby makes this process straightforward. The official way to add a global stylesheet is to import it into your gatsby-browser.js file.

  1. Create the CSS file:
    Create a file at src/styles/global.css.

    css
    /* src/styles/global.css */
    
    :root {
      --primary-color: #663399; /* Gatsby Purple! */
      --padding-large: 24px;
    }
    
    body {
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
      margin: 0;
      background-color: #f4f4f4;
    }
    
    a {
      color: var(--primary-color);
      text-decoration: none;
    }
  2. Import it in gatsby-browser.js:
    If you don't have one, create a file named gatsby-browser.js in the root of your project. Then, add the import statement.

    javascript
    // gatsby-browser.js
    
    import "./src/styles/global.css"

And that's it! When you start your development server, Gatsby will bundle this CSS and apply it to every page. You've now set the basic rules for your entire "closet."

✨ Fun Fact: The gatsby-browser.js file is a special Gatsby file that lets you hook into client-side browser events and APIs. Importing your CSS here ensures it's available as soon as your site loads in the browser.


2. CSS Modules: Scoped Styling for Reusable Components drawers

You've got your global rules, but what about individual pieces of clothing? You need a way to organize them so your sock styles don't accidentally apply to your shirts. That's exactly what CSS Modules do for your components.

The Definition and The Problem

CSS Modules are CSS files in which all class names are scoped locally by default. This means a class name you write in one file will not conflict with the same class name written in another file.

The Problem Solved: It directly solves the global namespace collision issue. By using CSS Modules, you can write a .card class for your UserProfile component and a completely different .card class for your ProductDetails component without any fear of them overwriting each other.

The Solution: Locally Scoped, Conflict-Free Styling

Under the hood, Gatsby's build process takes your class names (e.g., .title) and transforms them into a unique string (e.g., Component-title--1a2b3c). This guarantees the style is applied only where you explicitly import it.

Hands-On: Using CSS Modules

Gatsby has built-in, out-of-the-box support for CSS Modules. You don't need to install anything!

  1. Name your file correctly: To enable CSS Modules, simply name your stylesheet with the .module.css extension.

  2. Create a component and its styles:
    Let's make a simple Button component.

    • src/components/Button.js
    • src/components/Button.module.css
    css
    /* src/components/Button.module.css */
    
    .button {
      background-color: #663399; /* Gatsby Purple */
      color: white;
      padding: 10px 20px;
      border: none;
      border-radius: 5px;
      cursor: pointer;
      font-size: 1rem;
    }
    
    .primary {
      background-color: #ff6347; /* Tomato Red */
    }
  3. Import and use the styles in your component:
    You import the styles as an object (a common convention is to name it styles) and then reference the class names as properties of that object.

    jsx
    // src/components/Button.js
    
    import React from 'react';
    import * as styles from './Button.module.css';
    
    const Button = ({ children, isPrimary }) => {
      // Conditionally apply a class
      const buttonClassName = isPrimary ? `${styles.button} ${styles.primary}` : styles.button;
    
      return (
        <button className={buttonClassName}>
          {children}
        </button>
      );
    };
    
    export default Button;

Now, if you inspect this button in your browser, you won't see class="button". You'll see something like class="Button-module--button--xyz12". It's your personal, private style class! You've just created a perfectly organized, labeled drawer for your component's styles.


3. Integrating CSS-in-JS: Styled Components and Emotion πŸ’…

What if we could blur the lines between our components and their styles? What if styles could live inside our JavaScript files and react to props just like the rest of our component logic? Welcome to CSS-in-JS.

The Definition and The Problem

CSS-in-JS is a styling paradigm where CSS is written directly within JavaScript. Libraries like Styled Components and Emotion use tagged template literals to create React components with styles attached to them.

The Problem: While CSS Modules are great for preventing conflicts, you still have two separate files to manage for one component (.js and .module.css). Furthermore, making styles dynamic based on component props can be clunky, often involving string concatenation to toggle classes.

The Solution: Co-located, Dynamic, and Component-Based Styles

CSS-in-JS libraries solve these issues by:

  • Co-location: Keeping your component's logic, structure, and styles all in one .js file.
  • Dynamic Styling: Allowing you to easily and cleanly alter styles based on your component's props.
  • Full Power of JS: Letting you use JavaScript variables, functions, and logic directly within your styles.

Hands-On: Setting up Styled Components

Let's use Styled Components as our example. The setup requires a Gatsby plugin.

  1. Installation:
    Open your terminal and run:

    bash
    npm install gatsby-plugin-styled-components styled-components babel-plugin-styled-components
  2. Configuration:
    Add the plugin to your gatsby-config.js file.

    javascript
    // gatsby-config.js
    
    module.exports = {
      plugins: [`gatsby-plugin-styled-components`],
    }
  3. Create a styled component:
    Now, let's recreate our Button component using this new method.

    jsx
    // src/components/StyledButton.js
    
    import React from 'react';
    import styled from 'styled-components';
    
    // Create a <Button> component that will render a <button> tag with some styles
    const Button = styled.button`
      background-color: ${props => props.primary ? '#ff6347' : '#663399'};
      color: white;
      padding: 10px 20px;
      border: none;
      border-radius: 5px;
      cursor: pointer;
      font-size: 1rem;
    
      /* We can even add pseudo-classes! */
      &:hover {
        opacity: 0.9;
      }
    `;
    
    const StyledButton = ({ children, primary }) => {
      return (
        <Button primary={primary}>
          {children}
        </Button>
      );
    };
    
    export default StyledButton;

    Look how clean that is! The background color changes based on whether a primary prop is passed to the component. This is the power of CSS-in-JS. You're not just styling; you're creating a custom-designed, configurable storage unit for your component.

Emotion vs. Styled Components? They are very similar in syntax and functionality. Both are excellent, industry-leading choices. The decision often comes down to team preference. Emotion is known for being slightly more performant and flexible in certain advanced scenarios.


4. Utility-First Styling: Configuring Tailwind CSS with Gatsby πŸ’¨

Our final approach is a bit different. Instead of writing CSS that describes what a component is (e.g., .card, .button), what if we had a massive toolkit of classes that describe what a component does (e.g., has a shadow, has rounded corners, is a flex container)? This is the philosophy of utility-first CSS.

The Definition and The Problem

Utility-First CSS is an approach where you style elements by applying pre-existing, single-purpose classes directly in your HTML/JSX. Tailwind CSS is the most popular utility-first framework.

The Problem: Writing custom CSS for every component can lead to a lot of repeated code. You might find yourself writing display: flex; align-items: center; in a dozen different files. It can also be hard to maintain consistency in spacing, font sizes, and colors across a large application without a strict design system.

The Solution: Rapid Prototyping with a Constrained Toolkit

Tailwind CSS provides a huge set of utility classes like p-4 (padding: 1rem), flex (display: flex), rounded-lg (border-radius: 0.5rem), and text-center (text-align: center).

This approach:

  • Speeds up development: You build complex designs by composing utilities, often without writing a single line of custom CSS.
  • Enforces consistency: Since you're using classes from a predefined scale (e.g., p-1, p-2, p-3, p-4), your design remains consistent.
  • Keeps bundles small: Tailwind scans your files and only includes the utility classes you are actually using in its final production stylesheet.

Hands-On: Setting up Tailwind CSS

This setup is the most involved, but the payoff in development speed is huge.

  1. Installation:
    Install Tailwind and its dependencies, including postcss, which Gatsby uses to process the CSS.

    bash
    npm install gatsby-plugin-postcss tailwindcss postcss autoprefixer
  2. Generate Config Files:
    Run this command to create tailwind.config.js and postcss.config.js files.

    bash
    npx tailwindcss init -p
  3. Configure Tailwind:
    Open tailwind.config.js and tell it which files to scan for utility classes.

    javascript
    // tailwind.config.js
    
    /** @type {import('tailwindcss').Config} */
    module.exports = {
      content: [
        "./src/pages/**/*.{js,jsx,ts,tsx}",
        "./src/components/**/*.{js,jsx,ts,tsx}",
      ],
      theme: {
        extend: {},
      },
      plugins: [],
    }
  4. Configure Gatsby:
    Add gatsby-plugin-postcss to your gatsby-config.js.

    javascript
    // gatsby-config.js
    
    module.exports = {
      plugins: [`gatsby-plugin-postcss`],
    }
  5. Import Tailwind's Base Styles:
    Create a global CSS file (e.g., src/styles/global.css) and add Tailwind's directives. These are placeholders that Tailwind will replace with its generated styles.

    css
    /* src/styles/global.css */
    
    @tailwind base;
    @tailwind components;
    @tailwind utilities;

    Then, import this file in your gatsby-browser.js just like we did in the first section.

    javascript
    // gatsby-browser.js
    import "./src/styles/global.css"
  6. Start Styling!
    Now you can use Tailwind classes directly in any component.

    jsx
    // src/components/TailwindCard.js
    
    import React from 'react';
    
    const TailwindCard = () => {
      return (
        <div className="max-w-sm p-6 bg-white border border-gray-200 rounded-lg shadow-md hover:bg-gray-100">
          <h5 className="mb-2 text-2xl font-bold tracking-tight text-gray-900">
            Styled with Tailwind!
          </h5>
          <p className="font-normal text-gray-700">
            This card was built by composing utility classes directly in the JSX.
          </p>
        </div>
      );
    };
    
    export default TailwindCard;

You've just built a complex component without writing a single line of custom CSS. It's like having a perfectly organized workshop where every tool is labeled and within arm's reach.


Conclusion

Which styling method is best? It depends!

  • Global CSS: Essential for base styles, but use it sparingly.
  • CSS Modules: A fantastic, built-in solution for component-level styling if you like writing traditional CSS.
  • CSS-in-JS (Styled Components/Emotion): The best choice if you love keeping everything in JavaScript and need powerful, dynamic styling capabilities.
  • Tailwind CSS: Unbeatable for rapid development, enforcing consistency, and keeping your CSS codebase small.

Many large projects even use a hybrid approach! They might use Tailwind for layout and spacing, and Styled Components for complex, stateful components. The key is to understand the problem each tool solves and choose the right one for the job. Happy styling! πŸš€


πŸ“š Further Reading & References


Conclusion

Which styling method is best? It depends!

  • Global CSS: Essential for base styles, but use it sparingly.
  • CSS Modules: A fantastic, built-in solution for component-level styling if you like writing traditional CSS.
  • CSS-in-JS (Styled Components/Emotion): The best choice if you love keeping everything in JavaScript and need powerful, dynamic styling capabilities.
  • Tailwind CSS: Unbeatable for rapid development, enforcing consistency, and keeping your CSS codebase small.

Many large projects even use a hybrid approach! They might use Tailwind for layout and spacing, and Styled Components for complex, stateful components. The key is to understand the problem each tool solves and choose the right one for the job. Happy styling! πŸš€


πŸ“š Further Reading & References

Challenge

You are tasked with styling a Card component for a Gatsby application using a hybrid approach that combines CSS Modules and Styled Components. You will also need to consider how global styles would be integrated.

Your Tasks:

  1. CSS Module Styles: In the cssModuleContent string variable, write the CSS rules for the component.

    • Create a .container class with a 1px solid #ddd border, 16px of padding, and a 0 4px 8px 0 rgba(0,0,0,0.2) box shadow.
    • Create a .title class that sets the font-size to 1.5rem and color to #333.
    • Create a .description class for the paragraph text, setting its color to #666 and line-height to 1.6.
    • Assume a global CSS variable var(--font-family) exists and apply it to the .container.
  2. Styled Component: Create a dynamic Button component using styled-components.

    • The component must be named StyledButton.
    • It should have base styles: padding of 10px 15px, a 0 border, 4px border-radius, a pointer cursor, and a margin-right of 10px.
    • It must accept a boolean primary prop.
    • If the primary prop is present, the button's background-color should be var(--primary-color) and its text color should be white.
    • If the primary prop is not present, the background-color should be var(--secondary-color) and the text color should be white.
  3. Component Implementation: Complete the Card component's JSX.

    • Apply the class names from the (mock) styles object to the div, h2, and p elements.
    • Inside the final div, render two instances of your StyledButton. The first one should be the primary button with the text "Learn More", and the second one should be the default button with the text "Contact Us".

Expected result

Your solution should contain the following:

  1. A completed cssModuleContent string with valid CSS rules for .container, .title, and .description. The .container rule should use var(--font-family).
  2. A StyledButton constant assigned a styled.button tagged template literal. The CSS inside should conditionally set the background-color based on the primary prop, using var(--primary-color) and var(--secondary-color).
  3. The Card component's JSX should be updated:
    • The className prop for the container div should be set to styles.container.
    • The className for the h2 element should be styles.title.
    • The className for the p element should be styles.description.
    • Two StyledButton components should be rendered. The first one must have the primary prop, e.g., <StyledButton primary>Learn More</StyledButton>. The second one must not have the primary prop, e.g., <StyledButton>Contact Us</StyledButton>.
jsx

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.