How to Set a div to Its Content’s Width in CSS

How to Set a div to Its Content's Width in CSS

\
In HTML we use block elements to take up the full width of the 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.

\
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 an 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:

Full width div block element in CSS

\
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:

How fit-content works in CSS

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.

\
Also Published here

Leave a Reply

Your email address will not be published.