
KaTeX is an open-source JavaScript library for rendering LaTeX math on web pages.
It renders equations synchronously in the browser and supports server-side rendering with Node.js.
Features
- Inline and display math with support for fractions, roots, integrals, matrices, and multiline equations.
- Automatic rendering of delimited formulas in HTML text.
- HTML output with MathML for assistive technologies.
- Custom TeX macros for reusable mathematical notation.
- Equation alignment, manual numbering, and configurable rule thickness.
- Optional extensions for chemical equations and copying the original LaTeX source.
- Free for personal and commercial projects.
How to Use It
Basic Usage
Load the KaTeX stylesheet and JavaScript from a CDN.
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex/dist/katex.min.css"> <script src="https://cdn.jsdelivr.net/npm/katex/dist/katex.min.js"></script>
Pass the expression directly to katex.render() with the target element. Use String.raw to preserve TeX backslashes in JavaScript template literals.
<div id="block-math"></div>
katex.render("y = x^2", document.getElementById("inline-math"));
katex.render(
String.raw`\int_0^1 x^2\,dx = \frac{1}{3}`,
document.getElementById("block-math"),
{ displayMode: true }
);Advanced Usage
1. Render LaTeX automatically inside HTML.
Use the auto-render extension to typeset formulas inside an article or other HTML container. Write inline math between \( and \), and display math between $$ delimiters.
<article id="math-content">
<p>The area of a circle is \(A = \pi r^2\).</p>
<p>$$\sum_{k=1}^{n} k = \frac{n(n+1)}{2}$$</p>
</article>
<script>
renderMathInElement(document.getElementById("math-content"));
</script>To write inline math as $...$, replace the render call above with the following configuration.
renderMathInElement(document.getElementById("math-content"), {
delimiters: [
{ left: "$$", right: "$$", display: true },
{ left: "$", right: "$", display: false },
{ left: "\\(", right: "\\)", display: false },
{ left: "\\[", right: "\\]", display: true }
],
throwOnError: false
});2. Create a live equation preview.
Render the textarea value on each input event. For user-entered expressions, keep trust: false and set input length, macro expansion, and size limits.
<label for="latex-input">LaTeX expression</label>
<textarea id="latex-input" maxlength="1000">\frac{x^2+1}{x+1}</textarea>
<div id="math-preview"></div>
<script>
const input = document.getElementById("latex-input");
const preview = document.getElementById("math-preview");
function updatePreview() {
katex.render(input.value, preview, {
displayMode: true,
throwOnError: false,
trust: false,
maxSize: 20,
maxExpand: 1000
});
}
input.addEventListener("input", updatePreview);
updatePreview();
</script>3. Render equations in npm projects.
Install KaTeX via npm for a bundled front end or server-side rendering.
npm install katex
With a bundler that handles CSS imports, import KaTeX and its stylesheet. Render into an existing element, such as the inline-math span from Basic Usage.
import katex from "katex";
import "katex/dist/katex.min.css";
katex.render("y = x^2", document.getElementById("inline-math"));For automatic rendering in an npm project, import
renderMathInElementfromkatex/contrib/auto-render.
In Node.js, use katex.renderToString() to generate equation markup for your HTML template. Serve the matching KaTeX stylesheet and fonts. For static, pre-rendered equations, omit the core browser script.
const katex = require("katex");
const html = katex.renderToString(
String.raw`\frac{d}{dx}x^3 = 3x^2`,
{ displayMode: true }
);
console.log(html);4. Define reusable LaTeX macros.
Define \RR as shorthand for \mathbb{R} using the macros option:
katex.render(
String.raw`x \in \RR`,
document.getElementById("inline-math"),
{ macros: { "\\RR": "\\mathbb{R}" } }
);JavaScript API
| API | Description |
|---|---|
katex.render(tex, element, options?) | Replaces the contents of element with the typeset math. Returns undefined. |
katex.renderToString(tex, options?) | Returns the typeset math as a markup string in Node.js or the browser. |
renderMathInElement(element, options?) | Scans text nodes within the supplied DOM element and replaces delimited math in place. Returns undefined. Requires the auto-render extension. |
katex.version | The library version as a string. |
new katex.ParseError(message, token?) | Error class for invalid or unsupported TeX. Accepts a message and an optional token with location information. Fields: message, rawMessage, name (ParseError), and position and length when the input location is known. |
Configuration Options
| Option | Description |
|---|---|
displayMode | Boolean; default false. Set to true for centered block math in display style, with larger operators and no automatic line breaks. Inline math starts in text style and permits breaks after outermost relations and binary operators. Use \displaystyle or \textstyle to switch styles within an expression. |
output | String; default htmlAndMathml (HTML and MathML). Other values: html for HTML only; mathml for MathML only. |
leqno | Boolean; default false. Places equation numbers created with \tag on the left when enabled. |
fleqn | Boolean; default false. Left-aligns display equations with a 2em inset when enabled. |
throwOnError | Boolean; default true. Throws a ParseError for unsupported commands or invalid TeX. Set to false to show unsupported commands as text or invalid expressions as their source, in the error color. Invalid expressions also show an error tooltip. |
errorColor | String; default #cc0000. Hex color in #RGB or #RRGGBB format for error output with throwOnError: false. |
macros | Object; default {}. Maps a TeX command or active character to its expansion. String expansions accept arguments such as #1 and #2. Function and object expansions use internal macro structures. |
globalGroup | Boolean; default false. Preserves definitions such as \def, \newcommand and \let at the top level in the supplied macros object when enabled. |
minRuleThickness | Number; default 0 (no additional minimum). Sets the minimum rule thickness in ems for fractions, radicals, array rules, overlines, underlines, and boxes. Try 0.06 for thicker lines. Negative values are clamped to zero. |
colorIsTextColor | Boolean; default false. Changes \color from a declaration to the two-argument behavior of \textcolor. |
maxSize | Number; default Infinity. Caps user-defined dimensions, such as the height of a rule, in ems. |
maxExpand | Number; default 1000. Restricts macro expansion count to prevent infinite loops; Infinity removes the limit. \edef counts all expanded tokens. |
strict | Boolean, string, or function; default "warn". Controls LaTeX compatibility. Use false or "ignore" to permit incompatible input, "warn" to log warnings, true or "error" to enforce LaTeX compatibility, or a callback. |
trust | Boolean or function; default false. Controls commands for links, external images, and HTML attributes. false displays blocked commands in the error color; true allows them all. Use a callback for command-specific permissions. |
Strict Mode and Trust Callbacks
The strict(errorCode, errorMsg, token) callback returns true, false, "error", "warn", or "ignore" for specific LaTeX compatibility issues. The token argument is optional. The strict error setting throws a ParseError for the following issues, except newLineInDisplayMode.
unknownSymbol: Unknown Unicode character.unicodeTextInMathMode: Unicode text character used in math mode.mathVsTextUnits: Math/text unit mismatch.commentAtEnd: A final comment lacks a newline.htmlExtension: KaTeX-specific HTML commands.mathVsSout:\soutin math mode.mathVsTextAccents: Text accents used in math mode.textEnv: Array row contains too many cells.symbolNotInFont: Missing glyph metrics for the selected style and mode.newLineInDisplayMode:\\or\newlineoutside an array in display math.trueor"error"suppresses the break without throwing an error.
Return a boolean from trust(context) to allow or block a command. The context includes command and these fields:
| Commands | Description |
|---|---|
\url, \href, \includegraphics | url, protocol (lowercase, or _relative for relative URLs). |
\htmlClass | class |
\htmlId | id |
\htmlStyle | style |
\htmlData | attributes (object of string values). |
Allow HTTPS links with the following trust callback.
katex.render(
String.raw`\href{https://katex.org/}{KaTeX}`,
document.getElementById("inline-math"),
{
trust: ({ command, protocol }) =>
["\\url", "\\href"].includes(command) && protocol === "https"
}
);Auto-render Options
In addition to the core options, renderMathInElement() accepts the following settings. Each delimiter controls its own display mode, overriding the core displayMode setting.
| Option | Description |
|---|---|
delimiters | Array of objects with left and right delimiter strings and a display boolean. Entries are evaluated in array order. See the defaults below. |
ignoredTags | Array of lowercase tag names to skip. Default: script, noscript, style, textarea, pre, code, option. |
ignoredClasses | Array of class names to skip; default []. |
errorCallback | Function (message, error) => void called when rendering throws a ParseError; default console.error. The original delimited text remains. Input errors rendered with throwOnError: false do not invoke it. |
preProcess | Function (math) => string for transforming the expression before rendering. Optional. |
Default delimiters, in matching order:
[
{ left: "$$", right: "$$", display: true },
{ left: "\\(", right: "\\)", display: false },
{ left: "\\begin{equation}", right: "\\end{equation}", display: true },
{ left: "\\begin{align}", right: "\\end{align}", display: true },
{ left: "\\begin{alignat}", right: "\\end{alignat}", display: true },
{ left: "\\begin{gather}", right: "\\end{gather}", display: true },
{ left: "\\begin{CD}", right: "\\end{CD}", display: true },
{ left: "\\[", right: "\\]", display: true }
]Styling Math Equations
KaTeX formulas use a font size of 1.21em by default. Change it through .katex and enable horizontal scrolling for long display equations on narrow screens.
.katex {
font-size: 1.1em;
}
.katex-display {
overflow: auto hidden;
}To allow automatic line breaks in display equations, use these CSS overrides:
.katex-display > .katex {
white-space: normal;
}
.katex-display > .katex > .katex-html > .katex-base {
margin: 0.25em 0;
}
.katex-display {
margin: 0.5em 0;
}For a custom stylesheet build, override these Sass variables through src/styles/katex.scss. When building KaTeX from source, the USE_WOFF2, USE_WOFF, and USE_TTF environment variables accept "true" or "false" to include or exclude font formats.
| Sass variable | Description |
|---|---|
$font-folder | Font file directory; source default "../../fonts". |
$use-woff2 | Boolean; source default true. Includes WOFF2 font sources. |
$use-woff | Boolean; source default true. Includes WOFF font sources. |
$use-ttf | Boolean; source default true. Includes TrueType font sources. |
$font-display | Font loading behavior; source default block. |
$display-margin | Display equation margin; default 1em 0. |
KaTeX Extensions
Load the extension you need after the core script. If you use mhchem with auto-render, load mhchem first. Defer the math/tex extension until the page has been parsed.
contrib/mhchem.min.js: Adds\cefor chemical formulas and reactions and\pufor physical units.contrib/copy-tex.min.js: Copies selected formulas as LaTeX source through the Clipboard API, with$...$for inline math and$$...$$for display math. A partial formula selection copies the whole formula. To change delimiters in a custom build, editcopyDelimitersin the extension source.contrib/mathtex-script-type.min.js: Renders legacy MathJax markup in<script type="math/tex">elements. Usetype="math/tex; mode=display"for display math.
<script src="https://cdn.jsdelivr.net/npm/katex/dist/contrib/mhchem.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/katex/dist/contrib/copy-tex.min.js"></script> <script defer src="https://cdn.jsdelivr.net/npm/katex/dist/contrib/mathtex-script-type.min.js"></script>
For speech applications, import renderA11yString from katex/contrib/render-a11y-string. The renderA11yString(tex, options?) function converts supported math expressions into readable text.
Alternatives
- Render Math Equations with Pure HTML & CSS – PureTex.css
- Simplify MathML Authoring with Lightweight Syntax – Mathup
- MathJax | Beautiful math in all browsers.
FAQs
Q: Can I render KaTeX math after loading content through AJAX?
A: Call renderMathInElement(newContent) after inserting the new HTML into the DOM. Pass the same rendering options you used for the initial content. To update one equation, call katex.render() with the new formula and its existing element.
Q: Why do my equations show broken or overlapping symbols?
A: Check that the stylesheet and JavaScript versions match and that the font files load successfully. When self-hosting, keep the fonts/ directory next to the bundled stylesheet.
Q: Can I reuse macros across multiple equations?
A: Pass the same macros object to each render call. KaTeX updates that object with definitions created by \gdef or \global\let. Auto-render shares macros across equations within each call. Use a fresh object for each untrusted message to isolate its macro definitions.
Q: Does KaTeX support all LaTeX commands?
A: KaTeX implements a subset of LaTeX math commands and packages. Check the TeX command compatibility table for the commands your content uses.
Q: How do I display a custom error message for invalid LaTeX?
A: Use throwOnError: true and catch katex.ParseError. Display its message through textContent. Escape the message if you insert it as HTML because it can contain user input.







