# đ
Styling
Styling in Astro is meant to be as flexible as youâd 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 donât need dynamic values)_
All styles in Astro are automatically [**autoprefixed**](#-autoprefixer) and optimized, so you can just write CSS and weâll handle the rest â¨.
## đ Quick Start
##### Astro
Styling in an Astro component is done by adding a `
Iâm a scoped style and only apply to this component
I have both scoped and global styles
```
**Tips**
- `
```
_Note: all the examples here use `lang="scss"` which is a great convenience for nesting, and sharing [colors and variables][sass-use], but itâs entirely optional and you may use normal CSS if you wish._
That `.btn` class is scoped within that component, and wonât leak out. It means that you can **focus on styling and not naming.** Local-first approach fits in very well with Astroâs 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 ` ` component, and you wanted to style it differently there. You might be tempted to have something like:
```jsx
---
import Button from './Button.astro';
---
Menu
```
This is undesirable because now `` and `` fight over what the final button looks like. Now, whenever you edit one, youâll always have to edit the other, and they are no longer truly isolated as they once were (now coupled by a bidirectional styling dependency). Itâs easy to see how this pattern only has to repeated a couple times before editing one file breaks the styles of another.
Instead, let `` control its own styles, and try a prop:
```jsx
---
export let theme;
---
```
Elsewhere, you can use `` 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 (itâs 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.
#### 2. Use utility CSS
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 canât we have both][utility-css]? Truth is that while having scoped component styles are great, there are still hundreds of times when the websiteâs coming together when two components just donât line up _quite_ right, and one needs a nudge. Or different text treatment is needed in one component instance.
While the thought of having perfect, pristine components is nice, itâs unrealistic. No design system is absoutely perfect, and every design system has inconsistencies. And itâs 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. And utilities work best when theyâre globally-available so you donât have to deal with imports all willy-nilly.
Some great examples of Utility (and Global) CSS are:
- [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
```
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/
âââ âŚ
```
Whatâs in each file is up to you to determine, but start small, add utilities as you need them, and youâll keep your CSS weight incredibly low. And utilities you wrote to meet your real needs will always be better than anything off the shelf.
Is utility CSS capable of building entire apps? **No!** It becomes very unwieldy trying to create components entirely out of them. Or if youâre managing breakpoints (media queries), or when you are handling interactions like `:hover`, `:focus`, or even animation. Think of component styles as the backbone of a healthy style architecture 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 otherâs weakness.
#### 3. Centralize your layouts
While this guide will never be long enough to answer the question _âHow should a page be laid out?â_ thereâs a subtle, but important question within that field that is critical to get right: _âGiven a layout, how should components/styles be organized?â_ This question has more of a right or wrong answer, but it will take a little bit of explaining in the form of an example to communicate the general concept. Imagine that we are starting with a layout like so:
```
|---------------|
| 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, weâll just call these `` (1), `` (2), and `` (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';
import MediumPosts from '../components/MediumPost.astro';
import SmallPosts from '../components/SmallPost.astro';
import Footer from '../components/Footer.astro';
---
```
This is very clean, and all our components are isolated. This is correct, right? Well, not so muchâthis is about the worst way to compose the layout. Because thereâs no CSS in our top level, we can assume that the layout CSS doesnât exist in one place; itâs evenly split between four components: ``, ``, ``, and ``. 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. And because the layout is an implicit contract between 4 components, your layout is brittle, and it will always break unless you edit all 4 components together. In other words, youâve created one big component split into 4 files.
Further, this limits the reusable power of these components. Because now they canât be used outside of a ``, they arenât that reusable and youâll probably create clones of each. Or if they can live outside ``, you now have to manage multiple variations of all components that could be avoided. **Components should display the same regardless of placement**, and layouts that require specific combinations and orderings of components is a poor system.
By contrast, letâs see how weâd fix this:
```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';
---
```
This is much betterâ`index.astro` now manages 100% of the layout, and the components manage 0%. Your layout is centralized, and now these components truly are reusable because they donât care one bit about whether theyâre in the same grid or not. You can edit styles in any of these files now without fear of styles breaking in another.
The basic rule is that when orchestrating multiple components, **thatâs a unique responsibility** that should live in one and only one place. That can be in the form of page styles (like here), and thatâs a great starting point. But you can also extract layouts to their own layout components, just as long as they remain in one place.
#### 4. Donât use a Flexbox or Grid library; write it custom
This may feel like a complete overreach to tell you not to use your favorite layout framework youâre familiar with. After all, itâs 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 donât 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 and the first point is correct, many developers assume #2 is correct when that is not the reality for many. Many projects contain myriad layouts that are different from one part of a website to another. And even if they are the same on one breakpoint doesnât mean they are the same on all breakpoints!
Ask yourself: _If there really were more unique layouts in my website than I assumed, why am I trying to deduplicate them?_ Youâll probably start to realize that fewer of your layouts are reusable than you thought, and that a few, thoughtful, custom layout components can handle all your needs. This is especially true when you **Centralize your Layouts** (Rule #3).
Another way to look at it: perhaps spending a couple hours learning Flexbox and Grid will pay off much better than spending that same amount of time learning a proprietary styling framework, wrestling with it, and/or switchign it out when it doesnât perform as expected. There are great, free, learning resources that are worth your time:
- [Flexbox Froggy](https://flexboxfroggy.com/)
- [CSS Grid Garden](https://cssgridgarden.com/)
So in short: stop trying to deduplicate layouts when thereâs nothing to deduplicate! Youâll find your styles not only easier to manage, but your CSS payloads much lighter, and load times faster.
#### 5. Never use `margin` on a component wrapper
In other words, donât do this:
```jsx
```
If you remember the [CSS box model][box-model], `margin` extends beyond the boundarieso 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, itâs _technically_ affecting elements around it, so it [breaks the concept of style containment][layout-isolated].
When you have components that rearrage, or appear different when theyâre next to other components, thatâs a hard battle to win. **Components should look and act the same no matter where they are placed.** Thatâs what makes them components!
đ **Why this helps Astro styling**: 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 youâll spend less time styling in general.
#### 6. Donât use global media queries
The final point is a natural extension of the **Prefer Component-scoped styles** rule. That extends to breakpoints, too! You know that one, weird breakpoint where your ` ` component wraps awkardly at a certain size? You should handle that within ` `, and not anywhere else.
Even if you end up with some random value like `@media (min-width: 732px) {`, thatâll 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: youâll 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 theyâre more [layout-isolated][layout-isolated] in general.
đ **Why this helps Astro styling**: this is probably the least-important point, which is why itâs saved for last. But itâs 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!
### đ Further Reading
This guide wouldnât 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
[autoprefixer]: https://github.com/postcss/autoprefixer
[bem]: http://getbem.com/introduction/
[box-model]: https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/The_box_model
[browserslist]: https://github.com/browserslist/browserslist
[container-queries]: https://ishadeed.com/article/say-hello-to-css-container-queries/
[css-modules]: https://github.com/css-modules/css-modules
[layout-isolated]: https://visly.app/blogposts/layout-isolated-components
[magic-number]: https://css-tricks.com/magic-numbers-in-css/
[sass]: https://sass-lang.com/
[sass-use]: https://sass-lang.com/documentation/at-rules/use
[smacss]: http://smacss.com/
[styled-components]: https://styled-components.com/
[styled-jsx]: https://github.com/vercel/styled-jsx
[stylelint]: https://stylelint.io/
[svelte-style]: https://svelte.dev/docs#style
[tailwind]: https://tailwindcss.com
[tailwind-utilities]: https://tailwindcss.com/docs/adding-new-utilities#using-css
[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