Как написать формулу в html
Перейти к содержимому

Как написать формулу в html

  • автор:

Getting started with MathML

In this article, we will take a simple HTML document and see how to add MathML formulas into it, introducing a few elements along the way.

Prerequisites: Basic computer literacy, basic software installed, basic knowledge of working with files, and HTML basics (study Introduction to HTML.)
Objective: To understand the basic syntax of MathML and how to integrate it in HTML pages.

Inserting formulas in HTML via the <math> element

MathML uses the same syntax as HTML to represent a tree of elements and attributes. In particular, each mathematical formula is represented by an element <math> which can be placed inside an HTML page. In the following document, it is inside a paragraph of text:

The <mfrac> element specifies a fraction with a numerator (its first child) and a denominator (its second child). This is how it renders in your browser:

Warning: If you just see «1 3» instead of a fraction, then your browser may not support MathML. Check out the browser compatibility table for further details.

The display attribute

Note that in the previous example, the formula is on the same line as the text of the paragraph. However, it is quite common to instead render large mathematical formulas centered on their own line as shown below. To achieve that, you need to attach a display=»block» attribute on the <math> element.

You may also notice some subtle change in the appearance: the text and vertical spacing of the fraction becomes a bit bigger. Without the display=»block» attribute, the height is minimized to avoid disturbing the flow of the surrounding text. With the display=»block» attribute, priority is instead put on legibility of the mathematical formula.

Note: This corresponds to the LaTeX’s concept of inline formulas (delimited by dollar signs $. $ ) and display formulas (delimited by \[. \] ).

Note: The appearance change mentioned above is actually controlled by the math-style property which is initially normal for <math display=»block»> and compact otherwise. In some MathML subtrees, this property can then automatically become compact but we will ignore this subtlety for this introductory tutorial. Again, this is similar to LaTeX.

Grouping with the <mrow> element

The <math> element can actually contain an arbitrary number of children and will essentially render them in a row. For instance, the simple formula «1 + 2 + 3» would be encoded like this in MathML:

The <mrow> element is a generic container that performs similar layout but can be placed anywhere in the MathML subtree. It is helpful to group several elements together. For instance, the numerator of the following fraction (its first child) is «one plus two».

Active learning: nested expressions

As an exercise, figure out how to write the following expressions using only the MathML elements we’ve seen so far. If you are stuck or want to verify the solution, check the source code of the example.

Summary

In this article, we have taken a look at how to use the <math> element to insert a mathematical formula inside a HTML document. We have learned about rendering differences between <math> elements that use display=»block» or not. In addition, we stumbled upon a couple of other MathML elements: <mfrac> for fractions, <mrow> for grouping and finally a few text elements. We will analyze these text containers further in the next article.

Writing mathematical formulas in HTML

Hello, today we are going to learn how to write mathematical formulas in HTML, for example, to insert them on a website.

How to use letters in a calculation ?

The first and most important thing to learn when doing calculations with letters is to write them in such a way that they can be distinguished from the text. Thanks to HTML you can directly write letters as variables with the <var> tag. We notice that the letters are slightly italicized and slightly bolded.

The exhibitors

For exhibitors, HTML allows you to directly exhibitors an element without necessarily using a cascading style sheet. To do this, we will use the variable <sup> .
To repeat the previous example :

The roots

After having seen the exponents, we will learn the roots, which are not necessarily easy to write. To achieve it, you must necessarily go through the CSS.
You can for example copy the code below :

The problem with this code is that the horizontal bar of the square root is realized with the border property. So in some cases, if the display window is too small, the formula may be distorted. This is why many sites prefer images to handle square roots.

The fractions

First we will look at fractions, which can be problematic to create in HTML. There is no ready-made tag to create fractions, so we have to use CSS. The code is available below :

The vectors

Vectors are particularly useful in physical sciences, you will see later that the code is not very complicated.
For this example, I took the fraction seen before and I applied arrows on the letters.
The vectors for capital letters are designated by the class: oncapital and the vectors for small letters by the class: onsmall .

The sum

To make a sum in HTML and CSS :

The integrals

To make an integral in HTML and CSS :

I hope you enjoyed this tuto, feel free to suggest other tips in comments.

