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>
containing two items:
<html>
<body>
<div class="my-div">
<div class="item-1"></div>
<div class="item-2"></div>
</div>
</body>
</html>
Here, the display
CSS property is used to ensure that the <div>
element is no wider than the width of its content:
.my-div {
display: inline-block;
}
In modern browsers, the width
CSS property in conjunction with the fit-content
value can be used to perform the same task:
.my-div {
width: fit-content;
}
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.
| Click here to get started. It’s fast, easy and secure. | Sign Up Now |
From $3.95/mo
Initial Price = Renewal Price
Available for a limited time.
We can help you move your
email and websites as desired.
|