CSS and Styles in Astro

Learn how to work with global and scoped CSS in Astro.

Astro components were created to be capable of handling CSS right inside each component. Styling can be done through the use of the style tags, making it easy to keep styles associated with a component encapsulated in a single file. In this lesson, we’ll take a look at the following types of CSS:

  • Scoped CSS: This is CSS that is scoped to a component, meaning styles are encapsulated and won’t affect other elements on the page. This approach can be effectively used to avoid conflicting CSS styles.

  • Global CSS: This is CSS that is shared globally, which is the opposite of scoped CSS. When using global CSS, we can reuse the same styles across different components. This approach is useful for CSS resets or sharing commonly used styles.

  • Conditional CSS: This is CSS that is conditionally applied to elements based on a condition. This promotes code reusability because we can use the same elements with the same data with different styles in different places.

  • Inline CSS: This is CSS that is assigned to the element using the style attribute.

Scoped CSS

Let’s take a look at some examples. To turn the background of the page dark and the text light, we can create the following style tag inside the Layout component:

Get hands-on with 1300+ tech skills courses.