2 Floating divs, Need the first one to auto-size a

2019-07-31 18:27发布

This is how my code may go:-

<div id="parent" style="width:49%">
  <div id="left" style="float:left;clear:both;width:auto">BLAH!BLAH!Content goes here</div>
  <div id="right" style="float:left;clear:both:width:250px">Content again goes here!</div>
</div>

So basically I want left to auto-size based on the the width of "right" but must stay in limits of the "parent" container!

I looked up many places but didn't find sensible answers! Hope this website can help me! :D

Thanks in advance

3条回答
混吃等死
2楼-- · 2019-07-31 18:43

Float #right to the right, and do not float #left but give it a margin-right which is equal to the width of #right. If you float #left, it will take up the size of its contents, but if you don't float it, it will take up the possible maximum width it can. And you just lower this maximum width by setting a margin.

Demo

Notice that in the markup I changed the order of divs:

  <div id="right">Content again goes here!</div>
  <div id="left">BLAH!BLAH!Content goes here</div>

And the important part of the CSS:

#parent { 
    width: /*whatever you need*/; 
    overflow: hidden; /* to let it take up the height of floated elements */
}

#left {
    margin-right: 250px;
}

#right {
    float: right;
    width: 250px;
}

Tested in FF4, Chrome, IE8.

查看更多
贼婆χ
3楼-- · 2019-07-31 18:50

Pure CSS Answer:

<div id="parent" style="width:49%">
  <div id="left" style="float:left;clear:both;width:calc(100% - 250px)">BLAH!BLAH!Content goes here</div>
  <div id="right" style="float:left;clear:both:width:250px">Content again goes here!</div>
</div>
查看更多
干净又极端
4楼-- · 2019-07-31 18:53

You need to use JavaScript to detect remaining space. This cannot be done with CSS alone. With jQuery you can do

var parentw = $('#parent').width();
var rightw = $('#right').width();
$('#left').width(parentw - rightw);

Check working example http://jsfiddle.net/NP4vb/

查看更多
登录 后发表回答