EN
CSS - sizing elements using min-content, max-content and fit-content
0 points
In this article, we would like to show you how to set the size of the elements using min-content
, max-content
and fit-content
.
Quick solution:
xxxxxxxxxx
1
<style> div { border: 2px dashed #28a745; margin-top: 10px; } </style>
2
3
<div style="width: min-content;">min-content</div>
4
<div style="width: max-content;">max-content</div>
5
<div style="width: fit-content;">fit-content</div>
6
<div style="width: auto;">auto</div>
Warning: The
min-content
andmax-content
were introduced to some major browsers around 2015-2020.
In this example, we create four classes to compare the different sizes of elements:
auto
- default layout which is full container size,min-content
- as small as possible to fit all the content, which is usually the largest piece of text,max-content
- as wide as possible to fit all the content (never shrinks down),fit-content
- as wide as possible to fit all the content but shrinks down until becomes the same size asmin-content
, then it stops shrinking. In short:max-content
at full size,min-content
at minimum size, otherwise fills the full container.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<style>
5
6
div { border: 2px dashed #28a745; margin: 10px; }
7
8
.min { width: min-content; }
9
10
.max { width: max-content; }
11
12
.fit { width: fit-content; }
13
14
.auto { width: auto; }
15
16
</style>
17
</head>
18
<body>
19
<div class="min">min-content</div>
20
<div class="max">max-content</div>
21
<div class="fit">fit-content</div>
22
<div class="auto">auto</div>
23
</body>
24
</html>