水平div对齐

时间:2014-04-24 15:46:38

标签: html css

美好的一天。

我在输入样式中使用给定的宽度创建了一个有点百分比的栏。我希望给定的div彼此水平对齐但不重叠,只是跟随彼此。我怎么可能这样做?

这是一个简单的代码

http://jsfiddle.net/XU3JM

<html>
<head>
<style>
#one{
    background: green;
    height: 20px;

}
#two{
    background: blue;
    height:20px;
}
#three{
    background: gray;
    height:20px;
}
</style>
<body>
        <div id="one" style="width:20px;"></div>
        <div id="two" style="width:30px;"></div>
        <div id="three" style="width:40px;"></div>  
</body>
</head>
</html>

宽度没有恒定值,所以我不能只用左边的边距。我一直在调整这个后备代码。没有这样的运气。提前致谢。

4 个答案:

答案 0 :(得分:1)

添加此css:

#one, #two, #three {display:inline-block;}

http://jsfiddle.net/h35N6/

或者这个css:

#one, #two, #three {float:left;}

http://jsfiddle.net/h35N6/1/

答案 1 :(得分:1)

这可能会有所帮助

#one,#two,#three{
    height: 20px;
    padding: 0;
    display: inline-block;
    *display: inline;
    zoom: 1;
}

它还支持旧的IE版本

<强> http://jsfiddle.net/XU3JM/2/

答案 2 :(得分:0)

使用display:inline-block;将每个div作为中心对齐,并将它们包装在一个带有text-align:center的新容器中;适用于它。

答案 3 :(得分:0)

#first{
    background: green;
    height: 20px;
    margin-left: 2px;
    color: white;
    float: left;

}
#second{
    background: blue;
    height:20px;
    margin-left: 2px;
    color: white;
    float: left;
}
#third{
    background: gray;
    height:20px;
    margin-left: 2px;
    color: white;
    float: left;
}

 <div id="first" style="width:20px;">20</div>
        <div id="second" style="width:30px;">30</div>
        <div id="third" style="width:40px;">40</div>