What elements can be contained within a <a> tag?

All we need is an easy explanation of the problem, so here it is.

What are the valid html elements, if any, that can be contained within a <a> tag?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

As of HTML 5, <a> may contain not only (valid) inline elements, but also block elements, etc.

W3: http://dev.w3.org/html5/markup/a.html

Method 2

Inline elements ( a, span, strong, em among others ) can contain other inline elements and text nodes. An anchor can contain a span, which can contain a text node.

Generally, block-level elements may
contain inline elements and other
block-level elements. Generally,
inline elements may contain only data
and other inline elements. Inherent in
this structural distinction is the
idea that block elements create
“larger” structures than inline
elements.

From http://www.w3.org/TR/html401/struct/global.html

As noted in other answers, you can’t nest an a in an a.

Method 3

An <a> tag can contain any Inline Element besides another <a> tag.

Method 4

See the anchor section of the specification.

<!ELEMENT A - - (%inline;)* -(A)       -- anchor -->

The relevant section is (%inline;)* -(A), which means “Anything in the group %inline excluding A elements”. %inline is hyperlinked to make it easier for you to expand it.

Method 5

It can contain plain text and inline elements. Inline elements are following:

TT | I | B | BIG | SMALL | EM | STRONG | DFN | CODE | SAMP | 
KBD | VAR | CITE | ABBR | ACRONYM | A | IMG | OBJECT | BR | 
SCRIPT | MAP | Q | SUB | SUP | SPAN | BDO

But A can not be nested in another A and nesting SCRIPT doesn’t make senese.

Method 6

An anchor tag is an inline element, so it can contain other inline elements (except other anchor tags).

If you want to put a block element inside an anchor, you have to use an inline element and turn it into a block element using CSS, along with the anchor tag itself.

Example:

<a href="page.html" rel="nofollow noreferrer noopener" class="blocklink"><span>eat me</span></a>

CSS:

.blocklink { display: block; }
.blocklink span { display: block; }

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply