Fluid width div relative to sibling

2019-07-20 15:26发布

问题:

I have a suspicion this might need Flexbox (or would simply be a lot easier with), but maybe someone has an idea/workaround. I have a structure like this:

<section>
  <div>Some Text Here</div>
  <div></div>
</section>

Section is width: 100%. I want the first div (floating left) to stretch to different widths depending on text, and I want the second div to take whatever percentage is left of section. Each div will probably contain various other divs floating inside (and they in turn will use percentages for width). Is this possible?

Edit: Ok, I think the bigger problem is the fact that in the second div, I have a floating div with a % width, but it's parent is a width auto...so it won't work right will it? Codepen

回答1:

You can do this by specifying one DIV as left floating, and other as auto (so it used whatever space is left)

div:first-child { /* div on the left, width as per content */
    float: left;
    width: auto;
    background-color: #777;
}
div:last-child { /* div on the right, uses remaining width */
    background-color: #77f;
    width: auto;
}

Check this demo: http://jsfiddle.net/pQc3d/1/