Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center two divs floating next to one another

I have written the following HTML trying to center two div's next to each other.

<div id='wrapper' style='text-align:center;'>
    <div style='float:left;'>
        Lorem ipsum<br />
        dolor sit amet
    </div>
    <div style='float:left;'>
    Lorem ipsum<br />
    dolor sit amet
    </div>
</div>

However, the code I've written results in the two div's floating all the way to the left. What this does do correctly is float the two div's side by side.

What do I need to change to center the two div's side by side?

like image 625
Vivian River Avatar asked Mar 18 '11 20:03

Vivian River


People also ask

How do I center two divs side by side?

Simply put, if you have a div, and the elements inside are set to “display:inline-block” then you can just use “text-align:center” to center them inside.

How do I center a div with float?

First, remove the float attribute on the inner div s. Then, put text-align: center on the main outer div . And for the inner div s, use display: inline-block .

How do I align two divs side by side on Fitbit Flex?

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.

How do I align two divs on the same line?

To display multiple div tags in the same line, we can use the float property in CSS styles. The float property takes left, right,none(default value) and inherit as values. The value left indicates the div tag will be made to float on the left and right to float the div tag to the right.


3 Answers

Instead of using float: left, use display: inline-block:

<div id='wrapper' style='text-align: center;'>     <div style='display: inline-block; vertical-align: top;'>         Lorem ipsum<br />         dolor sit amet,<br />         consectetur adipisicing elit     </div>     <div style='display: inline-block; vertical-align: top;'>         Lorem ipsum<br />         dolor sit amet     </div> </div> 

The top of each inner div is kept aligned by using vertical-align: top.

Example: http://jsfiddle.net/hCV8f/1/

like image 184
jason_ruz Avatar answered Sep 25 '22 09:09

jason_ruz


You will have to automatically set the margin and probably a specific width to your wrapper div

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

In your CSS:

#wrapper {     width: 70%;     margin: 0 auto; } 
like image 29
Daff Avatar answered Sep 24 '22 09:09

Daff


Try this:

<div id='wrapper' style='text-align:center;'>
    <div style='float:left;background-color:red;width:50%'>
        Lorem ipsum<br />dolor sit amet
    </div>
    <div style='float:right;background-color:blue;width:50%'>
         Lorem ipsum<br />dolor sit amet
    </div>
</div>

http://jsfiddle.net/JDAyt/

like image 24
Steve Wellens Avatar answered Sep 22 '22 09:09

Steve Wellens