Hello, I Would like to know what's the actual difference between <span>
and
<div>
tags in HTML?
When we should prefer <span> and when <div>?
A <div>
is a block-level-element while a <span>
is an inline element.
Inline-Elements: These elements do not force new lines before or after its placement, and it only consumes as much space as necessary.
Block-Elements: New lines appear before and after the element with it consuming the full width available.
Use <span>
when you need to add small amount to HTML text in a block, without changing it's structure, use
<div>
when you want to create a new block of code inside HTML
div is a block level, meaning it’s on its own separate line. a span is inline, so it’s a child of another block level element.
<p><span>Text here</span> <span>Yes one more line</span></p>
I can have multiple spans inside a block-level. They all show up on the same line.
<div>Test</div><div>test2 line</div> //Output //Test //Test2 line
These divs text/code will be on separate lines.
basically the difference between <div>
and <span>
is, that
<div>
is displayed as a block (means it will add a new line to your code) and
<span>
is displayed inline(it will not any new line when text is written inside it). To illustrate the difference, look at these two HTML examples:
This is a line of text <div>with some text in a div</div>
and some text after.
This is a line of text <span>with some text in a span</span>
and some text after.
Here is how the div
example is displayed in a browser:
This is a line of text
with some text in a div
and some text after.
And here is how the span
example is displayed in the browser:
This is a line of text with some text in a span and some text after.
Here is the Visual Difference between inline element <span>
and block element
<div>
, considering below HTML
<p>This is a line of text <div>with some text in a div</div> <div>with some text in a div</div>
and some text after.</p>
<p>This is a line of text <span>with some text in a span</span>, <span> again with some text in a span</span>
and some text after.</p>
Output:
Hope it helps.
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly