Joshua Sortino
Joshua Sortino

Reputation: 2417

Is it semantically incorrect to put a <div> or <span> inside of a <button>?

I'd like to do the following, but is it semantically correct?

<button>
  <div></div>
  <div></div>
</button>

Upvotes: 87

Views: 124420

Answers (6)

khollenbeck
khollenbeck

Reputation: 16157

<span> is valid, <div> is not valid. You can verify it at W3C.

http://validator.w3.org/#validate_by_input+with_options

Paste this in the direct input and then validate.

<!DOCTYPE html>

<button>
  <div></div>
  <div></div>
</button>

enter image description here

-- or --

<button>
  <span></span>
  <span></span>
</button>

enter image description here

Set the UTF8 encoding and select HTML5 when testing at W3C.

Upvotes: 43

Leevi Graham
Leevi Graham

Reputation: 674

2022: No it's not valid.

Buttons can only contain 'Phrasing Content' which does not include divs.

https://html.spec.whatwg.org/multipage/form-elements.html#the-button-element

Upvotes: 2

shennan
shennan

Reputation: 11656

I'm sure this is heretical, but if you wanted to validate you could always use <span> elements inside your button and style them like a <div>:

button span {

  display: block;

}
<button>
  <span>I'm a div</span>
  <span>I'm a div</span>
  <span>I'm a div</span>
</button>

This validated today. Whether it will validate in ten years is another story...

enter image description here

Upvotes: 28

Quentin
Quentin

Reputation: 943193

Div and span elements do not have any semantics. They are generic block and inline elements. The only question you need to ask yourself about semantics when you are using them is Is there an element with better semantics for this content?.

That said, it is incorrect to place a div inside a button for reasons unrelated to semantics. The specification says about the content model for buttons:

Phrasing content, but there must be no interactive content descendant.

… a span is phrasing content but a div is not.

Upvotes: 5

Ollie Williams
Ollie Williams

Reputation: 2504

Span seems legit.

enter image description here

(screenshot from https://validator.w3.org/)

Upvotes: 4

aecolley
aecolley

Reputation: 2011

The current HTML5 draft says it is incorrect.

http://www.w3.org/TR/2012/WD-html5-20120329/the-button-element.html#the-button-element says that a <button> must contain only Phrasing content. Phrasing content is defined as including <span> but not <div>.

Upvotes: 74

Related Questions