阿里云主机折上折
  • 微信号
Current Site:Index > The tag closing rules of HTML5

The tag closing rules of HTML5

Author:Chuan Chen 阅读数:50240人阅读 分类: HTML

The tag closing rules in HTML5 have undergone significant changes compared to previous HTML versions, with substantial optimizations in the flexibility of tag closing. These rules directly impact code readability and browser parsing behavior.

Basic Rules for HTML5 Tag Closing

HTML5 adopts a more lenient approach to tag closing, allowing the omission of closing tags in many cases. This design is primarily based on common patterns in real-world development, aiming to reduce redundant code. Here are several typical scenarios:

  1. Void Element Tags: Elements like <img>, <br>, and <input>, which do not contain content, can be used without closing tags in HTML5.
<!-- Valid syntax -->
<img src="logo.png" alt="Logo">
<br>
<input type="text">
  1. Elements with Optional Closing Tags: Some content-containing elements can also omit closing tags under certain conditions.
<p>This is a paragraph
<p>This is another paragraph
<li>List item one
<li>List item two

Types of Tags That Must Be Closed

Despite HTML5's flexibility, certain elements still require explicit closing:

  1. Tags Containing Scripts or Styles:
<script src="app.js"></script>
<style>
  body { margin: 0; }
</style>
  1. Table-Related Elements:
<table>
  <tr>
    <td>Cells must be closed</td>
  </tr>
</table>
  1. Custom Elements:
<my-custom-element>
  Content must be closed
</my-custom-element>

Handling Special Closing Cases

HTML5 introduces some unique closing rules:

  1. Automatic Closing via Nesting Rules:
<p>Start paragraph
<div>New block-level elements automatically close preceding p tags</div>
  1. Error Handling for Void Elements:
<br></br> <!-- Parsed as two <br> tags -->
  1. Foreign Elements (MathML/SVG):
<svg>
  <circle cx="50" cy="50" r="40"/>
</svg>

Best Practices in Real-World Development

Although HTML5 allows omitting certain closing tags, for code maintainability, it is recommended to:

  1. Maintain Consistency:
<!-- Recommended -->
<ul>
  <li>Item one</li>
  <li>Item two</li>
</ul>

<!-- Not recommended -->
<ul>
  <li>Item one
  <li>Item two
</ul>
  1. Use XHTML-Style Closing:
<img src="photo.jpg" alt="Photo" />
<hr />
  1. Handling in Template Languages:
// In JSX, all tags must be closed
const Component = () => (
  <div>
    <img src="icon.png" alt="" />
    <br />
  </div>
);

Browser Parsing Differences

Different browsers handle tag closing with subtle variations:

  1. Chrome/Safari:
<p>First paragraph
<p>Second paragraph
<!-- Correctly generates two separate paragraphs -->
  1. Legacy IE:
<table>
  <tr>
    <td>Content
</table>
<!-- May cause DOM structure anomalies -->

Using Validation Tools

Use the W3C validator to check tag closing issues:

<!DOCTYPE html>
<html>
<head>
  <title>Validation Example</title>
</head>
<body>
  <main>
    <article>
      <h1>Title</h1>
      <p>Content
    </article>
  </main>
</body>
</html>

The validator will flag the unclosed <p> tag.

Special Requirements in Frameworks

Modern frontend frameworks may have additional closing requirements:

  1. Vue Single-File Components:
<template>
  <div>
    <img src="./assets/logo.png">
    <MyComponent/>
  </div>
</template>
  1. React JSX:
function App() {
  return (
    <>
      <input type="text" />
      <br />
    </>
  );
}

Historical Evolution and Design Considerations

HTML5's closing rule changes reflect the practical needs of web development:

  1. From XHTML's Strict Rules:
<!-- XHTML requirements -->
<br />
<hr />
<div></div>
  1. To HTML5's Pragmatism:
<!-- HTML5 allows -->
<br>
<hr>
<div>
  1. Special Cases in XML Serialization:
<script type="application/xml">
  <root>
    <item>XML content requires strict closing</item>
  </root>
</script>

Performance Impact Analysis

Tag closing methods have subtle effects on page loading:

  1. File Size Savings:
<!-- Omitting closing tags reduces HTML size by ~5-10% -->
<ul>
  <li>Item 1
  <li>Item 2
</ul>
  1. Parsing Speed Tests:
// Test code example
const bigHTML = '<div>' + '<p>Paragraph'.repeat(10000) + '</div>';
console.time('Parsing');
document.createElement('div').innerHTML = bigHTML;
console.timeEnd('Parsing');

Accessibility Considerations

Proper tag closing affects screen reader parsing:

  1. ARIA Attribute Dependencies:
<nav aria-label="Main navigation">
  <ul>
    <li><a href="/">Home</a>
    <li><a href="/about">About</a>
  </ul>
</nav>
  1. Landmark Roles:
<main>
  <article>
    <h1>Title</h1>
    <p>Content
  </article>
</main>

Server-Side Rendering Special Cases

Note these in SSR environments:

  1. PHP Short Tag Conflicts:
<?php
// Avoid confusion with HTML
echo '<img src="photo.jpg" alt="">';
?>
  1. Node.js Template Engines:
// EJS example
<%- include('header', {title: 'Page Title'}) %>
<div>
  <p>Main content
</div>

Mobile Optimization Strategies

Special handling for mobile devices:

  1. Extreme Bandwidth-Saving Practices:
<!DOCTYPE html>
<html>
<head><meta charset=utf-8><title>Minimal Page</title></head>
<body>
<main>
<h1>Title
<p>Content...
</body>
</html>
  1. AMP HTML Requirements:
<!doctype html>
<html ⚡>
<head>
  <meta charset="utf-8">
  <script async src="https://cdn.ampproject.org/v0.js"></script>
</head>
<body>
  <p>AMP pages require strict closing</p>
</body>
</html>

Interaction with CSS Selectors

Tag closing state affects style application:

  1. :empty Pseudo-Class:
<div class="box"></div>  <!-- Matches :empty -->
<div class="box"> </div> <!-- Does not match :empty -->
  1. Adjacent Sibling Selectors:
<h2>Title</h2>
<p>Paragraph one
<p>Paragraph two  <!-- Both p tags will apply styles -->

Toolchain Integration

Build tools handle tag closing:

  1. HTML Minifier Configuration:
const htmlmin = require('html-minifier');
const result = htmlmin.minify(html, {
  collapseBooleanAttributes: true,
  removeOptionalTags: true  // Automatically removes optional closing tags
});
  1. Prettier Formatting:
{
  "htmlWhitespaceSensitivity": "css",
  "printWidth": 80,
  "htmlSelfClosing": false
}

Team Collaboration Standards

Establish internal closing standards for teams:

  1. ESLint Rules:
// .eslintrc.js
module.exports = {
  rules: {
    'vue/html-self-closing': ['error', {
      html: {
        void: 'never',
        normal: 'always',
        component: 'always'
      }
    }]
  }
};
  1. Code Review Points:
- [ ] All non-void elements must be closed
- [ ] SVG/MathML use XML closing syntax
- [ ] Custom components maintain uniform style

Future Development Trends

Potential improvements under discussion by WHATWG:

  1. Further Simplification of Optional Tags:
<!doctype html>
<html>
<head>
  <meta charset=utf-8>
  <title>Future may be even simpler
<body>
  <h1>Main title
  <p>Content...
  1. Integration with Web Components:
<custom-drawer>
  <div slot=content>
    <p>Slot content requires strict closing
  </div>
</custom-drawer>

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.