Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I keep CSS floats in one line?

People also ask

How do you make an element stay in one line in CSS?

In your CSS section, use white-space: nowrap; .

How do I keep a div on one line?

You can force the content of the HTML <div> element stay on the same line by using a little CSS. Use the overflow property, as well as the white-space property set to “nowrap”.

How can we fix the floating problem in CSS?

To fix this problem, the footer can be cleared to ensure it stays beneath both floated columns. Clear has four valid values as well. Both is most commonly used, which clears floats coming from either direction. Left and Right can be used to only clear the float from one direction respectively.


Another option is, instead of floating, to set the white-space property nowrap to a parent div:

.parent {
     white-space: nowrap;
}

and reset the white-space and use an inline-block display so the divs stay on the same line but you can still give it a width.

.child {
    display:inline-block;
    width:300px;
    white-space: normal;
}

Here is a JSFiddle: https://jsfiddle.net/9g8ud31o/


Wrap your floating <div>s in a container <div> that uses this cross-browser min-width hack:

.minwidth { min-width:100px; width: auto !important; width: 100px; }

You may also need to set "overflow" but probably not.

This works because:

  • The !important declaration, combined with min-width cause everything to stay on the same line in IE7+
  • IE6 does not implement min-width, but it has a bug such that width: 100px overrides the !important declaration, causing the container width to be 100px.

Wrap your floaters in a div with a min-width greater than the combined width+margin of the floaters.

No hacks or HTML tables needed.


Solution 1:

display:table-cell (not widely supported)

Solution 2:

tables

(I hate hacks.)


Another option: Do not float your right column; just give it a left margin to move it beyond the float. You'll need a hack or two to fix IE6, but that's the basic idea.


Are you sure that floated block-level elements are the best solution to this problem?

Often with CSS difficulties in my experience it turns out that the reason I can't see a way of doing the thing I want is that I have got caught in a tunnel-vision with regard to my markup ( thinking "how can I make these elements do this?" ) rather than going back and looking at what exactly it is I need to achieve and maybe reworking my html slightly to facilitate that.