MathMl в HTML5

До выхода HTML5 использование формул было сущим наказанием. Судите сами: в 2005-м необходимо было иметь под рукой либо специальный браузер, либо разбивать текст на собственно HTML и вставки из изображений или PDF. Поиск и прочие операции редактирования и/или вывода на экран/бумагу был неоднозначной задачей, коей посвящались целые монографии.

В 2012-м было уже попроще. Появилась возможность подключать необходимые плагины (Firemath для FireFox и Daum Equation Editor для Chrome). Но неоднозначность стандартов (и поддержки) фактически заставляла писать одну и ту же статью для каждого из браузеров (и для их версий). Или встречать пользователей волшебным приветствием «Ваш браузер надо обновить/дополнить расширением».

Неудобно? — Да! Отнимало много времени на поиск универсального решения? — Да! Заставляет думать о том, какой тип записи лучше (презентационный или содержательный), каким конвертером пользоваться (а их только общеизвестных с десятка полтора)? — ДА! ДА! ДА!

В результате работа по публикации превращалась в освоение двух-трех лексиконов разметки и изучения работы минимум одной программы-перекодировщика.

Теперь, с приходом HTML5, все стало намного проще. В нем появился новый контейнер <math> .
Каждый допустимый экземпляр MathML должен быть внутри этого контейнера.
Он не допускает вложений, но внутри может быть произвольное число других дочерних элементов.

Атрибуты тэга

В дополнение к следующим атрибутам, тэг <math> воспринимает любые атрибуты из <mstyle> .

  • block — означает, что этот элемент будет отображаться за пределами текущего диапазона текста, как блока, который может быть расположен в любом месте без изменения смысла текста;
  • inline -означает, что этот элемент будет отображаться внутри текущего диапазона текста, и не могут быть перемещены из нее без изменения значения этого текста.

Значение по умолчанию inline .

mode <span title=«Этот устаревший API больше не используется, но, вероятно, все еще работает.»

Устаревшие значение display attribute.
Возможные значения: display (который имеет тот же эффект, как display="block" ) и inline .
overflow
Определяет, как выражение ведет себя, если текст слишком длинный и не помещается в указанном диапазоне ширины.
Возможные значения: linebreak (по умолчанию), scroll , elide , truncate , scale .

Теорема Пифагора

Представление в HTML5
Представление в XHTML

Примечания: XHTML документы с MathML должны быть поданы как application/xhtml+xml . Вы можете легко добиться этого, добавив .xhtml расширение для локальных файлов. Для серверов Apache вы можете настроить .htaccess файл для этого расширения на правильный тип MIME. Поскольку мы сохранили наш MathML в виде XML-документа, необходимо быть уверенным в правильно оформленном XML-документе.

Поддержка браузерами

Полноценные версии

Элемент Chrome Firefox (Gecko) Internet Explorer Opera Safari
XHTML описание (только 24-я) 1.0 (1.7 и выше) 9.5 5.1
HTML5 описание (только 24-я) 4.0 (2.0) 5.1
dir 12.0 (12.0)
href WebKit bug 85733 7.0 (7.0) WebKit bug 85733
mathbackground (только 24-я) 4.0 (2.0) 5.1
mathcolor (только 24-я) 4.0 (2.0) 5.1
overflow

Мобильные версии

Элемент Android Chrome для Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
XHTML описание 1.0 (1.0)
HTML5 описание 4.0 (2.0)
dir 12.0 (12.0)
href 7.0 (7.0)
mathbackground 4.0 (2.0)
mathcolor 4.0 (2.0)
overflow

В Gecko 7.0 (Firefox 7.0 / Thunderbird 7.0 / SeaMonkey 2.4) появилась поддержка всех MathML атрибутов для элементов верхнего уровня (т.е. такое же поведение как <mstyle> элемента). Тем не менее, displaystyle атрибут не отрабатывается. Его поддержка была добавлена в Gecko 8.0 (Firefox 8.0 / Thunderbird 8.0 / SeaMonkey 2.5).

Альтернативные текстовые описания ( alttext ) или ссылки на альтернативное изображение, (атрибуты altimg , altimg-width , altimg-height и altimg-valign ) в настоящее время не реализованы в Gecko.

