Using Horizontal Overflow for katex in mdx-bundler
November 5, 2024A Guide for resolving KaTeX math block overflow on mobile by wrapping .katex-display elements with a custom div using a custom rehype plugin in mdx-bundler.
Recently, I encountered an issue while using katex with mdx-bundler:
The math block may overflow on mobile devices. There isn't a direct way to add overflow-x: auto to the katex block.
After some researches, I found the solution and would like to take a note here.
Below is my method for implementing math rendering in MDX on my website. If your setup differs from mine, you might need to adjust the code accordingly.
- Install
mdx-bundlerandreact-katex. - Add
remark-mathandrehype-katexas plugins formdx-bundler.
To solve the overflow problem, I wrapped the .katex-display element in a custom div with the style overflow-x: auto;.
My Original Code
The rehype-katex plugin is used to transform math formulas into HTML code. I created a custom rehype plugin that works after rehype-katex and wraps all .katex-display elements with a custom div.
Solution
You can copy the plugin's code below. First, you need to install these libraries for plugin development:
Next, copy and paste this function into your source code. You can place it anywhere; for example, here I put it directly in global.ts.
Next, incorporate it as a mdx-bundler plugin. If rehypeWrapMathBlock is not in the same file as getMdxContent function, you should import it first. The following code snippet is modified based on code from the previous section (click here to jump):
This will now wrap the original .katex-display DOM element with a <div style="overflow-x: auto;"></div>.