Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Styles

In Astro, CSS is written right in the component, in a <style> tag. These styles are scoped: they apply only to the markup of this component and do not affect other pages. Rules for the whole site go into a global CSS file.

Component styles

Add a <style> tag at the end of src/components/PostCard.astro:

---
const { title, url } = Astro.props;
---
 
<article>
  <h2><a href={url}>{title}</a></h2>
</article>
 
<style>
  article {
    padding: 1rem;
    border: 1px solid #ddd;
    border-radius: 8px;
  }
  h2 {
    font-size: 1.25rem;
  }
</style>

Open /posts and the cards get a border. h2 headings on other pages do not change: Astro adds a special attribute to the component's elements and rewrites the selectors to match it. You do not need unique class names.

A global CSS file

Rules for the whole site (font, colors, spacing) go into a separate file. Create src/styles/global.css:

/* src/styles/global.css */
body {
  max-width: 720px;
  margin: 0 auto;
  font-family: system-ui, sans-serif;
  line-height: 1.6;
}

Import it in the frontmatter of the layout src/layouts/BaseLayout.astro:

---
import '../styles/global.css';
import Header from '../components/Header.astro';
---

The styles apply to every page that uses this layout. During the build Astro bundles and minifies the CSS.

Global rules inside a component

Sometimes you need to style markup the component does not create itself, such as the HTML of a Markdown post. That is what :global() is for:

<style>
  .content :global(p) {
    margin-bottom: 1rem;
  }
</style>

The rule applies to any paragraphs inside this component's element with the content class.

Conditional classes

The class:list directive builds the class attribute from an array and an object:

---
const { title, isDraft = false } = Astro.props;
---
 
<article class:list={['card', { draft: isDraft }]}>{title}</article>

If isDraft is true, the element gets the classes card draft, otherwise only card.

Tailwind

Tailwind CSS is a set of ready-made utility classes. It is added with one command:

npx astro add tailwind

The command installs the packages and updates the config. In Astro 5 with Tailwind 4 it also creates src/styles/global.css with the line @import "tailwindcss";, and you import this file in the layout. After that classes such as class="text-xl font-bold" work in the markup.

Common mistake

People write styles in the layout's <style> and expect them to style the markup of pages or nested components. Scoped styles apply only to the tags written in the same file. Put shared rules into global.css and component styles into the component's own <style>.

Thanks for reading!

Donate to the site — we work hard for you.