Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent floated divs from wrapping to new line

I've seen this asked a few times on SO, and the same answers are given which do not work on my end in Chrome or Firefox.

I want to make a set of left-floated divs run off, horizontally a parent div with a horizontal scroll bar.

I'm able to demonstrate what I want to do with this crappy inline css here: http://jsfiddle.net/ajkochanowicz/tSpLx/3/

However, from the answers given on SO*, this should work but does not on my end. http://jsfiddle.net/ajkochanowicz/tSpLx/2/

Is there a way to do this without defining absolute positioning for each item?

*e.g. Prevent floated divs from wrapping to next line

like image 759
Adam Grant Avatar asked Mar 12 '12 17:03

Adam Grant


People also ask

How do I keep my div from wrapping to the next line?

Inline elements behave in much the same way as text does. If you want to prevent them from wrapping, either remove the white space you have used for formatting, or add white-space:nowrap; to the rule for .

How do you keep a floated element from wrapping?

Use "overflow: hidden" to avoid floating elements from wrapping a container's text. Unfortunately, any content of the content 's text will wrap underneath it: ![

How do I make two divs display on the same line?

You can use display: inline to put the two div elements inline. Explanation: div elements are block elements, so their display style is usually display: block . You can wrap both the div elements in a span tag. Explanation: span works the same way as the div , to organize and group elements.


1 Answers

This should be all you need.

    .float-wrap {
      /* 816 = <number of floats> * (<float width> + 2 * <float border width>) */
      width: 816px;
      border: 1px solid;
      /* causes .float-wrap's height to match its child divs */
      overflow: auto;
    }
    .left-floater {
      width: 100px;
      height: 100px;
      border: 1px solid;
      float: left;
    }
    .outer {
      overflow-x: scroll;
    }
<div class="outer">
  <div class="float-wrap">
    <div class="left-floater">
      One
    </div>
    <div class="left-floater">
      Two
    </div>
    <div class="left-floater">
      Three
    </div>
    <div class="left-floater">
      I should be to the <s>left</s> right of "Three"
    </div>
    <div class="left-floater">
      I float.
    </div>
    <div class="left-floater">
      I float.
    </div>
    <div class="left-floater">
      I float.
    </div>
    <div class="left-floater">
      I float.
    </div>
  </div>
</div>

.float-wrap keeps space open for the divs. Because it will always maintain at least enough space to keep them side-by-side, they'll never need to wrap. .outer provides a scroll bar, and sizes to the width of the window.

like image 118
AaronSieb Avatar answered Oct 16 '22 00:10

AaronSieb