To div
is a block type element and by default it occupies 100% of the container width. Span is a line element, and by default it only occupies its own size.
So in the case of div
In case you wanted her to occupy only her own size you can leave her with display:inline-block
, so it gets "hybridized" and gets characteristics of an element block
and inline
. Another option is to use min-content
or max-content
in the width
of that div
, here are more details What are and how the width values max-content and min-content work?
See the example below to better understand.
div,
span {
border: 1px solid #000;
}
div.ib {
display: inline-block;
}
div.min {
width: min-content;
}
div.max {
width: max-content;
}
<div>DIV padrão - Lorem ipsum.</div>
<div class="ib">DIV inline-block - Lorem ipsum.</div>
<div class="min">DIV min-content - Lorem ipsum.</div>
<div class="max">DIV max-content - Lorem ipsum.</div>
<span>SPAN - Lorem ipsum.</span>
Another detail
An element, same as block, when with position:absolute
, or fixed
also takes up only the size of the element itself, as it changes its scope in the content stream of the page. The same happens when using float:right
or left
in div
.
div.pos {
border: 1px solid #000;
position: absolute;
}
div.float {
border: 1px solid #000;
float: left;
margin-top: 30px;
}
<div class="pos">DIV position:absolute - Lorem ipsum.</div>
<div class="float">DIV float - Lorem ipsum.</div>