Hello,
What is the difference between the default <div>
tag and the default <span>
tag with "display: block".
Thanks,
Gavriel
Hello,
What is the difference between the default <div>
tag and the default <span>
tag with "display: block".
Thanks,
Gavriel
You can found here a definition of the display CSS property.
As stated in this link, the block
value indicates that:
The element will generate a block box (a line break before and after the element)
By default, the value of this property is inline
which is defined as:
The element will generate an inline box (no line break before or after the element). This is default
A span
element with a style of display: block
essentially becomes a div
element. It makes the element's width stretch to fill whatever container it is in.
<span>
defaults to display:inline;
whereas <div>
defaults to display:block;
That is the only difference between the two, so if you specify display:block;
for a span, it will act the way a div normally acts, and vice-versa.
display:inline;
makes the element work flow in the text body, whereas display:block;
makes it act as a block (oddly enough!).
(note there is also a less well known variant display:inline-block;
, which is a half-way house between the two. <img>
tags default to this setting)
<span>
is an inline element by default. That is the <span>
element does not generate any breaks before and sfter ir. Also, there are some properties that cannot be applied to inline elements, like height.
<div>
is a block level element by default. That is a <div>
generates breaks before and after it when rendered.
You can change a block level element into inline and vice versa via the display
property.
See this for an explanation of all display
properties.
div is block element and span is inline element. There are two things that deserve attention.
Only if you care about validity and semantics of HTML elements, there is a difference. Otherwise they are identical. Let me explain:
div
and span
are both defined as generic containers without deeper meaning in terms of HTML. The one defaulting to block display, the other to inline, since these are the two major groups where almost any other element falls into
Certain elements must be contained by an element that is defined as a block. This has nothing to do with the CSS display
property, but with the semantics of HTML: The general idea is based on inlines being always children of blocks (which is, if you think of it, a good idea in general)
Now, if you have a span
with display:block
, it will, in the sense of CSS, act exactly like a div
. However, from the semantic point of view, if you embed block level elements inside the span
, you are creating invalid HTML, because you nest a block in an inline element