当前位置: 动力学知识库 > 问答 > 编程问答 >

css - align divs horrizontaly - the first one take all the horizontal available space

问题描述:

I have 2 divs which I need to arrange horizontally, I know the width of the second one and I need the first one to take all the remaining free space. can anyone help me and tell me the css in order to achieve that?

网友答案:

You could do something like this:

<div style="width:500px;">
    <div style="width:100px;float:right;background-color:cyan;">bar</div>
    <div style="margin-right:100px;background-color:magenta">foo</div>
</div>

bar floats in the right 100px, on top of foo's margin. foo takes the other 400px.

网友答案:

Try to do something like that:

<div style="width:200px; float:left;"></div>
<div style="width:auto;"></div>
网友答案:

Try to set the width of the second container to your known value and the first one's to width:100%;

网友答案:

You can use percentages, which is handy when you don't care about exact width. If you need an exact width, use javascript to get the offsetwidth of the div you KNOW, and floating both divs. Then, set the width of the other div accordingly. What I would caution against is setting the other div's value in pixels- if the user resizes the window you have to account for it which is more work. If you don't need it to be perfectly exact, set the other div as a percentage, which will automatically handle window resizing. Other issues crop up around it but basically thats one way of achieving it.

网友答案:

What you're asking for is a little tricky. But this should work...

http://jsfiddle.net/2hseV/2/

What this does is use div positioning. This should be cross-browser compatible. The reason I'm doing things this way is that there is no easy way to say "have two sibling divs, one of which consumes all available space" without pushing the second div off to the right.

For example, if you try using a percentage you'll either push the div to the right or come up short:

<div style="width: 200px; height: 100px;">
  <div style="width: 100%; height: 100%; float: left;"></div>
  <div style="width: 90px; height: 100%; float: left;"></div>
  <div style="clear: both;"></div>
</div>

So instead, I'm suggesting that you overlap the second div onto the first one using absolute positiong, like this:

<div style="width: 200px; height: 100px; position: relative;">
  <div style="width: 100%; height: 100%; float: left; position: relative;"><!-- Content of first div here --></div>
  <div style="width: 90px; height: 100%; float: left; position: absolute; right: 0; top: 0;"><!-- Content of second div here --></div>
</div>

The one thing you have to keep in mind here is that the content of your first div will go under the second div if it becomes too wide - so you may need to restrict the width!

分享给朋友:
您可能感兴趣的文章:
随机阅读: