Oct 24, 2022

Use Math Formulas and Syntax Highlight in HTML

I use MathJax and Hightlight.js to enable LaTeX-style math inputs and syntax highlights.

MathJax

Download the JSON files from Github and extract it into the hosting folder.

Allow Horizontal Scroll for Long Formulas

Put this in CSS:

mjx-container:is([display]) { width: inherit; overflow-x: auto; overflow-y: hidden; }

Highlight.js

Download the JSON files from the official website and extract it into the hosting folder.

Inline Code and Block Code

I prefer <code></code> for inline code and <div class="code"></div> for block code. This is the CSS I use to render code:

code { font-size: smaller; font-family: LiberationMono, monospace; } .code { font-size: smaller; font-family: LiberationMono, monospace; white-space: pre; width: inherit; overflow-x: auto; overflow-y: hidden; line-height: 1; display: block; }

Note: See how to use Font LiberationMono here.

Specify a Language

We can use classes like <div class="code language-css"> to specify the language.

See a list of supported languages here.

Integration

I found that the best way to integrate everything into every HTML page is to use a script. I include <script src="/frame.js"></script> at the end of every webpage and put the loading code in frame.js:

document.writeln("<script type='text/javascript' async src='/MathJax-3.2.2/es5/tex-chtml.js'></script>"); document.writeln("<link rel ='stylesheet' href ='/highlight/styles/github.min.css' type='text/css'/>"); document.writeln("<script type='text/javascript' src='/highlight/highlight.min.js'></script>"); // Add additional languages for Highlight.js document.writeln("<script src='/highlight/languages/apache.min.js'></script>"); document.writeln("<script src='/highlight/languages/latex.min.js'></script>"); document.writeln("<script type='text/javascript'> document.querySelectorAll('code, div.code').forEach(el => { el.innerHTML = el.innerHTML.replace(/^\\n+|\\n+$/g, ''); hljs.highlightElement(el); }); </script>");

You can check the source code of this page to see how it works!