What are the actual problems of not closing tags and attributes in HTML

后端 未结 6 1192
走了就别回头了
走了就别回头了 2021-01-11 15:44

Recently a friend decided not to close his tags or attributes in HTML because it\'s not required and he\'ll save some bandwidth and download time. I told him it\'s a bad ide

6条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-11 16:20

    You can often leave the closing tags off many elements without changing 'the way it looks'. However, even though one of the main goals of HTML5 is to standardize how browsers deal with bad markup, not closing tags can impact your content in unexpected ways. Here's a simple example, a list of items where some of the items are blank, both without explicitly closed tags and with:

    • Item
    • Item
    • Item
    • Item
    • Item
    • Item

    Looking at the two in a browser they look identical. However, if you add a bit of CSS to hide the empty ones:

    li:empty { display: none; }
    

    Now they don't look the same, even though the markup hasn't changed from the previous example. The underlying reason for this is that the two versions produce different DOM trees, this version iterates through all the nodes in both lists and counts them, then shows the results and the list of nodes found in alerts. You can see the top list has 12 DOM nodes, the lower list has 15. The results are at least consistent cross browser, and the difference is in text nodes which you'll frequently skip over when scripting anyway, but this shows that even if the visual output looks the same when tags are closed or not, there are underlying differences even in an example as simple as this.

提交回复
热议问题