2015-05-04 111 views
0

我需要三个盒子居中并水平排列。现在,我已在中心,但只在垂直方向:如何居中div的水平线?

enter image description here

这里是盒子的CSS:

.box { 
    margin-left: auto; 
    margin-right: auto; 
    background-color: #9FDCED; 
    display: block; 
    height: 400px; 
    width: 500px; 
} 

任何帮助将不胜感激。

+0

请加入小提琴和你的预期结果的更详细的图像。我不确定,但我相信你正在垂直和水平混合。 – timo

+0

我只是想让这3个盒子水平排列,而不是垂直排列 – HowToGaming

回答

0

只需将float:left;添加到.box类。像这样

.box { 
    margin: 5px; 
    background-color: #9FDCED; 
    display: block; 
    height: 100px; 
    width: 100px; 
    padding: 5px; 
    float: left; 
} 

工作的jsfiddle http://jsfiddle.net/wcvgs1zb/

+0

但是这个解决方案不再有盒子居中了。现在他们都在屏幕的左侧 –

4

给这个.box一个display: inline-blockvertical-align: top使他们旁边的海誓山盟对齐。如果将其与<div>环绕它,得到text-align: center,则内联内容会水平居中。

.container { 
 
    text-align: center; 
 
} 
 

 
.box { 
 
    background-color: #9FDCED; 
 
    display: inline-block; 
 
    height: 50px; 
 
    width: 50px; 
 
    vertical-align: top; 
 
} 
 

 
.box--high { 
 
    height: 75px; 
 
}
<div class="container"> 
 
    <div class="box"></div> 
 
    <div class="box box--high"></div> 
 
    <div class="box"></div> 
 
</div>

水平和垂直居中使用CSS一个很好的资源是https://css-tricks.com/centering-css-complete-guide/

+1

非常感谢你:) – HowToGaming

1

.box1 { 
 
\t display: table; 
 
    margin: 0 auto; 
 
} 
 
.box { 
 
\t background-color: #9FDCED; 
 
\t display: inline-block; 
 
\t height: 200px; 
 
\t width: 200px; 
 
}
<div class="box1"> 
 
\t <div class="box" style="background:#cc0000;"></div> 
 
\t <div class="box" style="background:#cceeff;"></div> 
 
\t <div class="box" style="background:#eeccff;"></div> 
 
</div>