Since a span can have display:block, when should I use that versus a div?
The technical difference is that div
is a block-level element while span
is an inline element meant for use with text. Although spans can display and behave like block elements, by nature they are still considered inline elements, and so cannot contain block elements as valid HTML.
div
can contain span
, but span
cannot validly contain div
even if you apply display: block
or display: inline
to all of them.
As others mention, you use div
s as building blocks to define the layout and structure of your pages, while you use span
s for wrapping parts of your text, for styling or structural purposes.
Some links to the HTML spec:
div
– generic flow container
Permitted contents
Zero or more style elements, followed by flow content.
... where flow content consists of phrasing content and many block-level elements (flow elements).
span
– generic span
Permitted contents
Phrasing content.
... where phrasing content consists of text and inline elements.
Theoretically, you could style a span to do the same thing as a div. But than again, you could surround all your text in h1's
and change the styles to look normal. Check out @BoltClock answer as he explains that you can't have a div inside a span and maintain code validity.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With