97

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?

Gabriele Cirulli
  • 10,038
  • 25
  • 68
  • 97
  • Imagine how much simpler web dev would have been if we could do this! **I want `display: block-inline`!!** (that is to behave outwardly as a block but inwardly as an inline - the opposite of `inline-block`) – ADTC Aug 20 '16 at 08:20

5 Answers5

152

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 of

  • position: absolute

  • float: left/right

Robert Koritnik
  • 100,870
  • 50
  • 272
  • 398
26

You can use display: inline-block.

Matt Ball
  • 344,413
  • 96
  • 627
  • 693
  • 1
    I'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/

ALSO: http://dev.w3.org/csswg/css-box-3/

The_HTML_Man
  • 337
  • 1
  • 4
  • 12
  • Is this a troll answer? fit-content is not a valid property value for width or height. – Adam Jun 09 '15 at 18:34
  • 2
    It 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
  • Ok. I didn't know that. – The_HTML_Man Jul 06 '15 at 10:41
  • 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
5

you can also use

word-break: break-all;

when nothing seems working this works always ;)

Vinay Prajapati
  • 6,621
  • 6
  • 42
  • 80
meghaM
  • 89
  • 2
  • 7
4

it works well on Edge and Chrome:

  width: fit-content;
  height: fit-content;
HungNM2
  • 2,050
  • 23
  • 19