Kevin Kiningham About Archive Feed

Rendering math with KaTeX

KaTeX is an open source javascript library for typesetting equations. To use it on a static site (like GitHub pages), add the following.

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.10.0-rc.1/dist/katex.min.css" integrity="sha384-D+9gmBxUQogRLqvARvNLmA9hS2x//eK1FhVb9PiU86gmcrBrJAQT8okdJ4LMp2uv" crossorigin="anonymous">
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.10.0-rc.1/dist/katex.min.js" integrity="sha384-483A6DwYfKeDa0Q52fJmxFXkcPCFfnXMoXblOkJ4JcA8zATN6Tm78UNL72AKk+0O" crossorigin="anonymous"></script>

If you want to render equations automatically, KaTeX includes an extension that will attempt to render all text elements on page load.

<script defer src="https://cdn.jsdelivr.net/npm/katex@0.10.0-rc.1/dist/contrib/auto-render.min.js" integrity="sha384-yACMu8JWxKzSp/C1YV86pzGiQ/l1YUfE8oPuahJQxzehAjEt2GiQuy/BIvl9KyeF" crossorigin="anonymous"></script>
<script>
    document.addEventListener("DOMContentLoaded", function() {
        renderMathInElement(document.body, {
            // ...options...
        });
    });
</script>

For more control, you can also manually render elements. For example, on this site I use Kramdown, which embeds equations in a <script type="math/text"> element. To typeset, I use katex.renderToString and replace each element with a bit of jquery.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
  document.addEventListener("DOMContentLoaded", function() {
    $("script[type='math/tex']").replaceWith(
      function(){
        var tex = $(this).text();
        return "<span class=\"inline-equation\">" +
               katex.renderToString(tex) +
               "</span>";
    });

    $("script[type='math/tex; mode=display']").replaceWith(
      function(){
        var tex = $(this).text();
        return "<div class=\"equation\">" +
               katex.renderToString("\\displaystyle "+tex) +
               "</div>";
    });
  });
</script>

Examples

Math in a figure element

The pdf of the Guassian distribution

Math in a block

Math inline: