4

I have made a simple fragment of html, which contains this:

<a href="#"><div>Something here</div></a>

It obviously alert me that div cannot be inside an <a> tag. I have used a div, because I want the whole box (div in this case) to be a button. So the subclass :hover and a proper button area applies to the whole box, not only a text inside. As far as I remember divs can be used inside tags in html5. I use XHTML 1.0 Transitional. Is there anything I can replace a div with to avoid errors in the code? or should I change xhtml to html5? will it work good without touching the rest of the code? thank you.

Piotr Ciszewski
  • 1,691
  • 4
  • 30
  • 53
  • 4
    What's the point of working under an XHTML doctype if you're knowingly writing invalid code (under that doctype)? Just switch to HTML5 if you want to use HTML5. – David Thomas Aug 05 '12 at 13:28
  • 4
    What's the purpose of the
    here? Wouldn't a{display:block;} behave as requested?
    – darma Aug 05 '12 at 13:29
  • 2
    You can either use the `!DOCTYPE html` for HTML5 or stay with the XHTML doctype and wrap **the content** of the `div` with `a`, while giving it a `display: block` CSS property. Removing the `div` wouldn't hurt either in the second case, unless it serves some other purpose too. – toniedzwiedz Aug 05 '12 at 13:30
  • possible duplicate of [Is putting a div inside an anchor ever correct?](http://stackoverflow.com/questions/1827965/is-putting-a-div-inside-an-anchor-ever-correct) – Ciro Santilli OurBigBook.com Jan 30 '14 at 13:05

5 Answers5

6

You could use display:block.

An example is as follows:

HTML:

<a href="#" class="btn"​​​​​​​​​​​​​​​​​​​​​>Button</a>​​​​​​​​​​​​​

CSS:

​a.btn{
    display: block;
    background-color: Green;
    width: 50px;
    height: 25px;
    text-align: center;
    text-decoration: none;
    color: White;
}
a.btn:hover{
    background-color: lightGreen;
    color: Black;
}

​ You can test it live here: http://jsfiddle.net/YdCzY/

Akhilesh B Chandran
  • 6,523
  • 7
  • 28
  • 55
1

Try using this:

HTML:

<a id="block-a" href="#">Something here</a>

CSS:

#block-a {
    display: block;
}
Anish Gupta
  • 2,218
  • 2
  • 23
  • 37
1

You could try using 'span' elements within the 'a' element instead of divs...

You can apply styles to the span so that it behaves just like the div you wanted (e.g. rich content which is also overally a link).

AFAICS, the only difference between span and div are the default styles, and the elements they're allowed to be children of. But I am willing to be corrected by more learned contributors...

Jake
  • 948
  • 8
  • 19
0

Use

<div onclick="..">...</div>

or a display: block; on your a-tag (http://green-beast.com/blog/?p=74)

Chris
  • 4,255
  • 7
  • 42
  • 83
0

It is way more easier at least

`<div onclik="window.location.href='url'">
</div>`
Nagibaba
  • 4,218
  • 1
  • 35
  • 43