EN
CSS - fit div width to content size
3 points
In this article, we would like to show you how to fit div width to content size in CSS.
Quick solution:
xxxxxxxxxx
1
.element {
2
width: fit-content;
3
width: fit-content;
4
width: fit-content;
5
}
Note: this solution was intoduced in Microsoft Edge web browser in 2020.
xxxxxxxxxx
1
<html>
2
<head>
3
<style>
4
5
div.container {
6
background: yellow;
7
}
8
9
div.content {
10
width: fit-content; /* <---- required (by older Chrome, Opera, Edge) */
11
width: fit-content; /* <---- required (by FF before 2022) */
12
width: fit-content; /* <---- required */
13
background: orange;
14
height: 300px;
15
}
16
17
</style>
18
</head>
19
<body>
20
<div class="container">
21
<div class="content">
22
1<br />
23
1 2<br />
24
1 2 3<br />
25
1 2 3 4<br />
26
1 2 3 4 5<br />
27
1 2 3 4<br />
28
1 2 3<br />
29
1 2<br />
30
1<br />
31
</div>
32
</div>
33
</body>
34
</html>
This solution is based on setting the overflow: hidden
on the container element to hide the overflow (disable scrolling) and setting the float: left
on the content
element that contains the text.
xxxxxxxxxx
1
<html>
2
<head>
3
<style>
4
5
div.container {
6
overflow: hidden; /* <---- required */
7
background: yellow;
8
}
9
10
div.content {
11
float: left; /* <---- required */
12
height: 300px;
13
background: orange;
14
}
15
16
</style>
17
</head>
18
<body>
19
<div class="container">
20
<div class="content">
21
1<br />
22
1 2<br />
23
1 2 3<br />
24
1 2 3 4<br />
25
1 2 3 4 5<br />
26
1 2 3 4<br />
27
1 2 3<br />
28
1 2<br />
29
1<br />
30
</div>
31
</div>
32
</body>
33
</html>
This solution required fixed height for container element.
xxxxxxxxxx
1
<html>
2
<head>
3
<style>
4
5
div.container {
6
position: relative; /* <---- required */
7
background: yellow;
8
height: 300px; /* <---- required */
9
}
10
11
div.content {
12
position: absolute; /* <---- required */
13
top: 0; /* <---- required */
14
bottom: 0; /* <---- required */
15
left: 0; /* <---- required */
16
background: orange;
17
max-width: 100%; /* <---- recommended */
18
}
19
20
</style>
21
</head>
22
<body>
23
<div class="container">
24
<div class="content">
25
1<br />
26
1 2<br />
27
1 2 3<br />
28
1 2 3 4<br />
29
1 2 3 4 5<br />
30
1 2 3 4<br />
31
1 2 3<br />
32
1 2<br />
33
1<br />
34
</div>
35
</div>
36
</body>
37
</html>