Why are nested anchor tags illegal?
Asked Answered
W

4

54

I learned that nesting anchor tags is not standards compliant HTML.

From W3:

Links and anchors defined by the A element must not be nested; an A element must not contain any other A elements.

Since the DTD defines the LINK element to be empty, LINK elements may not be nested either.

It would seem like alternatives such as those suggested in the selected answer in this question would have more of a chance of creating unexpected behavior than simply nesting the anchors would!

It also seems like overkill to make onclick event handlers just to redirect the page in JS. Not to mention using a script solution would cause problems for users browsing with scripts disabled.

EDIT

What is interesting was that I was working on a fiddle to demonstrate and I had overlooked that chrome was actually restructuring the DOM as such:

<div id="container">

    <a href="http://yahoo.com"></a>
    <div class="parent">
        <a href="http://yahoo.com">Parent Element</a>
        <a href="http://google.com">
            <div class="child">Child Element</div>
        </a>
        <a href="http://bing.com">
            <div class="child">Other Child</div>
        </a>
    </div>

</div>

I overlooked this because I saw the hover working and had my mouse on the text. Knowing this now doesn't necessarily change my question, but it sure does illustrate that it doesn't even work the way I thought.

Whitford answered 6/9, 2013 at 21:34 Comment(12)
If there are nested anchors then there is ambiguity about which anchor should be affected by a click of the internal anchorPrefabricate
@ExplosionPills couldn't the click just go to the innermost anchor in the nesting at the point the anchor was clicked?Ingoing
@Renan I agree. It seems to work that way in chrome and layout flow would suggest this naturally unless you were doing some very awkward things with the CSS.Whitford
Why do you want to nest anchor tags? why can't you simply have a collection of anchor tags in a div or something? I'm genuinely curious as to what desired outcome you are hoping for...Repay
@ShanRobertson Let me make a fiddle like the one the user did and add it to the question.Whitford
@Renan it could but ostensibly the W3C would prefer to avoid this possible ambiguity.Prefabricate
@ShanRobertson So am I. I'm guessing OP wants to have a link between other links. Nesting one link inside another would be less effort than writing three adjacent links.Ingoing
@Renan I'd have guessed the same thing. Note that the Question OP is refering to uses # href attributes... So it has something to do more than with just HTML, I'm sure.Joyner
Update to all, thank you kindly for your answers and comments, so far I've found much helpful information in them. I'm going to provide a fiddle as I promised but it may be a little bit before I have time to! Thanks!Whitford
The restructuring of the DOM that you see in Chrome (and other modern browsers) is the result of the Adoption Agency Algorithm which beat the "incest algorithm", the "secret affair algorithm", and the "Heisenberg algorithm" because it most accurately handles legacy malformed HTML, like attempts to nest <a> elements, in a backward compatible way.Anaphylaxis
@GeekyGuy _ couldn't the click just go to the innermost anchor in the nesting at the point the anchor was clicked_ => the <a> tag doesn't stop the propagation of the click event, so all the <a> (and any other tags) in the parents list would get the click event, thus undefined behaviour.Lucchesi
@santiagoarizti that goes against the specifications for anchors, see the answers to this question.Ingoing
C
57

Update:

The standards have changed over time, and "anchors" are now pretty much almost universally "links". But the problems with nesting them would still remain. Consider an example:

<a href="//google.com">
  <div>
    <a href="//microsoft.com">Click here</a> to go to Microsoft's website.
  </div>
</a>

What happens when you click on "click here"? You'll probably go to microsoft.com, but would it be wrong if you went to google.com instead? After all, you also clicked on that link. (And of course, if you click on "go to Microsoft's website" you'd definitely go to google.com, which is at best confusing to the user.)


Original, now ancient answer:

Keep in mind that an anchor isn't just a link, it's also something to which one can link. (Though the former use is far more common than the latter.) Quoting W3C (old, but relevant):

An anchor is a piece of text which marks the beginning and/or the end of a hypertext link.

