Issue
From what I know, setting width: fit-content; to the element simply means that the element width will take up the available space but never less than the min-content within the element. But, isn't the default width: auto; behaves the same as well?
Just wondering when should I use width: fit-content;?
Solution
width: auto
is the default width for all elements, so the width will rely on display types (block, inline, etc.) to show respectively.
To make you understand better about width:auto
, I put 2 code snippets below
Case 1: Using div
with display: block
as default
.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: Using span
with display: inline
as default
.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>
So basically, display: block
will take up the whole width for element display, and display: inline
and display: inline-block
will align with content width. The next question is why we don't use display: inline
or display: inline-block
instead of width: fit-content
?
Let's check the below 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 can see that each content line has been shown with an individual color box, and it does not consume other lines' space
As your question
Just wondering when should I use width: fit-content;?
In my personal experience, I've been usually using width: fit-content;
when I want to show tags with fit borders
All my tags can be shown in different lines but borders will be displayed respectively by content, so width: fit-content
is a good choice for me.
P/s: Actually, we can achieve this design in other ways like using a wrapper, using flexbox, etc. But I personally like width: fit-content
because it's simpler. One thing I'd like to note is that this approach does not work well with Internet Explorer (check browser compatibility here)
Answered By - Nick Vu
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.