astro/docs/guides/styling.md

511 lines
28 KiB
Markdown
Raw Normal View History

2021-06-28 06:27:12 +00:00
---
layout: ~/layouts/Main.astro
title: Styling
---
2021-05-08 15:35:44 +00:00
## 🖍 Quick Start
2021-04-20 23:15:47 +00:00
Styling in an Astro component is done by adding a `<style>` tag anywhere. By default, all styles are **scoped**, meaning they only apply to the current component. To create global styles, add a `:global()` wrapper around a selector (the same as if you were using [CSS Modules][css-modules]).
```html
<!-- src/components/MyComponent.astro -->
2021-04-20 23:15:47 +00:00
<style>
/* Scoped class selector within the component */
.scoped {
font-weight: bold;
}
/* Scoped element selector within the component */
h1 {
color: red;
}
/* Global style */
:global(h1) {
font-size: 32px;
}
</style>
<div class="scoped">Im a scoped style and only apply to this component</div>
<h1>I have both scoped and global styles</h1>
```
**Tips**
- `<style>` tags within `.astro` files will be extracted and optimized for you on build. So you can write CSS without worrying too much about delivery.
- For best result, only have one `<style>` tag per-Astro component. This isnt necessarily a limitation, but it may result in better optimization at buildtime.
- If you want to import third-party libraries into an Astro component, you can use [Sass][sass]! In particular, [@use][sass-use] may come in handy (e.g. `@use "bootstrap/scss/bootstrap"`);
2021-06-28 06:27:12 +00:00
## Cross-Browser Compatibility
We also automatically add browser prefixes using [Autoprefixer][autoprefixer]. By default, Astro loads the [Browserslist defaults][browserslist-defaults], but you may also specify your own by placing a [Browserslist][browserslist] file in your project root.
---
## Supported Styling Options
Styling in Astro is meant to be as flexible as youd like it to be! The following options are all supported:
| Framework | Global CSS | Scoped CSS | CSS Modules |
| :--------------- | :--------: | :--------: | :---------: |
| `.astro` | ✅ | ✅ | N/A¹ |
| `.jsx` \| `.tsx` | ✅ | ❌ | ✅ |
| `.vue` | ✅ | ✅ | ✅ |
| `.svelte` | ✅ | ✅ | ❌ |
¹ _`.astro` files have no runtime, therefore Scoped CSS takes the place of CSS Modules (styles are still scoped to components, but dont need dynamic values)_
All styles in Astro are automatically [**autoprefixed**](#cross-browser-compatibility) and optimized, so you can just write CSS and well handle the rest ✨.
---
## Using Frameworks and Libraries
2021-05-28 02:05:29 +00:00
### 📘 React / Preact
2021-04-20 23:15:47 +00:00
`.jsx` files support both global CSS and CSS Modules. To enable the latter, use the `.module.css` extension (or `.module.scss`/`.module.sass` if using Sass).
```js
import './global.css'; // include global CSS
import Styles from './styles.module.css'; // Use CSS Modules (must end in `.module.css`, `.module.scss`, or `.module.sass`!)
```
2021-05-28 02:05:29 +00:00
### 📗 Vue
2021-04-20 23:15:47 +00:00
Vue in Astro supports the same methods as `vue-loader` does:
- [Scoped CSS][vue-scoped]
- [CSS Modules][vue-css-modules]
2021-05-28 02:05:29 +00:00
### 📕 Svelte
2021-04-20 23:15:47 +00:00
Svelte in Astro also works exactly as expected: [Svelte Styling Docs][svelte-style].
2021-05-28 02:05:29 +00:00
### 👓 Sass
2021-04-20 23:15:47 +00:00
Astro also supports [Sass][sass] out-of-the-box. To enable for each framework:
- **Astro**: `<style lang="scss">` or `<style lang="sass">`
- **React** / **Preact**: `import Styles from './styles.module.scss'`;
- **Vue**: `<style lang="scss">` or `<style lang="sass">`
- **Svelte**: `<style lang="scss">` or `<style lang="sass">`
2021-05-28 02:05:29 +00:00
💁‍ Sass is great! If you havent used Sass in a while, please give it another try. The new and improved [Sass Modules][sass-use] are a great fit with modern web development, and its blazing-fast since being rewritten in Dart. And the best part? **You know it already!** Use `.scss` to write familiar CSS syntax youre used to, and only sprinkle in Sass features if/when you need them.
### 🍃 Tailwind
2021-04-20 23:15:47 +00:00
Astro can be configured to use [Tailwind][tailwind] easily! Install the dependencies:
```
npm install --save-dev tailwindcss
```
And also create a `tailwind.config.js` in your project root:
```js
// tailwind.config.js
module.exports = {
mode: 'jit',
2021-06-28 06:27:12 +00:00
purge: ['./public/**/*.html', './src/**/*.{astro,js,jsx,ts,tsx,vue}'],
2021-04-20 23:15:47 +00:00
// more options here
};
```
Be sure to add the config path to `astro.config.mjs`, so that Astro enables JIT support in the dev server.
2021-04-20 23:15:47 +00:00
```diff
// astro.config.mjs
export default {
+ devOptions: {
+ tailwindConfig: './tailwind.config.js',
+ },
};
2021-04-20 23:15:47 +00:00
```
2021-05-28 02:05:29 +00:00
Now youre ready to write Tailwind! Our recommended approach is to create a `public/global.css` file (or whatever youd like to name your global stylesheet) with [Tailwind utilities][tailwind-utilities] like so:
```css
/* public/global.css */
@tailwind base;
@tailwind components;
@tailwind utilities;
```
💁 As an alternative to `public/global.css`, You may also add Tailwind utilities to individual `pages/*.astro` components in `<style>` tags, but be mindful of duplication! If you end up creating multiple Tailwind-managed stylesheets for your site, make sure youre not sending the same CSS to users over and over again in separate CSS files.
2021-06-28 06:27:12 +00:00
---
## 📦 Bundling
2021-05-28 02:05:29 +00:00
All CSS is minified and bundled automatically for you in running `astro build`. Without getting too in the weeds, the general rules are:
2021-05-28 02:05:29 +00:00
- If a style only appears on one route, its only loaded for that route (`/_astro/[page]-[hash].css`)
- If a style appears on multiple routes, its deduplicated into a `/_astro/common-[hash].css` bundle
- All styles are hashed according to their contents (the hashes only change if the contents do!)
2021-04-20 23:15:47 +00:00
Well be expanding our styling optimization story over time, and would love your feedback! If `astro build` generates unexpected styles, or if you can think of improvements, [please open an issue][issues].
2021-04-20 23:15:47 +00:00
_Note: be mindful when some page styles get extracted to the ”common” bundle, and some page styles stay on-page. For most people this may not pose an issue, but when part of your styles are bundled they technically may load in a different order and your cascade may be different. While problem isnt unique to Astro and is present in almost any CSS bundling process, it can be unexpected if youre not anticipating it. Be sure to inspect your final production build, and please [report any issues][issues] you may come across._
2021-06-28 06:27:12 +00:00
---
2021-05-08 15:35:44 +00:00
## 📚 Advanced Styling Architecture in Astro
2021-05-28 02:05:29 +00:00
Too many development setups take a hands-off approach to CSS, or at most leave you with only contrived examples that dont get you very far. Telling developers “Use whatever styling solution you want!” is a nice thought that rarely works out in practice. Few styling approaches lend themselves to every setup. Astro is no different—certain styling approaches _will_ work better than others.
An example to illustrate this: Astro removes runtime JS (even the core framework if possible). Thus, depending on Styled Components for all your styles would be bad, as that would require React to load on pages where its not needed. Or at best, youd get a “[FOUC][fouc]” as your static HTML is served but the user waits for JavaScript to download and execute. Or consider a second example at the opposite end of the spectrum: _BEM_. You _can_ use a completely-decoupled [BEM][bem] or [SMACSS][smacss] approach in Astro. But thats a lot of manual maintenance you can avoid, and it leaves out a lof of convenience of [Astro components][astro-syntax].
We think theres a great middle ground between intuitive-but-slow CSS-in-JS and fast-but-cumbersome global CSS: **Hybrid Scoped + Utility CSS**. This approach works well in Astro, is performant for users, and will be the best styling solution in Astro _for most people_ (provided youre willing to learn a little). So as a quick recap:
2021-05-08 15:35:44 +00:00
2021-05-28 02:05:29 +00:00
**This approach is good for…**
2021-05-08 15:35:44 +00:00
2021-05-28 02:05:29 +00:00
- Developers wanting to try out something new in regard to styling
- Developers that would appreciate some strong opinions in CSS architecture
2021-05-08 15:35:44 +00:00
2021-05-28 02:05:29 +00:00
**This approach is **NOT** good for…**
2021-05-08 15:35:44 +00:00
2021-05-28 02:05:29 +00:00
- Developers that already have strong opinions on styling, and want to control everything themselves
2021-05-08 15:35:44 +00:00
2021-05-28 02:05:29 +00:00
Read on if youre looking for some strong opinions 🙂. Well describe the approach by enforcing a few key rules that should govern how you set your styles:
2021-05-08 15:35:44 +00:00
2021-05-28 02:05:29 +00:00
### Hybrid Scoped + Utility CSS
2021-05-08 15:35:44 +00:00
2021-05-28 02:05:29 +00:00
#### Scoped styles
You dont need an explanation on component-based design. You already know that reusing components is a good idea. And its this idea that got people used to concepts like [Styled Components][styled-components] and [Styled JSX][styled-jsx]. But rather than burden your users with slow load times of CSS-in-JS, Astro has something better: **built-in scoped styles.**
2021-05-08 15:35:44 +00:00
```jsx
---
// src/components/Button.astro -->
---
2021-05-08 15:35:44 +00:00
<style lang="scss">
/* ✅ Locally scoped! */
.btn {
padding: 0.5em 1em;
border-radius: 3px;
font-weight: 700;
}
</style>
<button type="button" class="btn">
<slot></slot>
</button>
2021-05-08 15:35:44 +00:00
```
_Note: all the examples here use `lang="scss"` which is a great convenience for nesting, and sharing [colors and variables][sass-use], but its entirely optional and you may use normal CSS if you wish._
That `.btn` class is scoped within that component, and wont leak out. It means that you can **focus on styling and not naming.** Local-first approach fits in very well with Astros ESM-powered design, favoring encapsulation and reusability over global scope. While this is a simple example, it should be noted that **this scales incredibly well.** And if you need to share common values between components, [Sass module system][sass-use] also gets our recommendation for being easy to use, and a great fit with component-first design.
By contrast, Astro does allow global styles via the `:global()` escape hatch, however, this should be avoided if possible. To illustrate this: say you used your button in a `<Nav />` component, and you wanted to style it differently there. You might be tempted to have something like:
```jsx
---
// src/components/Nav.astro
2021-05-08 15:35:44 +00:00
import Button from './Button.astro';
---
<style lang="scss">
.nav :global(.btn) {
/* ❌ This will fight with <Button>s styles */
2021-05-08 15:35:44 +00:00
}
</style>
<nav class="nav">
<Button>Menu</Button>
</nav>
2021-05-08 15:35:44 +00:00
```
2021-05-28 02:05:29 +00:00
This is undesirable because now `<Nav>` and `<Button>` fight over what the final button looks like. Now, whenever you edit one, youll always have to edit the other, and they are no longer truly isolated as they once were (now coupled by a bidirectional styling dependency). Its easy to see how this pattern only has to repeated a couple times before being afraid that touching any styles _anywhere_ may break styling in a completely different part of the app (queue `peter-griffin-css-blinds.gif`).
2021-05-08 15:35:44 +00:00
Instead, let `<Button>` control its own styles, and try a prop:
```jsx
---
// src/components/Button.astro
const { theme } = Astro.props;
2021-05-08 15:35:44 +00:00
---
<style lang="scss">
.btn {
/* ✅ <Button> is now back in control of its own styling again! */
2021-05-08 15:35:44 +00:00
[data-theme='nav'] {
// nav-friendly styles here…
}
}
</style>
<button type="button" data-theme={theme}>
<slot></slot>
</button>
2021-05-08 15:35:44 +00:00
```
Elsewhere, you can use `<Button theme="nav">` to set the type of button it is. This preserves the contract of _Button is in charge of its styles, and Nav is in charge of its styles_, and now you can edit one without affecting the other. The worst case scenario of using global styles is that the component is broken and unusable (its missing part of its core styles). But the worst case scenario of using props (e.g. typo) is that a component will only fall back to its default, but still usable, state.
2021-05-28 02:05:29 +00:00
💁 **Why this works well in Astro**: Astro is inspired most by JavaScript modules: you only need to know about whats in one file at a time, and you never have to worry about something in a remote file affecting how this code runs. But were not alone in this; Vue and Svelte have both capitalized on and popularized the idea that styles and markup are natural fits in the same component file. [You can still have separation of concerns][peace-on-css] even with markup, styling, and logic contained in one file. In fact, thats what makes component design so powerful! So write CSS without fear that you picked a name thats used by some other component across your app.
#### Utility CSS
2021-05-08 15:35:44 +00:00
Recently there has been a debate of all-scoped component styles vs utility-only CSS. But we agree with people like Sarah Dayan who ask [why cant we have both][utility-css]? Truth is that while having scoped component styles are great, there are still hundreds of times when the websites coming together when two components just dont line up _quite_ right, and one needs a nudge. Or different text treatment is needed in one component instance.
2021-05-28 02:05:29 +00:00
While the thought of having perfect, pristine components is nice, its unrealistic. No design system is absoutely perfect, and every design system has inconsistencies. And its in reconciling these inconsistencies where components can become a mess without utility CSS. Utility CSS is great for adding minor tweaks necessary to get the website out the door. But they also are incomplete on their own—if youve ever tried to manage responsive styles or accessible focus states with utility CSS it can quickly become a mess! **Utility CSS works best in partnership with component (scoped) CSS**. And in order to be as easy as possible to use, Utility CSS should be global (arguably should be your only global CSS, besides maybe reset.css) so you dont have to deal with imports all willy-nilly.
2021-05-08 15:35:44 +00:00
2021-05-28 02:05:29 +00:00
Some great problems best handled with Utility CSS are:
2021-05-08 15:35:44 +00:00
- [margin](https://github.com/drwpow/sass-utils#-margin--padding)
- [padding](https://github.com/drwpow/sass-utils#-margin--padding)
- [text/background color](https://github.com/drwpow/sass-utils#-color)
- [font size and family](https://github.com/drwpow/sass-utils#%F0%9F%85%B0%EF%B8%8F-font--text)
- [default element styling](https://github.com/kognise/water.css)
In Astro, we recommend the following setup for this:
```html
<head>
<link rel="stylesheet" href="/styles/global.css" />
</head>
```
And in your local filesystem, you can even use Sass [@use][sass-use] to combine files together effortlessly:
```
├── public/
│ └── styles/
│ ├── _base.scss
│ ├── _tokens.scss
│ ├── _typography.scss
│ ├── _utils.scss
│ └── global.scss
└── src/
2021-05-28 02:05:29 +00:00
└── (pages)
2021-05-08 15:35:44 +00:00
```
Whats in each file is up to you to determine, but start small, add utilities as you need them, and youll keep your CSS weight incredibly low. And utilities you wrote to meet your real needs will always be better than anything off the shelf.
2021-05-28 02:05:29 +00:00
So to recap, think of scoped styles as the backbone of your styles that get you 80% of the way there, and utility CSS filling in the remaining 20%. They both work well in tandem, with each compensating for the others weakness.
💁 **Why this works well in Astro**: Astro was built around the idea of **Scoped CSS and Global Utility CSS living together in harmony** ♥️! Take full advantage of it.
2021-05-08 15:35:44 +00:00
2021-05-28 02:05:29 +00:00
### More suggestions
2021-05-08 15:35:44 +00:00
2021-05-28 02:05:29 +00:00
”But wait!” you may ask, having read the previous section. ”That doesnt take care of [my usecase]!” If youre looking for more pointers on some common styling problems, you may be interested in the following suggestions. These all are cohesive, and fit with the **Hybrid Scoped + Utility** philosphy:
1. Split your app into Layout Components and Base Components
1. Avoid Flexbox and Grid libraries (write your own!)
1. Avoid `margin` on a component wrapper
1. Avoid global media queries
#### Suggestion #1: Split your app into Layout Components and Base Components
While this guide will never be long enough to answer the question _”How should a page be laid out?”_ (thats a [design problem!][cassie-evans-css]) there is a more specific question hiding within that we _can_ answer: _“Given a layout, how should components/styles be organized?”_ The answer is **dont bake layout into components.** Have layout components that control layout, and base components (buttons, cards, etc.) that dont control layout. _What does that mean?_ Lets walk through an example so its more clear. Pretend we have a page that looks like this (numbers for different components):
2021-05-08 15:35:44 +00:00
```
|---------------|
| 1 |
|-------+-------|
| 2 | 2 |
|---+---|---+---|
| 3 | 3 | 3 | 3 |
|---+---+---+---|
| 3 | 3 | 3 | 3 |
|---+---+---+---|
```
The layout consists of a big, giant, full-width post at top, followed by two half-width posts below it. And below that, we want a bunch of smaller posts to fill out the rest of the page. For simplicity, well just call these `<BigPost>` (1), `<MediumPost>` (2), and `<SmallPost>` (3). We add them to our page like so:
```jsx
---
// src/pages/index.astro
import Nav from '../components/Nav.astro';
import BigPost from '../components/BigPost.astro';
import Grid from '../components/Grid.astro';
2021-05-28 02:05:29 +00:00
import MediumPosts from '../components/MediumPosts.astro';
import SmallPosts from '../components/SmallPosts.astro';
2021-05-08 15:35:44 +00:00
import Footer from '../components/Footer.astro';
---
<html>
<body>
<Nav />
<Grid>
<BigPost />
<MediumPosts />
<SmallPosts />
</Grid>
<Footer />
</body>
</html>
```
2021-05-28 02:05:29 +00:00
This _looks_ clean, but looks can be deceiving. At first glance, we may think that `<Grid>` is controlling the layout, but thats an illusion. We actually have `<BigPost>` handling its own width, `<MediumPosts>` loading 2 components and controlling its width, and `<SmallPosts>` loading 4+ components and controlling its width. In total, including `<Grid>`, that means **4 components** are all fighting over the same layout. Remove one post from `<MediumPosts>`, the layout breaks. Edit `<BigPost>`, the layout breaks. Edit `<Grid>`, the layout breaks. If you think about it, none of these components are truly reusable—they might as well just be one big file.
2021-05-08 15:35:44 +00:00
2021-05-28 02:05:29 +00:00
This is actually the **Global CSS Problem** in disguise—multiple components fight over how they all lay out together, without layout being one, central responsibility (kinda like global CSS)! Now that we identified the problem, one way to fix this is to hoist the entire layout to the top level, and load all components there, too:
2021-05-08 15:35:44 +00:00
```jsx
---
// src/pages/index.astro
import Nav from '../components/Nav.astro';
import BigPost from '../components/BigPost.astro';
import MediumPost from '../components/MediumPost.astro';
import SmallPost from '../components/SmallPost.astro';
import Footer from '../components/Footer.astro';
---
<html>
<head>
<style lang="scss">
.wrapper {
max-width: 60rem;
margin-right: auto;
margin-left: auto;
padding-right: 2rem;
padding-left: 2rem;
}
.grid {
display: grid;
grid-gap: 1.5rem;
grid-template columns: 1fr 1fr 1fr 1fr;
}
.big-post {
grid-column: span 4;
}
.medium-post {
grid-column: span 2;
}
.small-post {
grid-column: span 1;
}
</style>
</head>
<body>
<Nav />
<div class="wrapper">
<div class="grid">
<div class="big-post"><BigPost postId={12345} /></div>
<div class="medium-post"><MediumPost postId={12345} /></div>
<div class="medium-post"><MediumPost postId={12345} /></div>
<div class="small-post"><SmallPost postId={12345} /></div>
<div class="small-post"><SmallPost postId={12345} /></div>
<div class="small-post"><SmallPost postId={12345} /></div>
<div class="small-post"><SmallPost postId={12345} /></div>
<div class="small-post"><SmallPost postId={12345} /></div>
<div class="small-post"><SmallPost postId={12345} /></div>
<div class="small-post"><SmallPost postId={12345} /></div>
<div class="small-post"><SmallPost postId={12345} /></div>
</div>
</div>
<Footer />
</body>
</html>
```
2021-05-28 02:05:29 +00:00
Getting over that this is more code, its actually a much cleaner separation. What was a four-component layout is now managed 100% within the top-level `index.astro` (which we can now consider a **Layout Component**, and if we wanted to reuse this we could extract this into its own file). Your layout is centralized, and now these components truly are reusable because they dont care one bit about whether theyre in the same grid or not. You can edit styles in any of these files now without fear of styles breaking in another.
2021-05-08 15:35:44 +00:00
2021-05-28 02:05:29 +00:00
The basic rule is that when orchestrating multiple components, **thats a unique responsibility** that should live in one central place, rather than split between 4 components as we were doing. In fact, top-level pages are great at this, and should always be the starting point of your layout components. See how far you can take it, and only extract layout components when you absolutely have to.
2021-05-08 15:35:44 +00:00
2021-05-28 02:05:29 +00:00
To recap: **if you have to touch multiple files to manage one layout, you probably need to reorganize everything into a Layout Component.**
💁 **Why this works well in Astro**: In Astro, anything can be a `.astro` component, and you never incur performance problems no matter how many components you add. But the main benefit to [Layout isolation][layout-isolated] is how much it cuts down on the amount of CSS you need.
2021-05-28 02:05:29 +00:00
#### Suggestion #2: Avoid Flexbox and Grid libraries (write your own!)
2021-05-08 15:35:44 +00:00
This may feel like a complete overreach to tell you not to use your favorite layout framework youre familiar with. After all, its gotten you this far! But the days of [float madness](https://zellwk.com/blog/responsive-grid-system/) are gone, replaced by Flexbox and Grid. And the latter dont need libraries to manage them (often they can make it harder).
Many front-end developers experience the following train of thought:
1. I should reuse as much CSS as possible (_good!_)
2. Many pages reuse the same layout, … (_hold up—_)
3. … therefore I can find an existing solution to manage all my duplicate layouts (_wait a minute—_)
While the logic is sound, the reality is that #2 isnt truth for many projects. Probably, many parts of the website werent designed to fit into these nice, neat, 12 column grids. Even modest web apps can contain _hundreds_ of unique layouts when you factor in all the breakpoints. Ask yourself: _If the website Im building really contains so many unique layouts, why am I using a heavy grid library that only gives me generic layouts?_
2021-05-08 15:35:44 +00:00
A few well-written lines of CSS Grid here and there will not only be perfect in every occasion; its likely lighter and easier to manage than that heavy library youve fought with for so long. Another way to look at it: if you have to spend a couple hours learning a proprietary styling framework, wrestling with it, filing issues, etc., why not just spend that time on Flexbox and Grid instead? For many people, learning the basics only takes an hour, and that can get you pretty far! There are great, free, learning resources that are worth your time:
2021-05-08 15:35:44 +00:00
- [Flexbox Froggy](https://flexboxfroggy.com/)
- [CSS Grid Garden](https://cssgridgarden.com/)
So in short: stop trying to deduplicate layouts when theres nothing to deduplicate! Youll find your styles not only easier to manage, but your CSS payloads much lighter, and load times faster.
2021-05-28 02:05:29 +00:00
💁 **Why this works well in Astro**: grid libraries are a quick path to stylesheet bloat, and a major contributor to people attempting to [treeshake their styles][css-treeshaking]. Astro does **not** treeshake unused CSS for you, because [that can cause problems][css-treeshaking]. Were not saying you have to be library free; were big fans of libraries like [Material UI][material-ui]. But if you can at least shed the thousands upon thousands of layouts youre not using from your styling library, you probably dont need automatic treeshaking.
#### Suggestion #3: Avoid `margin` on a component wrapper
2021-05-08 15:35:44 +00:00
In other words, dont do this:
```jsx
<!-- src/components/MyComponent.astro -->
<style lang="scss">
.wrapper {
/* ❌ Dont do this! */
margin-top: 3rem;
}
</style>
<div class="wrapper"></div>
```
If you remember the [CSS box model][box-model], `margin` extends beyond the boundaries of the box. This means that when you place `margin` on the outermost element, now that will push other components next to it. Even though the styles are scoped, its _technically_ affecting elements around it, so it [breaks the concept of style containment][layout-isolated].
2021-05-08 15:35:44 +00:00
When you have components that rearrage, or appear different when theyre next to other components, thats a hard battle to win. **Components should look and act the same no matter where they are placed.** Thats what makes them components!
2021-05-28 02:05:29 +00:00
💁 **Why this works well in Astro**: margins pushing other components around creeps into your styling architecture in sneaky ways, and can result in the creation of some wonky or brittle layout components. Avoiding it altogether will keep your layout components simpler, and youll spend less time styling in general.
2021-05-08 15:35:44 +00:00
2021-05-28 02:05:29 +00:00
#### Suggestion #4: Avoid global media queries
2021-05-08 15:35:44 +00:00
2021-05-28 02:05:29 +00:00
The final point is a natural boundary of **Scoped Styles**. That extends to breakpoints, too! You know that one, weird breakpoint where your `<Card />` component wraps awkardly at a certain size? You should handle that within `<Card />`, and not anywhere else.
2021-05-08 15:35:44 +00:00
Even if you end up with some random value like `@media (min-width: 732px) {`, thatll probably work better than trying to create a global [magic number][magic-number] somewhere that only applies to one context (an arbitrary value may be “magic” to the rest of an app, but it does still have meaning within the context of a component that needs that specific value).
Granted, this has been near-impossible to achieve until Container Queries; fortunately [they are finally landing!][container-queries]
Also, a common complaint of this approach is when someone asks _”What if I have 2 components that need to do the same thing at the same breakpoint?”_ to which my answer is: youll always have one or two of those; just handle those as edge cases. But if your entire app is made up of dozens of these cases, perhaps your component lines could be redrawn so that theyre more [layout-isolated][layout-isolated] in general.
2021-05-28 02:05:29 +00:00
💁 **Why this works well in Astro**: this is probably the least important point, which is why its saved for last. In fact, you could probably skip this if it doesnt work for you. But its something that people try to architect for at scale, and having a global system to manage this can often be unnecessary. Give _not_ architecting for global media queries a try, and see how far it takes you!
2021-05-08 15:35:44 +00:00
### 👓 Further Reading
This guide wouldnt be possible without the following blog posts, which expand on these topics and explain them in more detail. Please give them a read!
- [**Layout-isolated Components**][layout-isolated] by Emil Sjölander
- [**In defense of utility-first CSS**][utility-css] by Sarah Dayan
Also please check out the [Stylelint][stylelint] project to whip your styles into shape. You lint your JS, why not your CSS?
[astro-syntax]: ./syntax.md
2021-04-20 23:15:47 +00:00
[autoprefixer]: https://github.com/postcss/autoprefixer
2021-05-08 15:35:44 +00:00
[bem]: http://getbem.com/introduction/
[box-model]: https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/The_box_model
2021-04-20 23:15:47 +00:00
[browserslist]: https://github.com/browserslist/browserslist
[browserslist-defaults]: https://github.com/browserslist/browserslist#queries
2021-05-28 02:05:29 +00:00
[cassie-evans-css]: https://twitter.com/cassiecodes/status/1392756828786790400?s=20
2021-05-08 15:35:44 +00:00
[container-queries]: https://ishadeed.com/article/say-hello-to-css-container-queries/
2021-04-20 23:15:47 +00:00
[css-modules]: https://github.com/css-modules/css-modules
2021-05-28 02:05:29 +00:00
[css-treeshaking]: https://css-tricks.com/how-do-you-remove-unused-css-from-a-site/
[fouc]: https://en.wikipedia.org/wiki/Flash_of_unstyled_content
2021-05-08 15:35:44 +00:00
[layout-isolated]: https://visly.app/blogposts/layout-isolated-components
[issues]: https://github.com/snowpackjs/astro/issues
2021-05-08 15:35:44 +00:00
[magic-number]: https://css-tricks.com/magic-numbers-in-css/
2021-05-28 02:05:29 +00:00
[material-ui]: https://material.io/components
[peace-on-css]: https://didoo.medium.com/let-there-be-peace-on-css-8b26829f1be0
2021-04-20 23:15:47 +00:00
[sass]: https://sass-lang.com/
[sass-use]: https://sass-lang.com/documentation/at-rules/use
2021-05-08 15:35:44 +00:00
[smacss]: http://smacss.com/
[styled-components]: https://styled-components.com/
[styled-jsx]: https://github.com/vercel/styled-jsx
[stylelint]: https://stylelint.io/
2021-04-20 23:15:47 +00:00
[svelte-style]: https://svelte.dev/docs#style
[tailwind]: https://tailwindcss.com
[tailwind-utilities]: https://tailwindcss.com/docs/adding-new-utilities#using-css
2021-05-08 15:35:44 +00:00
[utility-css]: https://frontstuff.io/in-defense-of-utility-first-css
[vue-css-modules]: https://vue-loader.vuejs.org/guide/css-modules.html
[vue-scoped]: https://vue-loader.vuejs.org/guide/scoped-css.html