Typesetting chemical molecular formulas and equations using KaTeX & mhchem

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:

$${[{\textrm{Ag}(\textrm{N}\textrm{H}_{3}^{})}_{2}]}^{+}$$
$${\textrm{Cr}\textrm{O}_{4}^{}}_{}^{2-}.$$


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

$${[{\textrm{Ag}(\textrm{N}\textrm{H}_{3}^{})}_{2}]}^{+}$$

$${\textrm{Cr}\textrm{O}_{4}^{}}_{}^{2-}.$$

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

$$\ce{[Ag(NH3)2]+}$$
$$\ce{CrO4^2-}.$$


This is what you’ll have:

$$\ce{[Ag(NH3)2]+}$$

$$\ce{CrO4^2-}.$$

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!