width: auto
is the default width for all elements, so the width will depend on display types (block, inline, etc.) to display respectively.
To provide a clearer understanding of width:auto
, I have included 2 code snippets below
Case 1: Utilizing div
with display: block
as the default setting
.container {
border: 2px solid #ccc;
padding: 10px;
width: 20em;
}
.item {
width: auto;
background-color: lightblue;
padding: 5px;
margin-bottom: 1em;
}
<div class="container">
<div class="item">Item</div>
<div class="item">Item with more text in it.</div>
<div class="item">Item with more text in it, hopefully it's lengthy enough for the demo</div>
</div>
Case 2: Utilizing span
with display: inline
as the default setting
.container {
border: 2px solid #ccc;
padding: 10px;
width: 20em;
}
.item {
width: auto;
background-color: lightblue;
padding: 5px;
margin-bottom: 1em;
}
<div class="container">
<span class="item">Item</span>
<span class="item">Item with more text in it.</span>
<span class="item">Item with more text in it, hopefully it's lengthy enough for the demo</span>
</div>
Essentially, display: block
will occupy the full width for element display, while display: inline
and display: inline-block
will align with the content width. The question arises: why not use display: inline
or display: inline-block
instead of width: fit-content
?
Let's observe the following code snippet for div
with width: fit-content
.container {
border: 2px solid #ccc;
padding: 10px;
width: 20em;
}
.item {
width: fit-content;
background-color: lightblue;
padding: 5px;
margin-bottom: 1em;
}
<div class="container">
<div class="item">Item</div>
<div class="item">Item with more text in it.</div>
<div class="item">Item with more text in it, hopefully it's lengthy enough for the demo</div>
</div>
You may notice that each line of content is displayed within an individual colored box, without encroaching upon other lines' space
In response to your query
Just wondering when should I use width: fit-content;?
Based on my personal experience, I tend to employ width: fit-content;
when aiming to display tags with fitting borders
https://i.sstatic.net/U7svk.png
Source
All my tags can be exhibited on separate lines, yet the borders will conform to the content, making width: fit-content
a preferred option for me.
P/s: In fact, there are alternate methods to attain this design such as utilizing a wrapper, employing flexbox, etc. Nevertheless, I lean towards width: fit-content
due to its simplicity. It is worth noting that this approach may not function optimally with Internet Explorer (refer to browser compatibility here)