tags:

views:

1693

answers:

8

I want to nest span and a tags. Should I

  1. Put <span> inside <a>
  2. Put <a> inside <span>
  3. It doesn't matter ?
+3  A: 

It doesn't matter - they're both allowed inside each other.

Greg
But <a> is a block level and <span> is inline level element and Block level element cannot come inside inline element. I think it was in w3c validation
metal-gear-solid
No, both are inline
Greg
+4  A: 

that depends on what you want to markup.

  • if you want a link inside a span, put <a> inside <span>.
  • if you want to markup something in a link, put <span> into <a>
knittl
+1  A: 

It depends on what the span is for. If it refers to the text of the link, and not the fact that it is a link, choose #1. If the span refers to the link as a whole, then choose #2. Unless you explain what the span represents, there's not much more of an answer than that. They're both inline elements, can be syntactically nested in any order.

sykora
Correct, they are both inline elements.
Chris
+1  A: 

It will work both, but personally I'd prefer option 2 so the span is "around" the link.

Oldskool
+6  A: 

3 - It doesn't matter.

BUT, I tend to only use a <span> inside an <a> if it's only for a part of the contents of the tag i.e.

<a href="#">some <span class="red">text</span></a>

Rather than:

<a href="#"><span class="red">some text</span></a>

Which should obviously just be:

<a href="#" class="red">some text</a>
Jon Hadley
A: 

It is perfectly valid (at least by HTML 4.01 and XHTML 1.0 standards) to nest either a <span> inside an <a> or an <a> inside a <span>.

Just to prove it to yourself, you can always check it out an the W3C MarkUp Validation Service

I tried validating:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"&gt;
  <html>
    <head>
      <title>Title</title>
    </head>
    <body>
       <p>
         <a href="http://www.google.com/"&gt;&lt;span&gt;Google&lt;/span&gt;&lt;/a&gt;
       </p>
    </body>
  </html>

And also the same as above, but with the <a> inside the <span>

i.e.

<span><a href="http://www.google.com"&gt;Google&lt;/a&gt;&lt;/span&gt;

with both HTML 4.01 and XHTML 1.0 doctypes, and both passed validation successfully!

Only thing to be aware of is to ensure that you close the tags in the correct order. So if you start with a <span> then an <a>, make sure you close the <a> tag first before closing the <span> and vice-versa.

CraigTP
A: 

Semantically I think makes more sense as is a container for a single element and if you need to nest them then that suggests more than element will be inside of the outer one.

Toby
A: 

SPAN is a GENERIC inline container. It does not matter whether an a is inside span or span is inside a as both are inline elements. Feel free to do whatever seems logically correct to you.

Salman A