0

Here is the code.

<div style="overflow:hidden; width:800px;">
  <div style="float:left; width:500px;">
    first text
  </div>
  <div style="float:left; width:300px;">
    second text
  </div>
</div>

As you see I use width:300px; so that the second div takes the rest of right space. What is another option to make it taking the whole right space? Setting width:100%; doesn't help as it jumps down. The reason I ask is every time I have to count 800-500=300 (px). Once 500px changed to 550px, I have to change 300px to 250px. I believe there is a better way to set the width. Thank you.

Andy
  • 14,427
  • 3
  • 52
  • 76
Haradzieniec
  • 9,086
  • 31
  • 117
  • 212

2 Answers2

1

I guess this markup will play better http://jsbin.com/apubay/1/edit

dmi3y
  • 3,482
  • 2
  • 21
  • 32
1

The general solution to this problem is to

  1. Float the first element and give it a fixed width.
  2. Display the second element as a block and give it a left margin equal to the first element's width.

Here's your code, modified to incorporate this pattern:

<div style="overflow: hidden;">
  <div style="float: left; width: 500px;">
    first text
  </div>
  <div style="display: block; margin-left: 500px;">
    second text
  </div>
</div>

I removed the 800px width from the container. You can add it back, but that kind of defeats the purpose of this solution. If you're going to set a fixed width of 800px, then stuff on the right will always be 300px. Here it is running on JS Bin:

JS Bin example

While this does achieve the effect of making the right element take up the remaining space (you will notice that it works by resizing the browser width), you will still need to change the width in two places to keep them in sync: (1) the width of the float, and (2) the left margin of the block. However, this is slightly easier than in your solution because there's no subtraction involved; you use the same value in both places. (Which also means it works for any unit: em, px, %.)

As a side note, I always recommend against using overflow: hidden for containing floats because months down the road you may get clipping effects and not remember that it's because you used overflow: hidden here. See an alternative solution at Which method of 'clearfix' is best?

Community
  • 1
  • 1
Chris Calo
  • 7,518
  • 7
  • 48
  • 64