Why are nested anchor tags illegal?

33,899

Solution 1

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.

Solution 2

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?

Solution 3

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;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}

.parent a:hover{
  color: green;
}

/* bring other links "forward" to make them clickable */
.parent .secondary-link{
  position: relative;
  z-index: 1;
}
<div class='parent'>
  <a href='#111' class='main-link'>main link, full area</a>
  <a href='#222'class='secondary-link'>secondary link</a>
</div>

Solution 4

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.

Share:
33,899

Related videos on Youtube

Doug Morrow
Author by

Doug Morrow

Updated on July 09, 2022

Comments

  • Doug Morrow
    Doug Morrow almost 2 years

    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.

    • Explosion Pills
      Explosion Pills over 10 years
      If there are nested anchors then there is ambiguity about which anchor should be affected by a click of the internal anchor
    • Geeky Guy
      Geeky Guy over 10 years
      @ExplosionPills couldn't the click just go to the innermost anchor in the nesting at the point the anchor was clicked?
    • Doug Morrow
      Doug Morrow over 10 years
      @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.
    • Shan Robertson
      Shan Robertson over 10 years
      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...
    • Doug Morrow
      Doug Morrow over 10 years
      @ShanRobertson Let me make a fiddle like the one the user did and add it to the question.
    • Explosion Pills
      Explosion Pills over 10 years
      @Renan it could but ostensibly the W3C would prefer to avoid this possible ambiguity.
    • Geeky Guy
      Geeky Guy over 10 years
      @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.
    • Salketer
      Salketer over 10 years
      @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.
    • Doug Morrow
      Doug Morrow over 10 years
      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!
    • Alohci
      Alohci over 10 years
      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.
  • Doug Morrow
    Doug Morrow over 10 years
    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.
  • Doug Morrow
    Doug Morrow over 10 years
    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.
  • ench
    ench over 10 years
    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.org
  • Admin
    Admin almost 9 years
    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.
  • Admin
    Admin almost 9 years
    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?
  • manafi
    manafi over 8 years
    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.
  • David
    David over 8 years
    @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.
  • manafi
    manafi over 8 years
    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.
  • David
    David over 8 years
    @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.
  • manafi
    manafi over 8 years
    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.
  • David
    David over 8 years
    @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.
  • DMCoding
    DMCoding about 8 years
    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?
  • Salketer
    Salketer about 8 years
    @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...
  • DMCoding
    DMCoding about 8 years
    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.
  • Salketer
    Salketer about 8 years
    @DanielJames I simply tried to answer your question, not the original question...
  • worc
    worc over 5 years
    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 :/
  • tanguy_k
    tanguy_k about 3 years
    "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 work