Are custom elements valid HTML5?

后端 未结 12 1233
执念已碎
执念已碎 2020-11-22 09:27

I\'ve been unable to find a definitive answer to whether custom tags are valid in HTML5, like this:

Hello!

12条回答
  •  情深已故
    2020-11-22 09:50

    Basic Custom Elements and Attributes

    Custom elements and attributes are valid in HTML, provided that:

    • Element names are lowercase and begin with x-
    • Attribute names are lowercase and begin with data-

    For example, or
    .

    A common convention for elements is x-foo; x-vendor-feature is recommended.

    This handles most cases, since it's arguably rare that a developer would need all the power that comes with registering their elements. The syntax is also adequately valid and stable. A more detailed explanation is below.

    Advanced Custom Elements and Attributes

    As of 2014, there's a new, much-improved way to register custom elements and attributes. It won't work in older browsers such as IE 9 or Chrome/Firefox 20. But it allows you to use the standard HTMLElement interface, prevent collisions, use non-x-* and non-data-* names, and define custom behavior and syntax for the browser to respect. It requires a bit of fancy JavaScript, as detailed in the links below.

    HTML5 Rocks - Defining New Elements in HTML
    WebComponents.org - Introduction to Custom Elements
    W3C - Web Components: Custom Elements

    Regarding The Validity of The Basic Syntax

    Using data-* for custom attribute names has been perfectly valid for some time, and even works with older versions of HTML.

    W3C - HTML5: Extensibility

    As for custom (unregistered) element names, the W3C strongly recommends against them, and considers them non-conforming. But browsers are required to support them, and x-* identifiers won't conflict with future HTML specs and x-vendor-feature identifiers won't conflict with other developers. A custom DTD can be used to work around any picky browsers.

    Here are some relevant excerpts from the official docs:

    "Applicable specifications MAY define new document content (e.g. a foobar element) [...]. If the syntax and semantics of a given conforming HTML5 document is unchanged by the use of applicable specification(s), then that document remains a conforming HTML5 document."

    "User agents must treat elements and attributes that they do not understand as semantically neutral; leaving them in the DOM (for DOM processors), and styling them according to CSS (for CSS processors), but not inferring any meaning from them."

    "User agents are not free to handle non-conformant documents as they please; the processing model described in this specification applies to implementations regardless of the conformity of the input documents."

    "The HTMLUnknownElement interface must be used for HTML elements that are not defined by this specification."

    W3C - HTML5: Conforming Documents
    WhatWG - HTML Standard: DOM Elements

提交回复
热议问题