Use the display
CSS property to set the width of a <div>
element to fit its content.
By default, an HTML <div>
element has a width of 100%, forcing it to take on the maximum allowable width within its parent container.
However, sometimes you may find the need to have a <div>
that is set to be no wider than its content.
In this example, you have a <div>
with a class named make-me-fit
containing the sentence Hello, world!
, and you’d like the width of the <div>
to fit that sentence:
<html>
<body>
<div class="container">
<div class="make-me-fit">
<p>Hello, world!</p>
</div>
</div>
</body>
</html>
There are a couple of ways to do this using the display
CSS property. One involves the parent container, while the other involves the <div>
element for which you’d like to change the width.
The first method is to set the display
property of the parent container to flex
:
.container {
display: flex;
}
The second method is to set the display
property of make-me-fit
to inline-block
:
.make-me-fit {
display: inline-block;
}
Either of the above methods will ensure that the <div>
element make-me-fit
is no wider than the width of its content. Choose the method that works best on your page without disrupting its layout.
In modern browsers, you can set the width
CSS property to fit-content
to perform the same task:
.make-me-fit {
width: fit-content;
}
In particular, Internet Explorer does not support this modern method. So if you need to support Internet Explorer users, use either of the first two methods instead.
That’s all there is to it! Your <div>
is now set to the width of its content, and no wider.
You may also like:
Love our articles? HostM offers professional and helpful web hosting services with unlimited features and renewal rates that actually match our advertised rates.
From $2.48/mo
We can help you move your
email and websites as desired.