Welcome to part two of the Gatsby tutorial!
What’s in this tutorial?
In this part, you’re going to explore options for styling Gatsby websites and dive deeper into using React components for building sites.
Using global styles
Every site has some sort of global style. This includes things like the site’s typography and background colors. These styles set the overall feel of the site — much like the color and texture of a wall sets the overall feel of a room.
Creating global styles with standard CSS files
One of the most straightforward ways to add global styles to a site is using a global .css
stylesheet.
✋ Create a new Gatsby site
Start by creating a new Gatsby site. It may be best (especially if you’re new to the command line) to close the terminal windows you used for part one and start a new terminal session for part two.
Open a new terminal window, create a new “hello world” Gatsby site in a directory called tutorial-part-two
, and then move to this new directory:
Copy
copy code to clipboard
gatsby new tutorial-part-two https://github.com/gatsbyjs/gatsby-starter-hello-world
cd tutorial-part-two
You now have a new Gatsby site (based on the Gatsby “hello world” starter) with the following structure:
Copy
copy code to clipboard
├── package.json
├── src
│ └── pages
│ └── index.js
✋ Add styles to a CSS file
- Create a
.css
file in your new project:
Copy
copy code to clipboard
cd src
mkdir styles
cd styles
touch global.css
Note: Feel free to create these directories and files using your code editor, if you’d prefer.
You should now have a structure like this:
Copy
copy code to clipboard
├── package.json
├── src
│ └── pages
│ └── index.js
│ └── styles
│ └── global.css
- Define some styles in the
global.css
file:
src/styles/global.css
Copy
src/styles/global.css: copy code to clipboard
html {
background-color: lavenderblush;
}
Note: The placement of the example CSS file in a /src/styles/
folder is arbitrary.
✋ Include the stylesheet in gatsby-browser.js
- Create the
gatsby-browser.js
Copy
copy code to clipboard
cd ../..
touch gatsby-browser.js
Your project’s file structure should now look like this:
Copy
copy code to clipboard
├── package.json
├── src
│ └── pages
│ └── index.js
│ └── styles
│ └── global.css
├── gatsby-browser.js
💡 What isgatsby-browser.js
? Don’t worry about this too much and for now, just know thatgatsby-browser.js
is one of a handful of special files that Gatsby looks for and uses (if they exist). Here, the naming of the file is important. If you do want to explore more now, check out the docs.