Why isn't <body> expanding to fit its contents?

if you set display:table; to body or html, it will allow to grow its width over the 100% of viewport. it will just expand like a table does :)

html {display:table;width:100%; /* need to set a width to 100%, wich means here a min-width since it is displayed with the same specifities thas has a table , it shrinks and expand according to its content */}

http://jsfiddle.net/6REkj/1/

other options :

  • display:inline-block;min-width:100%; on body : http://jsfiddle.net/6REkj/3/
  • position:absolute;min-width:100%; on html : http://jsfiddle.net/6REkj/4/

Edit nowdays, min-width:max-content would do . http://jsfiddle.net/bj4wk6m2/


CSS isn't broken, the behaviour you are seeing is by design.

Some quotes from the link above:

The following constraints must hold among the used values of the other properties:

'margin-left' + 'border-left-width' + 'padding-left' + 'width' + 'padding-right' + 'border-right-width' + 'margin-right' = width of containing block

..

If 'width' is set to 'auto', any other 'auto' values become '0' and 'width' follows from the resulting equality.

From this I understand that block level elements have a default width of 100% of their containing block if all of the other properties are not set.

<body> is by default a block level element.

You could set float: left; or display: inline-block on body and it will grow with its content.

Here's a jsFiddle.

To answer question 2 (to get the result of the accepted answer without resorting to setting display: table on an element which isn't a table), you could do it this way:

CSS:

html {
    padding: 10px;
}
html, body {
    margin: 0px;
}
body {
    border: 2px solid blue;
    display: inline-block;
    min-width: 100%;
    box-sizing: border-box;
}
table, p {
    background-color: cyan;
}

Here's a jsFiddle.


It's very strange that the simplest solution hasn't been mentioned:

body {
  width: fit-content;
  min-width: 100%; /* because the content might only be a few words */
  box-sizing: border-box; /* because 100% + padding > 100% */
}

Unfortunately that doesn't work everywhere and it still requires prefixing. In Chrome (with Blink these days) that would be: -webkit-fit-content (-webkit- in Blink, weird).

Tags:

Css