-1
<body>
<div id="div01"></div>
<div id="div02"></div>
<img id="img01" src="...">
</body>

css

body{
width:90%;
margin:0 auto;
background-color:gold;
}

div01, div02 and img01 are 100px, 200px and 300px width, respectively.

The width of body's children is dynamically changed.

How can I set elastic width of the body, according to largest child ? Without using javascript, just pure css.

For example, if img01 becomes 250px body should be 250px. If div01 becomes 400px body should be 400px. And still staying horizontally centered.

Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
qadenza
  • 9,025
  • 18
  • 73
  • 126

2 Answers2

1

Your best bet would be:

body {
    width: auto;
}

This tells your browser to calculate your body's size accordingly to the size of its inner elements. You can see more documentation here: http://www.w3schools.com/cssref/pr_dim_width.asp

Valentin Mercier
  • 5,256
  • 3
  • 26
  • 50
1

I'd recommend against using the <body> as a variable width element - the standard method is a wrapper <div>. For example:

<body>
  <div id="wrap">
    <img src="http://placehold.it/300x200" />
    <img src="http://placehold.it/200x300" />
    <img src="http://placehold.it/400x100" />
    [ other variable width content ]
  </div>
</body>

and the CSS

body{
    text-align:center;
}
#wrap{
    display:inline-block;
}

http://jsfiddle.net/daCrosby/Teq6N/

DACrosby
  • 11,116
  • 3
  • 39
  • 51