I'd like to clarify whether it's possible or not to make a div fit its size based on the content's size without having to make elements float or having to make their position absolute. Is it possible?
Asked
Active
Viewed 1.6e+01k times
5 Answers
157
CSS display
setting
It is of course possible - JSFiddle proof of concept where you can see all three possible solutions:
display: inline-block
- this is the one you're not aware ofposition: absolute
float: left/right

Robert Koritnik
- 103,639
- 52
- 277
- 404
-
2
-
Brilliant answer, thank you! My case: Use `display: inline-block;` *and* check/remove any other styles with `width` or `height` attributes affecting said attributes. – HoldOffHunger Oct 25 '21 at 00:49
26
You can use display: inline-block
.

Matt Ball
- 354,903
- 100
- 647
- 710
-
1I've updated my proof of concept JSFiddle that also shows the possibility with `position:absolute`. It is as well possible. Click the link in my answer. – Robert Koritnik May 05 '11 at 19:41
16
You can use:
width: -webkit-fit-content;
height: -webkit-fit-content;
width: -moz-fit-content;
height: -moz-fit-content;
EDIT: No. see http://red-team-design.com/horizontal-centering-using-css-fit-content-value/

The_HTML_Man
- 347
- 1
- 4
- 13
-
Is this a troll answer? fit-content is not a valid property value for width or height. – Adam Jun 09 '15 at 18:34
-
2It works but you must set the value to `-webkit-fit-content` or `-moz-fit-content` depending on browser you use. – warownia1 Jul 05 '15 at 12:19
-
-
As of 2021, Desktop browsers do support this without the webkit or moz prefixes, though apparently mobile broswers still require the prefixes. See https://caniuse.com/?search=fit-content – Patronics Feb 13 '21 at 06:24
4
you can also use
word-break: break-all;
when nothing seems working this works always ;)

Vinay Prajapati
- 7,199
- 9
- 45
- 86

meghaM
- 97
- 2
- 7