I’m puzzled by the tag in HTML. People say it’s an empty tag, but it can have attributes like src, alt, width, height, and id. Can someone clear up whether it’s truly empty and shed light on why it supports these attributes?
Is it really a empty tag?
5
Answers
every tag in html is not empty tag you can add css, id, and classes to them so called attributes.THere is no such thing in html like empty tag yes there are tag who
are self closed
ex
,,
It’s "empty" in the sense that it doesn’t have content within its opening and closing tags. For example, the
<p>
has text between its opening and closing tags (<p>Lorum ipsum dolor</p>
). For an<img>
, you don’t have a closing tag (</img>
), and its behavior is defined entirely by its attributes (width
,height
,src
, etc).MDN Reference
In html we consider a tag empty tag when it does not have closing tag , because img tag does not have closing tag so we say it empty tag. Empty tag does not mean the tag don’t have any attribute it means the tag does not have closing tag.
No tag is not empty, it have attributes
The src attribute is required, and contains the path to the image you want to embed.
The alt attribute holds a textual replacement for the image, which is mandatory and incredibly useful for accessibility — screen readers read the attribute value out to their users so they know what the image means. Alt text is also displayed on the page if the image can’t be loaded for some reason: for example, network errors, content blocking, or linkrot.
There are many other attributes to achieve various purposes:
Referrer/CORS control for security and privacy: see crossorigin and referrerpolicy.
Use both width and height to set the intrinsic size of the image, allowing it to take up space before it loads, to mitigate content layout shifts.
Responsive image hints with sizes and srcset (see also the element and our Responsive images tutorial).
tag documentation
The concept of
empty tag
/void tag
/self-closing tag
is that which doesn’t contain any children element. So, you can consider it as aleaf tag
that doesn’t have even the text inside it. And as these tags don’t support child elements, they don’t have a corresponding closing tag either. Examples are-<img>
,<br>
,<hr>
,<meta>
,<link>
etc.In HTML5, even we don’t need to close those tags. By default according to the HTML5 specification, there are 15 empty tags, these are also known as
void tags
orself-closing
because they do not have a corresponding closing tag and they cannot contain other elements.[Note: Attributes inside a tag, help us to define their behavior & view. Different tags support different attributes. But tag itself an empty/void identifies from the capability of accepting a children element or not.]