如何对齐3个div左中右?

时间:2013-02-28 11:29:03

标签: html css

如何在左右中心的一行中对齐3个div,而无需定义显式大小?

左边应该与左边缘对齐,右边边缘对齐。

以下不起作用:

<div style="float: left;">
    left
</div>
<div style="float: right;">
    right
</div>
<div style="margin: 0 auto;">
    center
</div>

5 个答案:

答案 0 :(得分:16)

添加包装div并提供text-align:center

<强> CSS

.wrap{
        text-align:center
    }

<强> HTML

<div class="wrap">
<div class="left">
    left
</div>
<div class="right">
    right
</div>
<div class="center">
    center sdv dg sdb sdfbh sdfhfdhh h dfh
</div>
    </div>

<强> DEMO

答案 1 :(得分:2)

<div style="width:100%;margin:0 auto; padding: 0">
     <div style=" float:left;width:32%;border: thin solid black">
         left
     </div>
     <div style=" float:left;width:32%;border: thin solid black">
         center
     </div>
     <div style=" float:left;width:32%;border: thin solid black">
          right 
     </div>
 </div>
 <div style="clear:both">
 </div>

答案 2 :(得分:2)

下面是一个如何通过以正确的顺序放置浮动来执行此操作的示例。

jsFiddle Example

<div class="square" style="float: left;">left</div>
<div class="square" style="float: right;">right</div>
<div class="square" style="margin:0 auto  !important;">center</div>


.square {
width:50px;
height:50px;
background-color:#ff0000;
text-align:center;
border: 1px solid #000;
}

答案 3 :(得分:0)

试试这个

<强> CSS

div{width:33%;}

<强> HTML

<div style="float: left;border:1px solid red;">
    left
</div>
<div style="float: right;border:1px solid green;">
    right
</div>
<div style="margin: 0 auto;border:1px solid blue;">
    center
</div>

答案 4 :(得分:0)

如果不了解内容和布局模式,实际上不可能这样做。但是对于一个起点,你可以试试这个:

HTML:

<div class="clearfix holder">
    <div class="column left">
        Some Contents Here...
    </div>
    <div class="column middle">
        Some Contents Here...
    </div>
    <div class="column right">
        Some Contents Here...
    </div>
</div>

CSS:

.clearfix:before,
.clearfix:after {
    content: " ";
    display: table;
}
.clearfix:after {
    clear: both;
}
.clearfix {
    *zoom: 1;
}
.holder{
    text-align:center;
}
.column{
    display:inline-block;
    *display:inline;
    *zoom:1;
    width:auto;
}
.left{
    background-color:#ff0;
    float:left;
}
.middle{
    background-color:#f0f;
    margin:0 auto;
}
.right{
    background-color:#0ff;
    float:right;
}

DEMO