-
Create a file in your theme directory
layouts/partials/mathjax_support.html
as the following:<script> MathJax = { tex: { inlineMath: [['$', '$'], ['\\(', '\\)']], displayMath: [['$$','$$'], ['\\[', '\\]']], processEscapes: true, processEnvironments: true }, options: { skipHtmlTags: ['script', 'noscript', 'style', 'textarea', 'pre'] } }; window.addEventListener('load', (event) => { document.querySelectorAll("mjx-container").forEach(function(x){ x.parentElement.classList += 'has-jax'}) }); </script> <script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script> <script type="text/javascript" id="MathJax-script" async src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js"></script>
-
Next, open the file
layouts/partials/header.html
and add the following line just before the closing</head>
tag:{{ if .Params.mathjax }}{{ partial "mathjax_support.html" . }}{{ end }}
-
Then, add the following lines to your CSS file. You may need to tinker with the contents here depending on your theme, these are just the settings which worked for me.
code.has-jax { -webkit-font-smoothing: antialiased; background: inherit !important; border: none !important; font-size: 100%; }
-
Finally, add
mathjax: true
to the YAML frontmatter of any pages containing math markup. Alternatively, you could omit the outer{{ if .Params.mathjax }} … {{ end }}
conditional above to load the library automatically on all pages. However given that this library is quite heavy (it’s consistently the asset that Google PageSpeed Insights complains the most about) and that only <20% of my blog posts contain math at all, this is worth the extra effort for me.
Reference
- https://geoffruddock.com/math-typesetting-in-hugo/
- https://bwaycer.github.io/hugo_tutorial.hugo/tutorials/mathjax/