🛸Astroで構築したページをCSSでスタイリングする

イントロダクション

今回は、Astroで構築したページをCSSでスタイリングする方法について解説します。

AstroでCSSを使う方法

cssファイルを作成して読み込むという方法もありますが、今回はコンポーネント内にstyleタグを追加してスタイリングする方法を解説します。
この方法を使うメリットですが、Astro側で自動的にスコープしてくれるので、同じコンポーネント内でのみ適用される為、CSS設計を意識しなくてもよくなります。

以下の例では、index.astroとFooter.astro内にそれぞれ<h2>要素があるので、Footer.astroの<h2>要素にのみstyleタグを追加して文字の色を変えてみます。

---
import Head from "../components/Head.astro";
import Header from "../components/Header.astro";
import Footer from "../components/Footer.astro";
import Button from "../components/Button.astro";
---

<html lang="ja">
	<Head />
	<body>
		<Header />
		<main>
			<h1>Astro demo</h1>
			<h2>Astroのデモページです。</h2>
			<Button text="about" href="/about" primary />
			<Button text="contact" href="/contact"/>
		</main>
		<Footer />
	</body>
</html>
index.astro
---
import MenuList from "./MenuList.astro"
---
<footer>
  <h2>フッターのリンク</h2>
  <MenuList />
</footer>

<style>
  h2 {
    color: blue;
  }
</style>
Footer.astro

結果はこちらです。

image block
image block

index.astroに書かれた<h2>要素は何もclassが割り当てられていないですが、Footer.astroに書かれた<h2>要素にはastro-SZ7XMLTEというclassが割り当てられているのが検証ツールでも分かるかと思います。ちなみに全体に適用したい場合にはstyleタグにis:globalという属性を追加すれば全体に適用させることができます。

---
import MenuList from "./MenuList.astro"
---
<footer>
  <h2>フッターのリンク</h2>
  <MenuList />
</footer>

<style is:global>
  h2 {
    color: blue;
  }
</style>
Footer.astro
image block

全体に適用したいものはこれで対応できます。

SCSSの導入方法

AstroではSassで書くこともできます。その際は、npm i -D sassもしくはyarn add -D sassでしてから使ってください。使い方は簡単で先程のstyleタグにlang="scss"を追加するだけで使用できます。

<style lang="scss">
  h2 {
    color: red;
  }
</style>
Footer.astro

mixinやfunctionをまとめたファイルをAstroのコンポーネント内で読み込みたいときは、このようにしています。
まず、srcフォルダの中にstylesフォルダを作成し、更にその中にscssフォルダを作成して、その中にmixinなどのファイルを入れます。今回は例として_global.scssというファイルとそれを読み込む為のindex.sccファイルを作成します。

image block
$primary-color: purple;
$secondary-color: lightgreen;
_global.scss
@forward "./_global.scss"
index.scss

次に_global.scssで定義した変数をFooter.astroで読み込みします。

---
import MenuList from "./MenuList.astro"
---
<footer>
  <h2>フッターのリンク</h2>
  <MenuList />
</footer>

<style lang="scss">
  @import "../styles/scss/index";
  h2 {
    color: $primary-color;
  }
</style>
Footer.astro

styleタグ内でimportすれば、別のファイルで定義している変数を使用できました。

まとめ

Astroで構築したページにCSSを適用する方法について解説しました。
srcフォルダにcssファイルを作成して読み込むこともできますが、Astro側でスコープしてくれ、コンポーネント1つにHTMLとCSSの両方が記述されている方が見直しや修正はしやすいかと思うので、styleタグを使ってのコーディングが個人的には気に入ってます。今まで作ったmixinとかも使えますしね。
以上、Astroでのcssスタイリング方法でした。