Ming
Ming

Reputation: 784

Stretch / shrink parent div to fit content's width

I am trying trying to make a div's width as wide as it's content. Here's a fidle to show what I mean:

http://jsfiddle.net/djxpU/

I want the blue area to be as wide as the white. I tried float:left and display:inline-block, however they won't work with position:absolute;. Any workarounds?

Upvotes: 0

Views: 8613

Answers (3)

Marconius
Marconius

Reputation: 713

Block-level elements actually do this naturally. The problem you have is, absolute positioned elements are taken out of the normal flow, so the block can't wrap around your white boxes.

Is there a reason you need them positioned absolute?

EDIT: If you just wanted the white boxes to be centered, here you go: http://jsfiddle.net/Marconius/djxpU/1/

Code (because I have to): margin: 0 auto;

Upvotes: 1

Jacob VanScoy
Jacob VanScoy

Reputation: 1168

By default a div will be the width of its parent and will display as block. Here is an example of the divs filling the available space while still maintaining the left margin.

Apply this to your 'X' divs: { margin-left: 120px; height: 40px; background-color: white;}

http://jsfiddle.net/yz3Dk/

Upvotes: 0

Josh Rutherford
Josh Rutherford

Reputation: 2723

If you want the white area to fit the blue parent, you'd set the width of the white to 100% #X{ width:100%; }

Upvotes: 1

Related Questions