Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making buttons - <button> or <div>?

Tags:

html

Don't use <div> tags to make clickable elements. Use <a> or <button> elements. This enables browsers with JavaScript disabled to interact with them as expected. Even if your functionality requires JavaScript and there is no reasonable default behaviour you can assign to an <a>, use it regardless - it conveys "clickable" semantics.

In general, choose the tag that most closely describes the function of its content, not the appearance of its content, and avoid unnecessary <div> tags lest your documents suffer from divitis.


The "more" button on Twitter is an <a> with a background-image, CSS3 rounded corners, and a border. Here's the complete CSS (elem is <a class="more round">):

 .more {
      outline: none;
      display: block;
      width: 100%;
      padding: 6px 0;
      text-align: center;
      border: 1px solid #ddd;
      border-bottom: 1px solid #aaa;
      border-right: 1px solid #aaa;
      background-color: #fff;
      background-repeat: repeat-x;
      background-position: left top;
      font-size: 14px;
      text-shadow: 1px 1px 1px #fff;
      font-weight: bold;
      height: 22px;
      line-height: 1.5em;
      margin-bottom: 6px;
      background-image: url('/images/more.gif');
    }
    
    .more:hover {
      border: 1px solid #bbb;
      text-decoration: none;
      background-position: left -78px;
    }
    
    .more:active {
      color: #666;
      background-position: left -38px;
    }
    
    .round {
      -moz-border-radius: 5px;
      -webkit-border-radius: 5px;
    }
<a href="#" class="more round">Sample Button</a>

You should use <a> or <button>, not <div>.


In general you want to use <a> for navigation and <button> for some action that takes place on that screen.

The best reason I can think of to prefer a <button> or <a> tag to <anything-else> is that during testing, it makes it easier to locate the actionable items. I use Capybara and Rspec for example, and the method click_on works a lot more reliably when it refers to a <button>, the same with the method click_link and <a>.

The other reasons given here are also good: semantics, screen readers, etc.

Pragmatically, your audience will decide if every single element on your page is a really fancy <div> or if you want to play nice with the rest of the web dev ecosystem. It may simply depend on whether your audience all uses X browser or not.

One gotcha: Since a <button> could submit a form or <a> take you to another page, you have to make sure to prevent those default actions. In the JavaScript function that handles the click, you have to specify that it only does the action you program.

function onClickEvent(e)
{
  e.preventDefault();
  // What you want to do instead
}