Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

div inside anchor

Tags:

html

hyperlink

This doesn't happen all the time. A bug is not a bug if cannot be reproduced!

First, I thought this was a mistake of my young programming skills but same error appears in my two sites, apparently under the same circumstances.

<a style="display:block;" href="link">
 <div>text1</div>
 <div>text2</div>
</a>

Sometimes, while browsing, links with divs inside them render strangely, duplicate elements appear on the page with no reason, text gets distributed between different links, a real mess.

Real screenshots:

http://cupacupelor.ro/img/help.jpg
http://www.carbroker.ro/img/help.jpg

Anyone faced this problem? Is there a solution? I'm not interested of fixes involving JavaScript!

like image 622
Sorin Avatar asked Jul 07 '09 11:07

Sorin


People also ask

Can you have div inside anchor?

You can't put <div> inside <a> - it's not valid (X)HTML.

Can I put div inside TD?

Using a div instide a td is not worse than any other way of using tables for layout. (Some people never use tables for layout though, and I happen to be one of them.) If you use a div in a td you will however get in a situation where it might be hard to predict how the elements will be sized.

What can go inside an anchor tag?

As of HTML5 - which was released years ago - it is OK to wrap block-level elements inside of an Anchor tag. In fact, pretty much the only thing you can't put inside of an Anchor tag is another Anchor tag.


2 Answers

I guess your divs in links cause inconsistency in some browsers (may be your css playing here).

"Semantics", valid markup are some buzz words.

So why would you want DIVs in an <A> tag. You can try someting like this

<a href="#">
       <span class="divstyle">Text 1</span>
       <span class="divstyle">Text 2</span>
</a>

then in CSS

.divstyle { 
    display: block; //and other styles etc
 }
like image 50
TigerTiger Avatar answered Oct 07 '22 07:10

TigerTiger


Check your page in a HTML validator. I'm 90% sure that you can't have a <div> element inside inline elements like <a>. Even though you've set the link to display:block, it's still not allowed and the browsers may be spitting their dummy.

What you can do is use spans instead, setting them to block:

<style type="text/css">
  .link, .link span { display: block; }
</style>
<a class="link" href="example.com">
 <span>text1</span>
 <span>text2</span>
</a>
like image 41
DisgruntledGoat Avatar answered Oct 07 '22 06:10

DisgruntledGoat