1.21 gigawatts
1.21 gigawatts

Reputation: 17888

Can anchors be used in place of div containers?

Is there any reason to not use an anchor tag instead of a div tag as a container?

Current code:

<a href="#page1.html">
    <div id="container">
        <span>Some content</span>
    </div>
</a>

Proposed code:

<a id="container" href="#page1.html">
    <span>Some content</span>
</a>

Here is a live demo that seems to run:

.myClass {
  opacity: 1;
  position: absolute;
  left: 50px;
  top: 30px;
  box-sizing: border-box;
  margin: 0;
  padding: 0;
  overflow: visible;
  width: 148px;
  white-space: nowrap;
  text-align: left;
  font-family: Comic Sans MS;
  font-style: normal;
  font-weight: bold;
  font-size: 12px;
  color: rgba(112, 112, 112, 1);
  outline: 1px dashed red;
}

.class2 {
  top: 60px;
}
<a href="#page1.html">
  <div id="container" class="myClass">
    <span>Some content</span>
  </div>
</a>


<a href="#page1.html" class="myClass class2">
  <span>Some content</span>
</a>

Upvotes: 1

Views: 871

Answers (1)

Hooman Bahreini
Hooman Bahreini

Reputation: 15579

This perfectly valid in HTML5:

<a href="#page1.html">
    <div id="container">
        <span>Some content</span>
    </div>
</a>

The only difference is that an anchor tag's default display is inline while the defautl display of div is block.

From w3.org:

The a element may be wrapped around entire paragraphs, lists, tables, and so forth, even entire sections, so long as there is no interactive content within (e.g. buttons or other links). This example shows how this can be used to make an entire advertising block into a link:

<aside class="advertising">
 <h1>Advertising</h1>
 <a href="http://ad.example.com/?adid=1929&amp;pubid=1422">
  <section>
   <h1>Mellblomatic 9000!</h1>
   <p>Turn all your widgets into mellbloms!</p>
   <p>Only $9.99 plus shipping and handling.</p>
  </section>
 </a>
 <a href="http://ad.example.com/?adid=375&amp;pubid=1422">
  <section>
   <h1>The Mellblom Browser</h1>
   <p>Web browsing at the speed of light.</p>
   <p>No other browser goes faster!</p>
  </section>
 </a>
</aside>

upadted answer

The only difference between using a div and span inside an anchor is their display... as you can see in the example below, the spans are displayed inline while divs are displayed as block elements (of course you can change the default display in css):

<a href="#">
    <span>inline element1</span>
</a>

<a href="#">
    <span>inline element2</span>
</a>


<a href="#page1.html" class="myClass class2">
  <div>block elemnt1</div>
</a>

<a href="#page1.html" class="myClass class2">
  <div>block elemnt2</div>
</a>

Upvotes: 3

Related Questions