100

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?

kettlepot
  • 10,574
  • 28
  • 71
  • 100
  • 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

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 of

  • position: absolute

  • float: left/right

Robert Koritnik
  • 103,639
  • 52
  • 277
  • 404
26

You can use display: inline-block.

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • 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
  • 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
  • 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

it works well on Edge and Chrome:

  width: fit-content;
  height: fit-content;
HungNM2
  • 3,101
  • 1
  • 30
  • 21
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