2014-01-25 43 views
1

我知道这是一个拉出的问题,但所有示例都可以在网上找到,因为某些原因,我无法复制。如何以特定宽度居中彼此相邻的2个div

我需要2个300像素的div盒子;彼此相邻并且居中居中。

我有以下代码

<div class="container"> 
    <div class="box1"></div> 
    <div class="box2"></div> 
</div> 

<style> 
    .container { 
     width:100%; 
     text-align:center"; 
    } 
    .box1 { 
     float:left; 
     width:300px; 
    } 
    .box2 { 
     float:right; 
     width:300px; 
    } 
</style> 

无论出于何种原因,我能得到彼此相邻的箱子,但它停留在屏幕上,而不是中心的左侧。我只需要他们集中

回答

0

例子:http://jsbin.com/ubanuf/12/edit(不是我)

这是因为你有float: left。有几种方法可以做到这一点,你可以添加display: inline-block;或添加margin: 0 auto;

.box1 { 
     float:left; 
     width:300px; 
     display: inline-block; 
    } 
    .box2 { 
     float:right; 
     width:300px; 
     display: inline-block; 
    } 
+1

爱你:)该做的感谢 –

0

改变你的CSS如下

.container { 
    width:100%; 
    text-align:center; 
} 
.box1, .box2 { 
    display: inline-block; 
    width:300px; 
} 

inline-block元件将利用文本对齐,如果你的设置text-align: centercontainerdiv。 。 你在你的CSS text-align: center";有额外的(“)双引号

0

这里有一个其他的方式(有很多的确!):

.container { 
    margin: 0 auto; 
    width: 100px; 
} 
.box1 { 
    width:50%; 
    display: inline-block; 
} 
.box2 { 
    float: right; 
    width:50%; 
    display: inline-block; 
} 
0

有两个孩子的DIV之间的冗余空间,如果你使用inline-blockhere是我的解决方案。

container { 
    width:100%; 
    text-align:center; 
    font-size: 0; // hack the space 
} 
.container div{ 
    font-size: 16px; // hack "hack the space" 
} 
.box1 { 
    display:inline-block; 
    width:300px; 
} 
.box2 { 
    display:inline-block; 
    width:300px; 
} 
0

你不需要做任何thing..just给BOX1和BOX2宽度“%”或给容器宽度“像素”。这将解决你的问题

喜欢这个

<style> 
    .container { 
    width:100%; //or change it to 600px 
    text-align:center"; 
    } 
    .box1 { 
    float:left; 
    width:300px; //or change it to 50% 
    } 
    .box2 { 
    float:right; 
    width:300px; //or change it to 50% 
    } 
</style> 

尽量把一切都在 “%” 或 “像素” 感谢