Use MathML today, with CSS fallback!

These days, I’m working on the slides for my next talk, “The humble border-radius”. It will be about how much work is put into CSS features that superficially look as simple as border-radius, as well as what advances are in store for it in CSS Backgrounds & Borders 4 (of which I’m an editor). It will be fantastic and you should come, but this post is not about my talk.

As you may know, my slides are made with HTML, CSS & JavaScript. At some point, I wanted to insert an equation to show how border-top-left-radius (as an example) shrinks proportionally when the sum of radii on the top side exceeds the width of the element. I don’t like LaTeX because it produces bitmap images that don’t scale and is inaccessible. The obvious open standard to use was MathML, and it can even be directly embedded in HTML5 without all the XML cruft, just like SVG. I had never written MathML before, but after a bit of reading and poking around existing samples, I managed to write the following MathML code:

<math display="block">
    <mrow>
        <msub>
            <mi>r&prime;</mi>
            <mi>top-left</mi>
        </msub>
        <mo>=</mo>
        <mi>min</mi>
        <mo>(</mo>
        <msub>
            <mi>r</mi>
            <mrow>
                <mi>top-left</mi>
            </mrow>
        </msub>
        <mo>,</mo>
        <mi>width</mi>
        <mo>&times;</mo>
        <mfrac>
            <mrow>
                <msub>
                    <mi>r</mi>
                    <mi>top-left</mi>
                </msub>
            </mrow>
            <mrow>
                <msub>
                    <mi>r</mi>
                    <mi>top-left</mi>
                </msub>
                <mo>+</mo>
                <msub>
                    <mi>r</mi>
                    <mi>top-right</mi>
                </msub>
            </mrow>
        </mfrac>
        <mo>)</mo>
    </mrow>
</math>

I was very proud of myself. My first MathML equation! It’s actually pretty simple when you get the hang of it: <mi> is for identifiers, <mo> for operators and those are used everywhere. For more complex stuff, there’s <mfrac> for fractions (along with <mrow> to denote the rows), <msqrt> for square roots and so on.

It looked very nice on Firefox, especially after I applied Cambria Math to it instead of the default Times-ish font:

MathML native support in Firefox

However, I soon realized that as awesome as MathML might be, not not all browsers had seen the light. IE10 and Chrome are the most notable offenders. It looked like an unreadable mess in Chrome:

MathML in Chrome, with no CSS fallback

There are libraries to make it work cross-browser, the most popular of which is MathJax. However, this was pretty big for my needs, I just wanted one simple equation in one goddamn slide. It would be like using a chainsaw to cut a slice of bread!

The solution I decided to go with was to use Modernizr to detect MathML support, since apparently it’s not simple at all. Then, I used the .no-mathml class in conjunction with selectors that target the MathML elements, to mimic proper styling with simple CSS. It’s not a complete CSS library by any means, I just covered what I needed for that particular equation and tried to write it in a generic way, so that if I need it in future equations, I only have to add rules. Here’s a screenshot of the result in Chrome:

MathML in Chrome with CSS fallback

It doesn’t look as good as Firefox, but it’s decent. You can see the CSS rules I used in the following Dabblet:

