2 Floating divs, Need the first one to auto-size according to parent div and 2nd floating div

我是研究僧i 提交于 2019-12-14 04:20:03

问题


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


回答1:


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.




回答2:


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/




回答3:


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>


来源:https://stackoverflow.com/questions/5645746/2-floating-divs-need-the-first-one-to-auto-size-according-to-parent-div-and-2nd

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!