Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly float two columns side by side with css

This is one of those things I learned a long time ago and never thought much about if I was actually doing it the right way.

Let's say we have a structure like so:

<div id="wrapper">
  <div id="sideBar"></div>
  <div id="mainContent"></div>
</div>

Let's also say that wrapper has a width of 600px.

Should I float sideBar left, and mainContent right, or should I float them both left?

Additionally, if I set a fixed width for sideBar how can I make mainContent fill up the rest of the space similar to how a table works? If I set mainContent to display:inline-block and width:100% it moves down onto the next line :/

Note: In my specific scenario I do not want to use a table.

like image 829
The Muffin Man Avatar asked Apr 08 '11 02:04

The Muffin Man


People also ask

How do you float elements side by side?

Use CSS property to set the height and width of div and use display property to place div in side-by-side format. float:left; This property is used for those elements(div) that will float on left side. float:right; This property is used for those elements(div) that will float on right side.

How do I put elements side by side in CSS?

The most common way to place two divs side by side is by using inline-block css property. The inline-block property on the parent placed the two divs side by side and as this is inline-block the text-align feature worked here just like an inline element does.

How do I align two divs side by side?

To position the divs side by side, we are using the float property to float each . float-child element to the left. Since they are both floating to the left, they will display side by side if there's enough space for both to fit.


2 Answers

use display:flex for two div floats side-by-side

#wrapper {
    width: 600px;
    display: flex;
}
#sideBar {
    display: inline-flex;
    width: 25%;
}
#mainContent {
    width: 75%;
    flex: 1;
}
like image 170
Mike Tavish Avatar answered Sep 25 '22 00:09

Mike Tavish


You display:block along with float:left to float divs next to each other.

Check working example at http://jsfiddle.net/FhL4u/2/

To make mainContent fill up rest of the space if only the first div width is known then use percentages on both sideBar and mainContent ex: 20% 80% instead of using fixed width. otherwise you will need a JavaScript solution to achieve a cross browser compatibility.

Check jQuery solution at http://jsfiddle.net/FhL4u/3/

like image 21
Hussein Avatar answered Sep 23 '22 00:09

Hussein