Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Horizontally align div without float [duplicate]

I want to know if there exists an elegant way to horizontally align 3 divs without using float css property.

HTML:

<div id="parent">  
  <div id="first">Left</div>  
  <div id="second">Middle</div>  
  <div id="third">Right</div>
</div>

I ask this question because the parent div has not float property and adding float to children cause problems on page resizing.

like image 960
Azincourt Avatar asked Jun 17 '14 10:06

Azincourt


People also ask

How do you horizontally align divisions?

To center a div horizontally on a page, simply set the width of the element and the margin property to auto. That way, the div will take up whatever width is specified in the CSS and the browser will ensure the remaining space is split equally between the two margins.

How do I keep divs side by side?

(You'll see why in a bit.) 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.


4 Answers

You can use display:inline-block or display:table-cell with the inner content.

  • Flex layout (See also T J's answer):
#parent{ display:flex; justify-content: space-between; }

JSFiddle

  • Table layout:
#parent{ display:table; width:100%; }
#parent div{ display:table-cell; }
#first{ text-align:left; }
#second{ text-align:center; }
#third{ text-align:right; }

JSFiddle

  • Inline-block layout :
#parent{ width:100%; white-space:nowrap; }
#parent div{ display:inline-block; width:33.3%;}
#first{ text-align:left; }
#second{ text-align:center; }
#third{ text-align:right; }

JSFiddle

like image 131
potashin Avatar answered Oct 14 '22 14:10

potashin


Adding to notulysses's answer, If ancient browser support is not an issue, you can use css3 Flexible_boxes.

By applying display:flex the child divs will be aligned horizontally (by default)

#parent{
 display:flex;
 justify-content:space-around;
}

more about flexbox @ CSSTricks

This will avoid the white space issue with inline-block elements

JSfiddle

like image 30
T J Avatar answered Oct 14 '22 15:10

T J


Instead of finding a workaround for floating, you could also use the following fix for your "resizing problems" (at least what I think it is caused by):

After using floats, you should always clear your floats. You can do this by adding an extra <div> with a class.

<div id="parent">  
  <div id="first">Left</div>  
  <div id="second">Middle</div>  
  <div id="third">Right</div>
  <div class="clear"></div>
</div>

In CSS:

.clear{
  clear: both;
}
like image 22
Praxis Ashelin Avatar answered Oct 14 '22 15:10

Praxis Ashelin


#parent { 
    display: table; 
}

#first, #second, #third { 
    display: table-cell; 
}
like image 29
Ankit Agrawal Avatar answered Oct 14 '22 14:10

Ankit Agrawal