How to render math in Astro - A detailed guide

December 9, 2023

Pretty much the heading. This article aims to de-mystify writing math in Astro for non web developers.

Starting points

I believe the following blog post is a really good starting point - it goes in depth into installing the required plugins - remark-math and rehype-katex.

 Render Math in Astro Markdown Pages with Katex

KaTeX\KaTeX is what we are going to use to render the math from the markdown documents. On a very high level it parses everything within $...$ or $$...$$ in your documents and applies css styles to it. The docs are pretty detailed although it can get somewhat vague at times; check them out here.

Customising KaTeX\KaTeX

As mentioned before, KaTeX\KaTeX does somewhat of a poor job of explaining how to customise the styles in there docs. They outline here how the fonts can be customised (and you should, KaTeX\KaTeX fonts differ considerably from the LaTeX\LaTeX default - Computer Modern Roman)

There is a simpler procedure:

  • Motivation: We want to overwrite the default styles KaTeX\KaTeX applies, as defined in the katex.min.css stylesheet which we saw how to load in the previously referred link.
  • To do this, we will load another local static stylesheet after loading katex.min.css which redefines only those classes we want to modify.
BaseLayout.astro
<link
    rel="stylesheet"
    href="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.css"
    integrity="sha384-n8MVd4RsNIU0tAv4ct0nTaAbDJwPJzDEaqSD1odI+WdtXRGWt2kTvGFasHpSy3SV"
    crossorigin="anonymous"
/>
<!-- Next load the local stylesheet -->
<link rel="stylesheet" href="/styles/katex-custom.css" />
  • Now, where to place this local stylesheet? Referring the Astro docs, local stylesheets are stored in the /public/styles/ directory. This is analogous to how you store fonts in the /public/fonts/ directory.
  • You can load all the custom math fonts you want, override colors and do all sorts of stuff - just have a look at the actual katex.min.css file to refer the name of the classes.

Extras

If you want the exact LaTeX\LaTeX fonts, download them from here. Load them in the katex-custom.css file and you are good to go!