Jamus
Jamus

Reputation: 865

HTML 5, linking with a div

At the moment I have a setup similar to this:

<a href="#">
  <div style="width: 50px; height: 20px;">
    <span>Blah</span>
  </div>
</a>

Which works perfectly well in Chrome. It fails W3C validation, however - IE apparently has issues with it.

I've considered using JavaScript to do it, but I know a lot of older web-users disable JavaScript for security concerns (personally, I'd just stop using old versions of IE. the pains)

But I was wondering, what's the HTML5 approved way to do this?

Before anyone downvotes, I'd like to reiterate that I'm asking specific to HTML 5.

Upvotes: 0

Views: 74

Answers (2)

moribvndvs
moribvndvs

Reputation: 42497

Just use CSS to make the anchor a block or inline block element so it can be given a height and width. Use either a CSS selector or an inline style attribute to assign display:block or display:inline-block, set the height and width, and get rid of the div.

<a href="#" style="display:block;width: 50px; height: 20px;">
    <span>Blah</span>
</a>

If you're not sure about block vs inline-block, there are lots of articles on the web. However, block elements exist on their own line (barring things like float), but may have a height and width (amongst other things). inline-block can also be assigned height and width, but can exist inline with other elements. Caveat, some browsers cougholdversionsofIEcough don't understand inline-block or have bugs with it (there are ways around that). inline (the default for a), technically can't be given a height or width. And obviously the insinuation here is you can make inline elements behave like block elements, and vise versa.

EDIT

As per the comments, here's a CSS hack to make inline-block work reasonably well for proper browsers and also IE7-8.

.my-inline-block-element {
  display:inline-block;
  zoom:1;
  *display:inline;
  width: 50px;
  height: 20px;
}

Good browsers will see display and use inline-block. IE7-8 will say WTF is that and do something stupid. But it'll see zoom which will trigger hasLayout, and because of a bug, it'll process *display:inline (but other browsers won't because * isn't allowed) and set display back to inline. But since we've got hasLayout, it'll now use the height and width but remain inline. Confused? Annoyed? Good... IE sucks.

Upvotes: 2

ceejayoz
ceejayoz

Reputation: 180024

It's perfectly valid HTML5 if you fix the missing quotation mark in your style attribute. Try putting this in the HTML5 validator:

<!DOCTYPE html>
<head><meta charset="utf-8"><title>Something</title></head>
<body><a href="#">
  <div style="width: 50px; height: 20px;">
    <span>Blah</span>
  </div>
</a>
</body>

enter image description here

Upvotes: 2

Related Questions