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

Written by smpnjn | Published 2022/07/04
Tech Story Tags: css | css3 | javascript | webdevelopment | web-development | web-design | html | software-engineering

TLDRBoth 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 an element like a div take up no more space than its content, we can use the fit-content keyword.via the TL;DR App

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:

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:

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


Written by smpnjn | Product, Engineering, Web
Published by HackerNoon on 2022/07/04