Making floated div shrink instead of dropping to new line

10,122

Solution 1

Have you tried experimenting with giving these two divs relative (such as a percentage) widths?

When you float without explicitly declaring a width, either fixed or relative, the dimensions will default to 'auto'. Auto will force the div to be the width of it's content. When the browser shrinks, the content will still force these boxes to that width, until it is forced to collapse by touching another element.

Using auto widths is not the best way to achieve fluidity in your layout. You'll need to specify some kind of relative dimension somewhere, otherwise this problem will be entirely unavoidable.

There are lots of resources out there which can help you achieve a more fluid layout (a lot of articles on www.alistapart.com discuss this in quite some depth).

Solution 2

CSS's display property, set it to inline and the div will behave like a span.

Share:
10,122
George Kendros
Author by

George Kendros

Updated on June 04, 2022

Comments

  • George Kendros
    George Kendros almost 2 years

    Is there any way I can force a floated div to shrink instead of going to a new line?

    I know I can set implicit widths on the divs but it's on a menu which might have variable amounts of items in it. I'm trying to do this while keeping the site's layout fluid if possible.

    #left {
      float: left;
      border: 1px solid #000;
    }
    
    #right {
      float: right;
      border: 1px solid #000;
    }
    <div id="left">
      <p>This div represents the logo</p>
    </div>
    <div id="right">
      <p>When the window's width is reduced and these divs touch I want this div to shrink instead of falling to the next line.
      </p>
    </div>

    Basically, I want #right to begin shrinking when the browser window is shrunk rather than having it drop a line first, then shrink when the window is further resized.

  • George Kendros
    George Kendros over 13 years
    It's still dropping to the next line. The line has a left floated element and right floated element on it (logo floated left, menu floated right)
  • cambraca
    cambraca over 13 years
    I can't think of a way of solving this without tables. I hate doing layout with tables.... I know it's Satan's way....
  • George Kendros
    George Kendros over 13 years
    I've that's the only route I'll go with fixed width before tables.
  • George Kendros
    George Kendros over 13 years
    That worked perfectly. I just figured what the min width I wanted to support was, subtracted the width of my logo div, then took the remaining width as a percentage (ie. 700px min width - 140px logo div = 560px or 80%)