Can I Use Self-closing Tags With Input Elements?
Solution 1:
The HTML specification states and clearly shows by example that the proper syntax is <input>
. While <input/>
is allowed, and called a void element, the closing slash has no meaning, it does nothing and browsers are instructed to ignore it.
If you are concerned about how a browser will handle it, the best advice, as always, is to do what the specification says to do and always use the specified and always valid <input>
.
Solution 2:
The WHATWG spec requires that modern browsers support void elements, though the main editor of the spec is notably opposed to calling a document XML (and including self-closing elements) if it isn't served with a XML mime type.
Chrome and Firefox rewrite that void tag by removing the slash, but Microsoft Edge doesn't.
The spec at https://www.w3.org/TR/xhtml11/ is old, from 2010. The official Living HTML spec includes what the WHATWG calls "the XML syntax" of HTML5, so it's not correct to say that developers may not use it, as long as the document is served as application/xhtml+xml
(though that's rare) and it has an XML namespace such as <html xmlns="http://www.w3.org/1999/xhtml" lang="en">
.
For example, according to Validator.nu, this document, even though it includes a void <input/>
element, is valid "HTML5 + ARIA + SVG 1.1 + MathML 2.0":
<!DOCTYPE html><htmlxmlns="http://www.w3.org/1999/xhtml"lang="en"><head><title>Test</title></head><body><p><input/></p></body></html>
For me, this is not mere theory or nitpicking. I had to use XML syntax at my last job or my work couldn't get done. When I didn't include closing slashes on void elements in my web templates, our expensive enterprise-level content management system would arbitrarily rearrange or remove divs. So it was difficult to get our CMS to produce HTML without XML syntax. That convinced me that insisting on removing closing slashes can be as cult-like as insisting on including them.
More discussion at https://stackoverflow.com/a/3558200/1584531
Solution 3:
No, <input/>
(and <br/>
, <hr/>
, <image/>
, and so on) is not proper syntax for HTML (any version). It's just that the HTML5 spec describes how these XML-isms are ignored/recovered by lenient parsers. There's also the cargo-cult usage of <input />
(eg. with a space between the element name and the slash character in the hope a browser would ignore it more robustly than without).
These practices came up with XHTML and the desire to use XML tools for HTML, or to author content for HTML and XHTML simultaneously, but are generally discouraged in modern HTML.
Post a Comment for "Can I Use Self-closing Tags With Input Elements?"