Typesetting chemical molecular formulas and equations using KaTeX & mhchem

Last modified date

Comments: 0

Using KaTeX or MathJax without extensions, you’ll soon get tired of typesetting chemical molecular formulas and equations because of the time-consuming details such as super- and subscripts. Let’s take the following as example formulas:


But please note that I use the dollar sign as a rendering delimiter for KaTeX as well as for LaTeX. Those lines are converted as



Using the mhchem extension, however, you can display the same formulas effortlessly. With the extension loaded, the following is valid to use:


This is what you’ll have:



The same goes for chemical equations. These equations relate to the water electrolysis:

  • Cathode (reduction): $\ce{2H2O(l) + 2e- -> H2(g) + 2OH-(aq)}$
  • Anode (oxidation): $\ce{4OH-(aq) -> 2H2O(l) + O2(g) + 4e-}$

To display the equations, I wrote simple lines as shown below:

$\ce{2H2O(l) + 2e- -> H2(g) + 2OH-(aq)}$
$\ce{4OH-(aq) -> 2H2O(l) + O2(g) + 4e-}$

By now, you might have wanted to ask me how to load the extension. It’s not tricky at all. Append the following to the line where KaTeX is called:

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/contrib/mhchem.min.js"></script>

It’s just part of the mhchem manual although I added “defer” to every relevant script element. Let’s write formulas and equations without tedious work!

Leave a Reply

Your email address will not be published. Required fields are marked *

Post comment