How to set the width of a <div> to fit its content

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.

Making a <div> fit no more than the width of 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;
}

Modern browsers only: setting the width of a <div> to no wider than its content

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.