Obviously it’s not a complete MathML-to-CSS library, if one is even possible, but it works well for my use case. If I have to use more MathML features, I’d write more CSS rules. The intention of this post is not to provide a CSS framework to use as a MathML fallback, but to show you a solution you could adapt to your needs. Hope it helps!

  • http://peter.krautzberger.info/ Peter Krautzberger

    Arguably, I’m biased (being part of MathJax), but CSS only goes so far — Opera/presto had been doing it for years and it was miserable. There are a few fundamental barriers to it in fact.

    You might want to look into other shims like jqmath (not to be confused with jsmath) that do not strive for such a high typesetting quality as MathJax does.

    • http://lea.verou.me/ Lea Verou

      Still, a universal library, any of them, is too heavy for simple use cases like mine. For documents with more equations, or more complex ones, sure.

      • Frédéric Wang

        Peter is referring to the style sheet defined in

        http://www.w3.org/TR/mathml-for-css/

        which is used by Opera (Presto) and may have better MathML support than your library (but still limited). For your simple use, you might want to have a look at David Carlisle’s html5mathml library that does the work of choosing Native MathML or attaching the CSS style sheet according to the browser support:

        http://dpcarlisle.blogspot.fr/2011/09/html5mathml.html

        • http://lea.verou.me/ Lea Verou

          Yup, I know. My point was that for a simple equation here and there, you don’t need a huge stylesheet or a heavy library. Of course all these are immensely useful in more math-heavy documents or apps.

        • http://twitter.com/StuCoxMedia Stu Cox

          Think there could be a case for an open source CSS library here, with a modular builder? (i.e. select which features you need to use, and it’ll churn out some styles just for those) Or are these simple MathML cases not really common enough to warrant it?

        • http://lea.verou.me/ Lea Verou

          That’s a great idea Stu!

      • http://peter.krautzberger.info/ Peter Krautzberger

        I agree. I admit I had just too many conversations where people think CSS is the solution — it’s so much more complicated than that :(

        Detecting MathML capabilities is virtually impossible right now since support is just too spotty. modernizr checks for one very basic construct — that’s a bit like detecting if a font size increase to decide that tables are supported.

        Sorry for sounding so negative — yay! for using MathML and not resorting to images!

  • http://twitter.com/PaulTopping PaulTopping

    Nice post. A long time ago I was on the W3C Math Working Group that created MathML. It was always our hope that CSS would be so powerful that a stylesheet could transform it into HTML+CSS and that’s all we’d ever need. David Carlisle did write such a stylesheet and he’s to be congratulated for his efforts, but the limitations of the approach were known right from the start. That said, it has been Opera’s answer to MathML support for a long time.
    It should be noted that MathML was not intended to be coded by hand. There are many products that can generate MathML for you with a nicer interface, including my company’s MathType application. Of course, it is nice to know how it all works.

  • http://twitter.com/diogovincenzi Diogo Vincenzi

    Interesting post. Though, you lucked out a bit on the fact that your equation is readable with CSS due to the way it was built. But in any other case, it would be very easy to apply them the wrong way, due to the parenthesis not being wrapped around both lines of the fraction. If you had something like x = (a + b / c), with you css it might end up reading x = (a + b) / c, which is a completely different equation. If you could find a way to get the parenthesis bigger, it would improve readability a lot :)

  • http://twitter.com/fabbiatti Facundo Abbiatti

    I love it!

  • http://beben-koben.blogspot.com/ Beben Koben

    fantastic breakthroughs, we look forward
    thumbs

    • http://beben-koben.blogspot.com/ Beben Koben

      ASCIIMathML, Latex, Regex!!!
      qiqiqqi

      • Jeff Barnes

        Ladies and gentleman, web development pop culture.

  • ArtjomKurapov

    Being a web developer and a content-producer I must say – no, MathML (and if we go that far – XML) is a horrible thing to aspire to. I’m all for LaTex, since thats a defacto standart for scientific publications anyway. So having MathJax supporting syntax that is that short is a great thing to have. I wish browsers would support LaTex instead.

    I realize that having full structural overview can be a good thing, but its the same with regular expressions – sometimes its easier to have very short string that does complex transformations, than a dosen of commands for cycling/searching. So in a way its more a question of length vs understandability.

    • Jeff

      The W3C have this myopic view that everything can and should be represented as XML. It failed before and it’ll fail again.

  • pixelass

    for this particular example you could add…

    .no-mathml math > mrow:first-child > mo:nth-child(10),
    .no-mathml math > mrow:first-child > mo:nth-child(4) {
    vertical-align: bottom;
    font-size: 300%;
    }

    …to make the surrounding brackets larger. Of course this is hardcoded, but it sure makes this example look a lot better.

    http://dabblet.com/gist/5248521

  • Jeff Barnes

    The whole point of LaTeX is to render at a specific, known size (bitmap images). To not like LaTeX because it does only what it was intended to do is akin to not liking a car because it can’t fly.

    • http://lea.verou.me/ Lea Verou

      I don’t see anything about specific, known sizes being a *goal* of LaTeX here: http://www.latex-project.org/ do you?

      • Jeff

        Argumentum ad ignorantiam. Cool story, bro.

      • Jeff

        By the way, I was replying specifically to this:

        “I don’t like LaTeX because it produces bitmap images that don’t scale and is inaccessible”

        What has that got to do with LaTeX *math*? The subject of this post is MathML, so criticizing LaTeX when you’re evaluating (the completely orthogonal) LaTeX *math*, seems to be missing the point and a pretty lazy analysis.

        MathML is simply a horribly bastardised, bloated and unreadable version of LaTeX math, which merely serves as a “pointless complexity” check-box for the W3C. Congratulations.

        • cben

          In the context of writing an HTML presentation, Lea’s “I don’t like LaTeX” should obviously be taken as “I don’t like the LaTeX→PNG road to displaying math in a browser”.

  • http://goldingdamien.blogspot.jp/ Damien Golding

    I actually don’t get what MathML is for. Can somebody explain?
    You can perfectly set style to show a Math expression in CSS and if CSS is not good enough to style equations yet then just improve CSS.
    Dynamic changing of CSS based on equations can easily be done in JavaScript. What is the point of this messy xml code? Can somebody please explain to me?

  • http://www.nx8.name/ nx8

    Use MathM, with CSS fallback, I will do this by. Very good.

  • http://yepi3.yepi250.com/ yepi3

    Nice information, many thanks to the author. It is incomprehensible to me now, but in general, the usefulness and significance is overwhelming.