3 Ways To Write Math Equations In HTML

Welcome to a tutorial on how to write Math equations in HTML. The Internet has come a long way from the Stone Age, and HTML is now fully capable of handling various types of content, different languages, images, audio, and videos. But there is seemingly one mystery left unanswered… How do we write Math equations?

There are a few ways to write Math equations in HTML:

  1. Use HTML Math symbols and tags to build simple equations.
    • Refer to this list for the available Math symbols.
    • For example, &#8731; 27 = 3 will display as ∛ 27 = 3.
  2. For the complicated equations, use a library to help – Check out MathJax.
  3. Lastly, use online generators to create images of equations – Check out Mathcha.

That covers the basics, but let’s walk through more examples in this guide – Read on!

ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

QUICK SLIDES

TABLE OF CONTENTS

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

QUICK NOTES

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

HTML MATH EQUATIONS

All right, let us now get into the various ways and examples of writing Math equations in HTML.

METHOD 1) HTML SYMBOLS & TAGS

1A) BASIC HTML MATH SYMBOLS

  • In short, there are a ton of HTML symbols available, and we can define them using &CODE; . For example, &#8800; above “translates” to the “not equals” symbol.
  • HTML symbols are not restricted to only Math. There are also many other icons, smileys, arrows, etc…
  • I will leave a link to a complete list of Math symbols in the extras section below.
  • <sup> is but a simple superscript tag.
  • Not in the above example, but the other useful one is the <sub> subscript tag.
1B) MORE MATH WITH CSS

  • We have created “3 layers” .math containers here.
  • For the first <div > –
    • Both the top and bottom .smol layers are used to specify the upper and lower limits respectively.
    • The middle layer &#8721; is the summation (sigma) symbol.
    • Both the top and bottom .smol layers are empty with a white space &nbsp; .
    • The middle layer is the formula c = cn .

    Yep… This is kind of a painful way to do it, but it works.

    METHOD 2) MATH LIBRARY

    2A) MATH EQUATIONS WITH TEX

    Following up on the above, there are thankfully libraries that we can use. This is a popular one called MathJax, and it supports multiple “Math Code Languages” – Tex, LaTeX, MathML, and AsciiMath. While this library is not the friendliest for beginners, this is still way better than manually creating formulas using raw HTML and CSS.

    P.S. I will leave links for the library tutorials in the extra section below.

    2B) MATH EQUATIONS WITH MATHML

    This is another example of the Mathjax library, but using the MathML “language”. I personally prefer this over the “less human” Tex and LaTeX – As you can see, this is a lot more similar to HTML and easier to understand.

    METHOD 3) IMAGE EQUATIONS

    3A) ONLINE EQUATION EDITORS
      – Code Cogs – Online Math Editor

    Just do a search for “latex online editor”, “Math equation online”, or “latex to image”, and there will be plenty.

    3B) LATEX TO IMAGE

    What’s next is to simply use one of these tools to create the equation, and download it as an image accordingly – Finally, insert this image into your HTML file. Captain Obvious to the rescue.

    USEFUL BITS & LINKS

    That’s all for this guide, and here is a small section on some extras and links that may be useful to you.

    LINKS & REFERENCES

      – ginifab.com
    • MathJax – Official Website | Documentation | Examples – Tutorialspoint

    INFOGRAPHIC CHEAT SHEET

    How to Write Math Equations In HTML (click to enlarge)

    THE END

    Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

    5 thoughts on “3 Ways To Write Math Equations In HTML”

    You Will Been Hack!

    1) If it is “going to”, the proper English sentence is “you will be hacked”.
    2) If it “already happened”, it should be “you have been hacked”.

    Since nothing happened, I take it that it is the former. I recommend you start with basic digital literacy first. Then follow up with networking, security, cryptography, Math, coding, cyber ethics, cyber ethnography, social engineering, read the book “hacking for dummies”, and research a bit more about “CEH”.

    Since you are going to do it, don’t waste your time with a potato blogger. Please write a former request to both AWS and Cloudflare – Pretty sure they will pay very handsomely for people who can break their systems. You will also be famous if you can break one of the world’s most reliable cloud hosting.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *