CSS width, relative to the content size!


Generally, we do a fixed width (ex. pixels) or container-relative width (ex. percentage) for a block element like div. So, to size the width of an element based on its content, instead, hasn’t always been a usual or straightforward thing to do.

When we think of width that’s same as the content size, we think of inline elements. That’s why we almost always apply display: inline-block to a block element to shrink its width to match that of its content.

That, however, like I mentioned before, is not a very straightforward approach.

Other ways a block element might shrink its width to that of its content is when it’s floated or absolutely positioned, none of which are ideal methods to do what we want.

However, there’s one approach I believe has the least caveats and is the most direct, because it uses the paramount width.

CSS width has two values: max-content and min-content that cause an element to wrap around its content to the content’s inclined and minimum-needed width, respectively. These values are also available for height, but the browser support may not be as wide as for width.

There’s also the value, fit-content, but I wouldn’t recommend it if you want the width to be based on content size alone, because fit-content also considers the element’s container’s width along with the two criteria mentioned above while computing, and that might result in a width different from what you’d expected.

Below are three paragraphs with the second and last styled with max-content and min-content width.

width: max-content;
width: min-content;

You can add a fallback width value and browser specific prefixes if needed.

The Author

Web developer and writer. @rpsthecoder in Twitter.