Here are some options for styling in Gatsby:
We can use inline styles in our components.
Inline styles can be written as attributes in the opening tag of a JSX element:
<h1 style={{ color: 'red' }}>Hello world</h1>
We can create a global css file for our project.
For example, in src
directory, we create a css
folder then create layout.css in that folder.
src
├── css
│ └── layout.css
h1 {
color: blue;
text-align: center;
}
We can then import the layout.css
file in our layout.js
component
import "../css/layout.css"
Note: Inline style is always stronger than global css.
While Global style is useful for small projects, it can be annoying if the project gets bigger because we’ll need to think different className.
CSS Modules scope CSS locally to that file.
For example, we create a src/css/blog.module.css
.page {
background: pink;
}
.page h1 {
color: white;
text-align: center;
}
.text {
text-transform: capitalize;
}
In src/pages/blog.js
blog.module.css
module<div>
import React from 'react'
import Layout from "../components/Layout"
import {page, text} from "../css/blog.module.css"
const Blog = () => {
return (
<Layout>
<div className={page}>
<h1>This is our blog page</h1>
<p className={text}>Hello there.</p>
</div>
</Layout>
)
}
export default Blog
We can also import all without naming each class using \*
import React from 'react'
import Layout from "../components/Layout"
import * as blogStyle from "../css/blog.module.css"
const Blog = () => {
return (
<Layout>
<div className={blogStyle.page}>
<h1>This is our blog page</h1>
<p className={blogStyle.text}>Hello there.</p>
</div>
</Layout>
)
}
export default Blog
Styled-components are a CSS-in-JS framework that offers different features to styling components in a functional and reusable way
The concept of styled-components is quite similar to CSS Modules, in that it copes CSS to particular component.
We can install a Gatsby plugin for styled-component
npm install gatsby-plugin-styled-components styled-components babel-plugin-styled-components
Plugin page: https://www.gatsbyjs.com/plugins/gatsby-plugin-styled-components/
To use style-component, we need to edit gatsby-config.js
module.exports = {
plugins: [ `gatsby-plugin-styled-components`],
}
Any time we make changes in gatsby-config.js, we must restart gatsby develop
server.
In this example, we will create a button.js component
import styled from "styled-components"
export const ExampleButton = styled.button`
background: black;
color: white;
font-size: 2rem;
`
We can then use Button component anywhere we want. For example, we can use it in index.js
import React from 'react'
import Layout from "../components/layout"
import { ExampleButton } from "../components/button"
const Home = () => {
return (
<Layout>
<h2>Hello World</h2>
<ExampleButton>Click Me</ExampleButton>
</Layout>
)
}
export default Home