How To Write Fractions Using Only HTML & CSS


Usually when I write fractions I use LaTeX’s command: \frac{x^2 + 3x + 5}{2x} which is easy, neat and when rendered does an awesome job:

[latex]\frac{x^2 + 3x + 5}{2x}[/latex]

Currently, though I’m designing a simple website for my math students where I’d prefer not use a math renderer (if possible). The reason being that most of the content which is published does not require extensive math notation and therefore the majority of things that I need to show doesn’t need the heavy lifting of a LaTeX engine.

However, one mathematical notation that is needed in this simple activity did require the use of writing some fractions, so I thought to myself, Instead of using LaTeX why not design it using simple HTML & CSS (and maybe with the help of jQuery)? Surely it couldn’t be that hard? I mean, in the HTML world we have the following workaround:

Unfortunately it looks ugly. So I started my quest to find a much more elegant solution with the help from the folks at Stack Overflow.

When creating a fraction there were two main things I wanted to keep in mind, with a third as an optional preference:

  1. I want the line of the fraction to be horizontal and to spans the length of the longest expression in either the numerator, or the denominator;
  2. I want the fraction to appear inline with the question being asked of it, I don’t want it to protrude too far outside the line height; and
  3. I want the pronumerals (letters) to be italicised

Those are my fraction format terms and conditions. The last one I could forgo as the other two are the main essence of writing a fraction. Knowing this I then set about using divs and this is what I created initially:

Which produces:

Math fraction using HTML & CSS

Then after receiving a few responses from SO I received this better response which required less HTML & CSS:

Conclusion

Thankfully, there are solutions available for us in being able to write complex (yet not too complex) fractions in HTML & CSS. I’m guessing if I want to italicise the letters I’d be looking at something like jQuery.

For the time being I’m happy with what I have, and it’s a better alternative than ⁄.

jsFiddle

Ryan

Author of scripteverything.com, Ryan has been dabbling in code since the late '90s when he cut his teeth by exploring VBA in Excel when trying to do something more. Having his eyes opened with the potential of automating repetitive tasks, he expanded to Python and then moved over to scripting languages such as HTML, CSS, Javascript and PHP. When he is not behind a screen, Ryan enjoys a good bush walk with the family during the cooler months, and going with them to the beach during the warmer months.

Recent Posts