Table of Contents
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
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
As mentioned before, 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, fonts differ considerably from the default - Computer Modern Roman)
There is a simpler procedure:
- Motivation: We want to overwrite the default styles 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.
<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 fonts, download them from here. Load them in the katex-custom.css
file and you are good to go!