Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between a div and a span with display:block?

Tags:

html

css

Since a span can have display:block, when should I use that versus a div?

like image 658
Bill Gates Avatar asked Feb 24 '23 11:02

Bill Gates


2 Answers

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 divs as building blocks to define the layout and structure of your pages, while you use spans 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.

like image 55
BoltClock Avatar answered Feb 26 '23 09:02

BoltClock


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.

like image 35
Phil Avatar answered Feb 26 '23 08:02

Phil