开发者

CSS Fluid Width inside div with fixed width

I have two divs inside a wrapper div of width 880px.

The first div contains an image which can be any width, I'd like the second width to scale with it i.e:

Div 1 = 300px Div 2 = 580px << this div scales to fit t开发者_StackOverflow社区he parent div.

Setting a width of 100% on the second div ignores the fixed width on the parent div.

Is this possible using only css or would I have to use javascript/jquery (jquery is already loaded so it's not too big a hassle)?

Thanks!


With CSS, you can only set dimensions that are directly relative to an element's content, one if its parents, the font size, or to the screen resolution, but not to the dimensions of its siblings.* This means that, in order for the second block to be the same width as the image, it should "inherit" the width from a parent, or have it set dynamically. For example:

#wrapper {
    float: left;
}

<div id="wrapper">
    <img id="image" src="…" alt="" />
    <div id="fits_img">…</div>
</div>

The float property on the #wrapper block makes its width fit its contents. The width of the #fits_img block is auto or 100% by default (since it's a div element), so its width will fit #wrapper and therefore be indirectly relative to the width of the image.

If you can't make the #wrapper element float, you could also mirror the width with jQuery like so:

$(document).ready(function()
{
    $('#fits_img').width($('#image').width());
});

* Note that there are also absolute units like 'cm', but they're relatively useless and rarely used.


copy/paste the code below and try changing the image's width and see what happens.

<div style="width:880px;">
    <img style="float:left;margin-right:10px;width:600px;height:80px;" src="whatever" />
    <div>a sadasd wqe sad asdqwe qweqwedasdasdqwe qwe qwe </div>
    <div style="clear:both;"></div>
</div>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