Set a div or block to its content's width in CSS
📣 Sponsor
In HTML we use block
elements to take up the full with of a page. These differ in properties from inline
elements, which are typically found within text flow.
Learn about the Box Model
Both inline
and block
elements are important components of CSS. To learn about the box model in CSS, click here.
When we create a new div
or other block
element, it takes up the full width of the page - but what if we want a div
or any other block
DOM element to only be the width of its contents and no more? To make an HTML block
element like a div take up no more space than its content, we can use the fit-content
keyword.
For example, here is a div
containing some dummy text with a background. Even though the content is short, the div
takes up the whole page:
Hello There
If we want this div to now only take up the same width as its content, we can add fit-content
:
div {
width: fit-content;
}
Now our div
is much smaller, and only as large as the content it contains:
Hello There
Conclusion and Support
Support for fit-content
is quite broad, but it will not work in Internet Explorer. Similarly, some browsers will only support it for width
, and not for other properties. In any case, you can be pretty confident using this property with width
, but there may be some caveats when applying it to other CSS properties. A full list of support can be found on caniuse.com.
If you want to learn more about CSS, click here.