Eric J Ma's Website

Help MathJax render correctly by wrapping latex in span tags

written by Eric J. Ma on 2021-05-28 | tags: til blogging


Today I learned that we can help MathJax guarantee correct rendering of LaTeX in HTML and HTML-converted Markdown documents by simply wrapping the latex inside a <span> tag.

For example, if the following equation gives you trouble because the underscore gets parsed by a Markdown parser incorrectly:

$y_{alpha} = 3x^2 + 5$

If it is rendered correctly, you'll see: $y_{alpha} = 3x^2 + 5$

However, if the rendering is butchered somehow, then we can simply add <span> tags around it to guarantee correct parsing:

<span>
$y_{alpha} = 3x^2 + 5$
</span>

With the span tags, it'll look like: $y_{alpha} = 3x^2 + 5$. (Inspect the website source to see how I did it.)

This tip should apply anywhere we use LaTeX inside Markdown and wish to have it render correctly in HTML using MathJax. Some examples of documents where this might be useful is in:

  1. Jupyter Notebooks
  2. vanilla Markdown files,
  3. Markdown blocks in YAML files that get parsed.

I send out a newsletter with tips and tools for data scientists. Come check it out at Substack.

If you would like to sponsor the coffee that goes into making my posts, please consider GitHub Sponsors!

Finally, I do free 30-minute GenAI strategy calls for organizations who are seeking guidance on how to best leverage this technology. Consider booking a call on Calendly if you're interested!