Using css variables for syntax highlighting in Astro
2 min read

I recently learned that there was an incredibly easy way to utilize shiki syntax highlighting with CSS variables in combination with Astro’s CSS variables.

First, we need to update the astro config to to tell Astro that shiki should use css variables.

astro.config.mjs
import { defineConfig } from "astro/config";
import mdx from "@astrojs/mdx";
import tailwind from "@astrojs/tailwind";

// https://astro.build/config
export default defineConfig({
  site: "https://example.com",
  integrations: [mdx(), tailwind()],
  markdown: {
    shikiConfig: {
      theme: "css-variables"
    }
  }
});

Second, define and customize the css variables for Astro in your global.css file.

global.css
@tailwind base;
@tailwind components;
@tailwind utilities;

:root {
  --astro-code-color-text: #c9d1d9;
  --astro-code-color-background: #0d1117;
  --astro-code-token-constant: #79c0ff;
  --astro-code-token-string: #a5d6ff;
  --astro-code-token-comment: #8b949e;
  --astro-code-token-keyword: #ff7b72;
  --astro-code-token-parameter: #ffa657;
  --astro-code-token-function: #d2a8ff;
  --astro-code-token-string-expression: #e3b341;
  --astro-code-token-punctuation: #8b949e;
  --astro-code-token-link: #58a6ff;
}

/* ...other styles */

If you are using tailwind you can also use the tailwind color palette.

global.css
@tailwind base;
@tailwind components;
@tailwind utilities;

:root {
  --astro-code-color-text: theme(colors.zinc.800);
  --astro-code-color-background: theme(colors.zinc.50);
  /* ...other variables */
}
/* ...other styles */

That’s all there is to it!