To that end, don't think of an anchor as a link. Think of it as a point in the document which connects to (and/or from) another point (in the same document or another document, it makes no difference). Two points in some non-physical space which are connected by a non-physical thread.

Given that, anchors shouldn't contain a lot of content. If it contains a lot of content, it ceases to become a "point" and starts to become an "area." For example, imagine an anchor which when rendered takes up more space than the browser can display at once. If something links to that anchor, where should it go? The beginning? Middle? End? (Intuitively you might think the beginning, but you get the idea.)

Furthermore, anchors definitely shouldn't contain other anchors. The non-physical connections between the non-physical points can become ambiguous. Does the child anchor connect to the other point, or does the parent anchor connect to the other point? This probably doesn't result in being a big deal in most cases, since the vast majority of anchors today are one-way links from the anchor to another document. But the purpose of the anchor is more than just a one-way link to another document, so the definition continues to embody that purpose.

Choriamb answered 6/9, 2013 at 21:53 Comment(10)
I think your explanation of a point versus an area rings home the most. I think anchor tends to be one of those things that is understood at best incompletely. Thanks for the perspective.Whitford
Perfect explanation, which also highlights the disconnect between the intentions of so many tags and our understanding/use of them. Interestingly, this has changed somewhat as of HTML5, the <a> tag is now explicitly defined as a hyperlink, as opposed to just being an anchor. The "restriction" on content was also lifted, making the <a> tag officially able to contain "block"-level content (now called "flow"). W3.orgMethodical
Personally, I think these (everything I'm seeing, not your post specifically) are all poor excuses. Establish some sort of convention. Maybe even add some HTML attributes that can be provided to anchor elements to add customization on top of whatever the decided convention is. You could unambiguously derive the behavior of nested anchor tags, just like you can unambiguously derive the layout behaviors of nested and sibling elements with styling.Tea
There is a design principle that click/tap targets should be as large as possible. By that principle, links SHOULD BE areas. The HTML spec may have a differing opinion on the matter, but I would argue they are wrong.Hachmann
@ChristopherJamesCalo: That principle sounds like a broadly applied misinterpretation. By that statement alone, devoid of context, all links should be full-screen. But I digress... I think you're missing the point. We're not talking about design, we're talking about content. You can style your anchors however you wish. This is a question about HTML, not CSS. The HTML spec isn't "wrong" because it doesn't include CSS any more than a hammer is "wrong" because it can't be used as a screwdriver.Choriamb
I'm specifically responding to "anchors shouldn't contain a lot of content." How would the "anchors should be a point" world view recommend implementing Google Now-like cards in HTML? The entire card should be clickable, and it may contain lots of content.Hachmann
@ChristopherJamesCalo: You're confusing "anchors" with "clickable elements". Not everything clickable needs to be an anchor. An anchor tag has a more specific semantic meaning which has nothing to do with its clickability. (Hint: Not all anchors are clickable.) Google Now Cards are, and should be, clickable elements. But they are not anchors. A cursory examination of them reveals that they are div elements, which have much less specific semantic meanings and fewer restrictions around those semantics. Clickable divs are nothing new.Choriamb
When navigational elements are clickable but aren't anchors, they break basic web functionality like screen readers, open in new tab/window, and copy URL.Hachmann
@ChristopherJamesCalo: There are pros and cons. As with any choice, one places priorities where necessary. You had asked "how would [one] recommend implementing Google Now-like cards" without significant anchor content. Well, I'd do it exactly as Google did, which was without significant anchor content. You're right, HTML anchors alone don't provide us with the full rich modern content we've come to enjoy. I don't know why you would think they should. Sometimes that rich content doesn't work well with screen readers. The medium doesn't always support the user experience.Choriamb
nesting clickable elements is standard for every other tag out there and the behavior is well-defined (start from the bottom and bubble-up). there are no pros in the original spec here, except conservatism in the design; it's all cons: no accessibility, no navigation hinting, no visited/active styling, unexpected break from event bubbling, poor support for touch screens here try to touch a zero-dimension, non-physical point to connect to another page :/Conclave
P
12

The spec for <a> has a content model of:

Transparent, but there must be no interactive content descendant.

So the spec is actually more complicated than you say. This also applies to <button> -- essentially you can't have working links inside of links or buttons inside of buttons.

Unfortunately I don't have a strong answer to your question why -- I can only speculate. One clear reason is the ambiguity that it causes (e.g. which anchor should be followed when the inner one is clicked?)

This creates not only functional ambiguity, but also semantic ambiguity. The content of the <a> is a label for its hyperlink. So does this mean that the inner hyperlink is part of the label for the content of the outer link?

Prefabricate answered 6/9, 2013 at 21:56 Comment(2)
I can definitely get this reasoning. I can see the need for a programmer to be very explicit in how they want something like the example in my fiddle to work.Whitford
It's not like that ambiguity is an unresolvable problem, however. How hard is it to come up with some conventions and maybe some HTML attributes for control?Tea
L
5

While the other good people of the community gave excellent answer, I would like to contribute by giving an example of how to mimic nested anchor tags without actually nesting them in the markup, by making them appear visually as if one is inside another's area:

.parent{
  position: relative;
  width: 300px;
  height: 150px;
  border: 1px solid salmon;
}

.parent .main-link{
  display: block;
  margin-bottom: 2em;
}

/* 
  expands the clickable area of the main link 
  to fill the parent container, because it's the nearest
  ancestor with "position:relative"
*/
.parent .main-link::before{
  content: '';
  position: absolute;
  inset: 0;
}

.parent a:hover{
  color: green;
}

/* bring other links "forward" to make them clickable */
.parent .secondary-link{
  position: relative;
  z-index: 1;
  padding: 10px;
  background: lightgreen;
}
<div class='parent'>
  <a href='#111' class='main-link'>main link, full area</a>
  <a href='#222'class='secondary-link'>secondary link</a>
</div>
Loma answered 10/5, 2020 at 15:42 Comment(0)
J
1

Anchor nesting is not recommended by standards (although all browsers I tested it on seem to lead to the innermost click target) because of ambiguity.

It is not logic to say that a big part should lead to a certain page and in this part a small section should lead somewhere else. I still have to see any use case for this kind of behaviour. With the evolution of available scripting languages, this kind of iteration or heritage can work (javascript click events on divs for exemple), but never will a code want to direct to a certain URL and then to another (parent anchors' href).

Edit: Looking at the question you referenced in yours, stacking 2 anchors that point to the exact same href is completely useless. Just remove the nested one and everything is gonna be good. If it is because you did a CSS rule like a a{color:red;} use a span! Or even a div with display:inline but please, pretty please, an anchor should go somewhere, should not be used just for styling purpose or something.

Joyner answered 6/9, 2013 at 21:47 Comment(5)
What about if the internal anchor is supposed to link to a particular part of the resource referenced by the external anchor? For example, a #comments section?Overtrick
@DanielJames although you may find some "logic" reasons to do so, you have to understand that it is not semantically correct and since the standards do not plan such irregularity, browser implementations are free to handle that situation differently which could cause unexpected behaviors...Joyner
that does not answer the posted question at all. The question was clearly about why the HTML spec from WHATG and W3C was written as it is. Saying "you have to understand that the standards are this way" and then saying something irrelevant about browser behaviour when the spec is not followed adds nothing to the conversation at all. Furthermore, if you check my post history, you'll see that I have clearly documented exactly what happens when the spec is not followed.Overtrick
@DanielJames I simply tried to answer your question, not the original question...Joyner
"all browsers [...] lead to the innermost click target" I've tested Chrome 88, Firefox 85, WebKit 605.1.15 (GNOME Web), Microsoft Edge 42, IE 11, UC Browser 7.0.185.1002, Baidu Browser 43.23 => they all workShimmy

© 2022 - 2024 — McMap. All rights reserved.