问题
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.
回答1:
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
回答2:
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
回答3:
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;
}
回答4:
#parent {
display: table;
}
#first, #second, #third {
display: table-cell;
}
回答5:
Use the CSS style below :
#parent div{ display: inline-block; }
Working Fiddle
回答6:
With the CSS below you can achieve your goal :
#parent{
width:140px;
height:30px;
border:1px solid #CCC;
}
#first{
width:19px;
height : inherit;
display:inline;
border : 1px solid red;
}
#second{
width:19px;
height : inherit;
display:inline;
border : 1px solid green;
}
#third{
width:19px;
height : inherit;
display:inline;
border : 1px solid blue;
}
Fiddle
来源:https://stackoverflow.com/questions/24261376/horizontally-align-div-without-float