Andrew Cheong
Andrew Cheong

Reputation: 30273

Constraining a <div>'s width to a sibling <div>'s width

I have some dynamically generated charts that each get placed in a container, floated left:

<div class="container">
    <div class="chart"> ... </div>
</div>
<div class="container">
    <div class="chart"> ... </div>
</div>
<div class="container">
    <div class="chart"> ... </div>
</div>

The above, for example, produces

Sample 1

I wanted to add captions beneath each chart, so I added sibling <div>s, like this:

<div class="container">
    <div class="chart"> ... </div>
    <div class="caption"> ... </div>
</div>
<div class="container">
    <div class="chart"> ... </div>
    <div class="caption"> ... </div>
</div>
<div class="container">
    <div class="chart"> ... </div>
    <div class="caption"> ... </div>
</div>

This didn't work because the parent's width, not having been specified, would grow with the caption text:

Sample 2

So, how can I constrain the caption <div> width to the chart <div> width?

The chart is generated by an external jQuery library, and although I could use jQuery to obtain the generated chart's width and set the caption <div>'s width to that value, I'd prefer a CSS-only solution. I'd also like to avoid injecting the caption <div> into the chart <div> (though, I'm not sure how that'd help anyway).

The result I'm looking for looks more like the following (example faked via forced linebreaks):

Sample 3

Thanks in advance for any advice.

Upvotes: 1

Views: 951

Answers (1)

haejeong87
haejeong87

Reputation: 957

you can do this by applying absolute position without any positional attributes (top, bottom, left, right)

Tested only on Chrome, FF, and IE10

.container {
    position: relative;
}
.caption {
    position: absolute;
}

http://jsfiddle.net/YzQcs/

Upvotes: 1

Related Questions