randomable
randomable

Reputation: 417

Can you put multiple elements in an html a tag?

Very newbie question.

For instance, is this okay?

<a href="allaboutpeanuts.html">Peanuts<img src="peanut.jpg"> </a>

I tried it and it works fine, but I've been googling around and I can't find any mention of anyone putting more than one element in an a href. So are you not actually supposed to do that, but I cheated, so it's sort of a hack?

Upvotes: 4

Views: 9744

Answers (3)

roryf
roryf

Reputation: 30160

This is perfectly valid HTML, just note the following constraints:

In HTML 4.01 and XHTML, only inline elements are valid as children of an <a> tag (e.g. <span>)

In HTML5, this has been changed to allow non-interactive block level elements - e.g. you can nest <p>, <div>, <h1> or even <section>, but not a further <a> or <input>. [See The a element]

Upvotes: 5

VoteyDisciple
VoteyDisciple

Reputation: 37803

Yes, absolutely. HTML tags can be nested in any combination and any number.

The main rule is that they must nest properly. So this is not valid:

<a href="allaboutpeanuts.html">Peanuts <h1>Lovely <img src="peanut.png" alt="Peanut" /></a> Peanuts</h1>

The h1 tag is not completely inside the a tag.

This, however, is entirely valid:

<div><h1><a href="allaboutpeanuts.html">Peanuts <img src="peanut.png" alt="Peanut" /></a></h1></div>

Upvotes: 9

Māris Kiseļovs
Māris Kiseļovs

Reputation: 17285

Yes, it's correct - you can place one element into another. The only illegal thing is to place block elements inside inline elements.

Upvotes: 1

Related Questions