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.
/* 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.
Create the CSS file:
Create a file atsrc/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; }Import it in
gatsby-browser.js:
If you don't have one, create a file namedgatsby-browser.jsin 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.jsfile 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!
Name your file correctly: To enable CSS Modules, simply name your stylesheet with the
.module.cssextension.Create a component and its styles:
Let's make a simpleButtoncomponent.src/components/Button.jssrc/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 */ }Import and use the styles in your component:
You import the styles as an object (a common convention is to name itstyles) 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
.jsfile. - 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.
Installation:
Open your terminal and run:bashnpm install gatsby-plugin-styled-components styled-components babel-plugin-styled-componentsConfiguration:
Add the plugin to yourgatsby-config.jsfile.javascript// gatsby-config.js module.exports = { plugins: [`gatsby-plugin-styled-components`], }Create a styled component:
Now, let's recreate ourButtoncomponent 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
primaryprop 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.
Installation:
Install Tailwind and its dependencies, includingpostcss, which Gatsby uses to process the CSS.bashnpm install gatsby-plugin-postcss tailwindcss postcss autoprefixerGenerate Config Files:
Run this command to createtailwind.config.jsandpostcss.config.jsfiles.bashnpx tailwindcss init -pConfigure Tailwind:
Opentailwind.config.jsand 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: [], }Configure Gatsby:
Addgatsby-plugin-postcssto yourgatsby-config.js.javascript// gatsby-config.js module.exports = { plugins: [`gatsby-plugin-postcss`], }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.jsjust like we did in the first section.javascript// gatsby-browser.js import "./src/styles/global.css"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
- Gatsby Documentation on Styling: https://www.gatsbyjs.com/docs/how-to/styling/
- CSS Modules: Gatsby and CSS Modules
- Styled Components: Official Documentation | Gatsby Plugin for Styled Components
- Emotion: Official Documentation | Gatsby Plugin for Emotion
- Tailwind CSS: Official Documentation | Using Tailwind CSS with Gatsby Guide
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
- Gatsby Documentation on Styling: https://www.gatsbyjs.com/docs/how-to/styling/
- CSS Modules: Gatsby and CSS Modules
- Styled Components: Official Documentation | Gatsby Plugin for Styled Components
- Emotion: Official Documentation | Gatsby Plugin for Emotion
- Tailwind CSS: Official Documentation | Using Tailwind CSS with Gatsby Guide
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:
CSS Module Styles: In the
cssModuleContentstring variable, write the CSS rules for the component.- Create a
.containerclass with a1px solid #dddborder,16pxof padding, and a0 4px 8px 0 rgba(0,0,0,0.2)box shadow. - Create a
.titleclass that sets thefont-sizeto1.5remandcolorto#333. - Create a
.descriptionclass for the paragraph text, setting itscolorto#666andline-heightto1.6. - Assume a global CSS variable
var(--font-family)exists and apply it to the.container.
- Create a
Styled Component: Create a dynamic
Buttoncomponent usingstyled-components.- The component must be named
StyledButton. - It should have base styles:
paddingof10px 15px, a0border,4pxborder-radius, apointercursor, and amargin-rightof10px. - It must accept a boolean
primaryprop. - If the
primaryprop is present, the button'sbackground-colorshould bevar(--primary-color)and its textcolorshould bewhite. - If the
primaryprop is not present, thebackground-colorshould bevar(--secondary-color)and the textcolorshould bewhite.
- The component must be named
Component Implementation: Complete the
Cardcomponent's JSX.- Apply the class names from the (mock)
stylesobject to thediv,h2, andpelements. - Inside the final
div, render two instances of yourStyledButton. 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".
- Apply the class names from the (mock)
Expected result
Your solution should contain the following:
- A completed
cssModuleContentstring with valid CSS rules for.container,.title, and.description. The.containerrule should usevar(--font-family). - A
StyledButtonconstant assigned astyled.buttontagged template literal. The CSS inside should conditionally set thebackground-colorbased on theprimaryprop, usingvar(--primary-color)andvar(--secondary-color). - The
Cardcomponent's JSX should be updated:- The
classNameprop for the containerdivshould be set tostyles.container. - The
classNamefor theh2element should bestyles.title. - The
classNamefor thepelement should bestyles.description. - Two
StyledButtoncomponents should be rendered. The first one must have theprimaryprop, e.g.,<StyledButton primary>Learn More</StyledButton>. The second one must not have theprimaryprop, e.g.,<StyledButton>Contact Us</StyledButton>.
- The