Styling
Global Styles
src\styles\global.css
You will need to create the styles directory.
src\components\layout.js
Component Styles (Scoped)
Create a CSS Module for the layout component.
src\components\layout.module.css
.container {margin: 0 auto;max-width: 1920px;padding: 10px;}Import your css module into the component and apply the container class.
src\components\layout.js
import React from "react"import Footer from "./footer"import Header from "./header"+ import * as styles from "./layout.module.css"export default function Layout({ children }) {return (- <div>+ <div className={styles.container}><Header />{children}<Footer /></div>)}
CSS-in-JS
CSS-in-JS
is a styling technique where JavaScript is used to style components. When this JavaScript is parsed, CSS is generated (usually as a <style>
element) and attached into the DOM. It allows developers to abstract CSS to the component level itself, using JavaScript to describe styles in a declarative and maintainable way.
There are multiple implementations of this concept in the form of libraries such as:
Emotion
Styled Components
For more information on the adoption level and user satisfaction of these libraries see the State of CSS Survey and this npm Trends Chart.
Emotion
gatsby-config.js
src\components\header.js
Utility-First CSS
Building complex components from a constrained set of primitive utilities
Utility-First Example
Traditionally, whenever you need to style something on the web, you write CSS.
Using a traditional approach where custom designs require custom CSS
With utility classes (Tailwind), you style elements by applying pre-existing classes directly in your HTML.
Using utility classes to build custom designs without writing CSS
Utility-First Benefits
- You aren't wasting energy inventing class names
- Your CSS stops growing
- Making changes feels safer
Why not just use inline styles?
- Designing with constraints.
- Using inline styles, every value is a magic number. With utilities, you're choosing styles from a predefined design system, which makes it much easier to build visually consistent UIs.
- Responsive design.
- You can't use media queries in inline styles, but you can use Tailwind's responsive utilities to build fully responsive interfaces easily.
- Hover, focus, and other states.
- Inline styles can't target states like hover or focus, but Tailwind's state variants make it easy to style those states with utility classes.
Tailwind
- a utility-first CSS framework
- for rapidly building custom user interfaces
Reference
Review
- How can you include global styles in a Gatsby site?
- What do you think about CSS-in-JS approaches to styling in Gatsby?
- What are some of the benefits with using a Utility-first CSS Framework like Tailwind?