SPAN vs DIV (inline-block)
Is there any reason to use a <div style="display:inline-block">
instead of a <span>
to layout a webpage?
Can I put content nested inside the span? What is valid and what isn't?
It's ok to use this to make a 3x2 table like layout?
<div>
<span> content1(divs,p, spans, etc) </span>
<span> content2(divs,p, spans, etc) </span>
<span> content3(divs,p, spans, etc) </span>
</div>
<div>
<span> content4(divs,p, spans, etc) </span>
<span> content5(divs,p, spans, etc) </span>
<span> content6(divs,p, spans, etc) </span>
</div>
Solution 1:
According to the HTML spec, <span>
is an inline element and <div>
is a block element. Now that can be changed using the display
CSS property but there is one issue: in terms of HTML validation, you can't put block elements inside inline elements so:
<p>...<div>foo</div>...</p>
is not strictly valid even if you change the <div>
to inline
or inline-block
.
So, if your element is inline
or inline-block
use a <span>
. If it's a block
level element, use a <div>
.
Solution 2:
If you want to have a valid xhtml document then you cannot put a div inside of a paragraph.
Also, a div with the property display: inline-block works differently than a span. A span is by default an inline element, you cannot set the width, height, and other properties associated with blocks. On the other hand, an element with the property inline-block will still "flow" with any surrounding text but you may set properties such as width, height, etc. A span with the property display:block will not flow in the same way as an inline-block element but will create a carriage return and have default margin.
Note that inline-block is not supported in all browsers. For instance in Firefox 2 and less you must use:
display: -moz-inline-stack;
which displays slightly different than an inline block element in FF3.
There is a great article here on creating cross browser inline-block elements.
Solution 3:
Inline-block is a halfway point between setting an element’s display to inline or to block. It keeps the element in the inline flow of the document like display:inline does, but you can manipulate the element’s box attributes (width, height and vertical margins) like you can with display:block.
We must not use block elements within inline elements. This is invalid and there is no reason to do such practices.
Solution 4:
I know this Q is old, but why not use all DIVs instead of the SPANs? Then everything plays all happy together.
Example:
<div>
<div> content1(divs,p, spans, etc) </div>
<div> content2(divs,p, spans, etc) </div>
<div> content3(divs,p, spans, etc) </div>
</div>
<div>
<div> content4(divs,p, spans, etc) </div>
<div> content5(divs,p, spans, etc) </div>
<div> content6(divs,p, spans, etc) </div>
</div>