Div Size Automatically size of content

Css

Css Problem Overview


I am trying to make a h2 header for sidebar widgets but I want the width of the div class to be whatever width the content becomes. It seems I can't just set a width because those headlines with longer content then shorter content makes it break.

How can I simply make width stretch/change depending on the length of content there is? Any help would be greatly appreciated.

Css Solutions


Solution 1 - Css

As far as I know, display: inline-block is what you probably need. That will make it seem like it's sort of inline but still allow you to use things like margins and such.

Solution 2 - Css

If you are coming here, there is high chance width: min-content or width: max-content can fix your problem. This can force an element to use the smallest or largest space the browser could choose…

This is the modern solution. Here is a small tutorial for that.

There is also fit-content, which often works like min-content, but is more flexible. (But also has worse browser support.)

This is a quite new feature and some browsers do not support it yet, but browser support is growing. See the current browser status here.

Solution 3 - Css

If display: inline; isn't working, try out display: inline-block;. :)

Solution 4 - Css

The easiest is:

width: fit-content;

Solution 5 - Css

I faced the same issue and I resolved it by using: max-width: fit-content;

Solution 6 - Css

The best way to do this is to set display: inline;. Note, however, that in inline display, you lose access to some layout properties, such as manual height and vertical margins, but this doesn't appear to be a problem for your page.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionZach SmithView Question on Stackoverflow
Solution 1 - CssSvishView Answer on Stackoverflow
Solution 2 - CssrugkView Answer on Stackoverflow
Solution 3 - CssKyleView Answer on Stackoverflow
Solution 4 - CssfruitloafView Answer on Stackoverflow
Solution 5 - Csseliram9View Answer on Stackoverflow
Solution 6 - CssDelan AzabaniView Answer on Stackoverflow