📜 ⬆️ ⬇️

HTML is not XML

Many people think that html is a subset of xml. And, accordingly, they write code in the same style. But this is not the case; there are differences between these layouts. There are some xml rules that are not applicable in html.

I will review the three main mistakes of those who try to write html in xml style.

1. Self-closing tags


The first and most common mistake. Many times I saw someone trying to close an html tag with
using /> For example, <button /> or <br /> .
But even if the element has no content, it is still impossible to write that way. Because unlike xml
in html closing tags using /> is prohibited. The tag can only be closed explicitly with </ tag> . This is not just a good style. The browser perceives the "/" symbol inside the element as an error and ignores it. The element simply does not close.

Let's see how the browser handles such tags. Perform the following html:
')
<div style="background-color: red; width: 300px;">  <div style="background-color: green;"/>   </div> <div> </div> 

Everything seems to be normal, but it will look like this:



As you can see, the browser did not close the element, ending with />. It had to be closed with an explicit </ div>.

And by the way, even serious companies sometimes write incorrectly.

Example
Yandex.Metrika writes his img tag like this: <img src = "// mc.yandex.ru/watch/24049213" style = "position: absolute; left: -9999px; "alt =" " />

2. Closing tags


Ok, tags need to be explicitly closed. So you should always write <tag> </ tag> ? Not. Not so simple. According to the specification in html, some tags must be closed, some are optional, and some are prohibited.

I will give examples:

Of course, these examples are not complete. For each individual tag, see the documentation.

3. Record Boolean Attributes


How to write boolean attributes in html (such as checked and disabled)? Those who write html in xml style happen to write them like this: <option selected = "true"> </ option>
So do not need to. There is no “true” value in html. The standard says that if an attribute is declared in markup, then its value is already true.

You can choose one of three recording options:

I prefer to use a short third option, like: <input id = "smth" disabled type = "text"> .

PS These rules apply to html, not xhtml. However, even if your page is framed as xhtml, the browser will
parse it as html if the server renders it with the mime-type 'text / html' . In order for a page to become a valid xhtml, its mime-type must be 'application / xhtml + xml' . Only then the browser will parse this page according to the xml rules.

Source: https://habr.com/ru/post/252283/


All Articles