in spectrum in spectrum - 6 months ago 10
CSS Question

Should all of my clickable content be wrapped in either <a> or <button> tags?

I want more clarification on this: I have a website that uses a ton of JavaScript buttons styled with CSS like this:



nav ul { font-size:150%; text-align:center; margin:0; padding:0 }
nav li {
width:150px; height:150px; list-style:none; float:left; margin:5px;
-webkit-user-select:none; -moz-user-select:none; -ms-user-select:none;
user-select:none
}
nav li:hover { background:#022; color:#eee; cursor:pointer; }
nav li:active { background:#066; color:#fff }
nav span {
display:block; position:relative; top:50%;
-webkit-transform:translateY(-50%); transform:translateY(-50%)
}

<nav>
<ul>
<li><span>one</span></li>
<li><span>two</span></li>
<li><span>three</span></li>
</ul>
</nav>





Is it better semantically, functionally, etc. to use anchor tags instead like this, and why?:



nav ul { font-size:150%; text-align:center; margin:0; padding:0 }
nav li {
width:150px; height:150px; list-style:none; float:left; margin:5px;
-webkit-user-select:none; -moz-user-select:none; -ms-user-select:none;
user-select:none
}
nav li:hover { background:#022; color:#eee; }
nav li:active { background:#066; color:#fff }
nav span {
display:block; position:relative; top:50%;
-webkit-transform:translateY(-50%); transform:translateY(-50%)
}
nav a{ text-decoration:none; color:#222 }/* anchor styling added */

<nav>
<ul>
<a href="#"><li><span>one</span></li></a><!-- anchor tags added -->
<a href="#"><li><span>two</span></li></a>
<a href="#"><li><span>three</span></li></a>
</ul>
</nav>





what about using the
button
element instead of the other ways? Is there any difference?

Answer

The specification that w3.org has for <a> tags is kind of open ended.

The default behavior associated with a link is the retrieval of another Web resource. This behavior is commonly and implicitly obtained by selecting the link (e.g., by clicking, through keyboard input, etc.)... Authors may also create an A element that specifies no anchors, i.e., that doesn't specify href, name, or id. Values for these attributes may be set at a later time through scripts.

For <button>'s:

Push buttons have no default behavior. Each push button may have client-side scripts associated with the element's event attributes. When an event occurs (e.g., the user presses the button, releases it, etc.), the associated script is triggered.

Reading between the lines the general consensus I would stick to is: If it's a link it should link somewhere. If it performs an action it should be a button. Using divs or other elements for this behavior isn't semantic and it isn't the current accepted convention.

Comments