开发者

Block Level Elements in <a> Tag, Validation vs Usability

开发者 https://www.devze.com 2023-01-08 12:43 出处:网络
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:

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:

  1. Is this a valid reason for this not to validate?
  2. Is the usability gain (by having a larger clickable area) worth it not validating?
  3. 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:

  1. Not worth the energy to argue.
  2. Not if you can find a better way.
  3. Use <span> tags instead of divs (really, what is to be gained by making a div display:inline?); or use Javascript and add an onclick event to the containing <li>.


  1. In my opinion, yes. However, you're pretty much on your own if you decide to disregard validation.

  2. Benefits to the user win over benefits to the author, certainly.

  3. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消