Block Level Elements in <a> Tag, Validation vs Usability
I have often wrapped block level elements with <a>
tags in order to make the whole group clickable. For example, say I have a list of events:
<ul>
<li>
<a href="#" style="display: block;">
<div style="float: left; display: inline;">12/12/2010</div>
<div style="float: left; display: inline;">Some event information</div>
</a>
</li>
<!-- etc... -->
</ul>
NOTE: inline styles applied for example only.
This way, the whole thing is clickable rather than only the text within the elements.
Ofcourse, the (x)html validator at validator.w3.org doesn't like this because I've placed a block level element (<div>
) insider an inline level element (<a>
). Even though, I am using CSS to define the <a>
tags as block level, and the <div>
tags as inline.
I've always coded by the rule of thumb that you should always strive to author valid code; however, if your code doesn't validate, and you understand why it doesn't validate, and you have a valid reason for it not validating, then don't worry about it.
So my question is tri-fold:
- Is this a valid reason for this not to validate?
- Is the usability gain (by having a larger clickable area) worth it not validating?
- Is there a better way?
Using span
as below is perfectly valid and you can achieve the same effect.
<a href="#" style="display: block;">
<span style="float: left;">12/12/2010</span>
<span style="float: left;">Some event information</span>
</a>
I would use <span>
instead of <div>
and then apply the same styling. That way you get the best of all worlds. You can still have your larger click targets, but it will also validate.
With respect to your three questions:
- Not worth the energy to argue.
- Not if you can find a better way.
- Use
<span>
tags instead of divs (really, what is to be gained by making a divdisplay:inline
?); or use Javascript and add an onclick event to the containing<li>
.
In my opinion, yes. However, you're pretty much on your own if you decide to disregard validation.
Benefits to the user win over benefits to the author, certainly.
Use HTML5, where
<a>
elements are allowed to wrap block level elements.
I have solved this by adding an onclick event to the div, ie onclick="window.location='redirectpage.html'"> and then the style cursor:pointer. Works like a charm and also validates.
精彩评论