Ad

Wrapping Anchor Elements With Text

- 1 answer

If an anchor element has text (and only text), but is not part of a larger block of text, does it matter (e.g. semantics, SEO, maintenance) whether or not that anchor tag is wrapped by a paragraph element?

<!-- Wrapped -->
<p><a href=''>Link Description</a></p>

<!-- Standard -->
<a href=''>Link Description</a>

Looking at large websites, both ways appear to be popular. But are there any notable differences?

Ad

Answer

(Note that p should only be used for paragraphs. If it’s not a paragraph, and you want to use such a wrapper, use div instead; if it is a paragraph, p should be used anyway.)

I can think of two cases where such a wrapper semantically matters (see below). Another good reason for using a wrapper is, of course, if the existing CSS/JS suggests/requires it (e.g., if the CSS author decided to style div elements, and an a without a div wrapper would break the layout).

Line breaks

User agents that don’t support author-provided CSS (like text browsers, feed readers, etc.) typically start a new line for elements like div, p, etc. (i.e., "block-level elements" in HTML 4), but not for elements like span, a, etc. ("inline elements").

So if you have something like this:

<p>Teaser with some text.</p>
<a target="_blank" rel="nofollow noreferrer" target="_blank" rel="nofollow noreferrer" href="link">Read more</a>
<cite>John Doe</cite>

such a user agent might display the last two elements on the same line:

Teaser with some text.

Read more John Doe

while it might be preferable to have each on its own line:

Teaser with some text.

Read more

John Doe

So for this and similar cases a wrapping element (that typically creates a new line by default) should be used.

If the a is the only phrasing content element (e.g., between two p elements), then this is not an issue, of course.

Unclosed p

If a p element has no closing tag (which is valid), a following a would become part of the p:

<p>some text

<a target="_blank" rel="nofollow noreferrer" target="_blank" rel="nofollow noreferrer" href="link">Read more</a>

If closing the p is not an option, one would have to use a wrapper for the a (one that can’t be a child of p, e.g., a div).

Ad
source: stackoverflow.com
Ad