1

What are the rules of using a_tag, div_tag and button_tag as button in HTML?

I am a Ruby on Rails user. Rails default gives input_tag and button_tag as button. What are the advantages of using other tags beside button_tag itself? When should I use each one?

Thanks in advance.

Ivan Wang
  • 8,306
  • 14
  • 44
  • 56

1 Answers1

1

Without introducing any attributes, there is one HTML button element:

<button></button>

There is also a generic form input element which can be set to render as a button:

<input />

Both of these elements accept three button-type attributes which let user agents determine their behaviour (as buttons):

<button type="button">Regular button</button>
<input type="button" value="Regular button" />

<button type="submit">Form submit button</button>
<input type="submit" value="Form submit button" />

<button type="reset">Form reset button</button>
<input type="reset" value="Form reset button" />

These two elements behave identically when these attributes are set. The main difference between the two elements is that the button element can contain HTML whereas an input element may only contain text passed in through its value attribute (see <button> vs. <input type="button" />. Which to use?):

<button type="button">
    <span>This is perfectly valid</span>
</button>

<input type="button" value="No HTML permitted here" />

(As a side note, a button element accepts any phrasing content descendant which isn't interactive content (another button or a checkbox, for example).

However, from an accessibility perspective any HTML element which accepts a role attribute can be turned into a button simply by declaring role="button":

<a role="button"></a>
<div role="button"></div>
<span role="button"></span>
...

These are all perfectly valid, and complying user agents will treat all of these as buttons.

How you use them depends entirely on the context. If your button is within a form, you're going to want to use an input element; if your button is standalone on your page, you're going to want to use a button element; if your button is found within a list of hyperlinks, you may as well just use an a element with a role of "button", but you could just use button here as well if you wanted to. Bear in mind that the type attribute's submit, reset and button values are only valid on button and input elements and will have no effect when added to any other element with a "button" role.

Community
  • 1
  • 1
James Donnelly
  • 126,410
  • 34
  • 208
  • 218
  • Thanks. But I still don't understand why it is designed that way. Having all these methods to do the same thing seems very redundant to me. Is there benefits to use `a` among `a` list? If `button` supports everything better and more natively, why do we not just stick with `button`? Is it because `button` is harder to stylize? – Ivan Wang Jan 02 '14 at 02:12