[英]Centering multiple side-by-side divs
我正在嘗試制作多個div,特別是五個並將它們全部置於中心位置。 我已經使用了display:inline-block
來讓它們並排,但是當我使用margin: 0 auto
, display:inline-block
似乎被否定了,然后它就是一個沿着頁面向下的垂直條帶。
以下是我的代碼:
div { width: 50px; height: 300px; border-radius: 0; display: inline-block; } #red { background-color: red; } #orange { background-color: orange; } #yellow { background-color: yellow; } #green { background-color: green; } #blue { background-color: blue; }
<div class="container"> <div id="red"></div> <div id="orange"></div> <div id="yellow"></div> <div id="green"></div> <div id="blue"></div> </div>
我試着查看SO上的其他相關帖子,但他們沒有使用盡可能多的div或者他們使用我不想使用的靜態定位。
有人能指出我正確的方向嗎?
發生這種情況導致容器的寬度為50px。 一個快速的解決方案是將容器的width
設置為100%:
div { width: 50px; height: 300px; border-radius: 0; display: inline-block; } #red { background-color: red; } #orange { background-color: orange; } #yellow { background-color: yellow; } #green { background-color: green; } #blue { background-color: blue; } .container { width: 100%; }
<div class="container"> <div id="red"></div> <div id="orange"></div> <div id="yellow"></div> <div id="green"></div> <div id="blue"></div> </div>
您可以使用text-align
中心與容器對齊到中心:
div { width: 50px; height: 300px; border-radius: 0; display: inline-block; } #red { background-color: red; } #orange { background-color: orange; } #yellow { background-color: yellow; } #green { background-color: green; } #blue { background-color: blue; } .container { width: 100%; text-align: center; }
<div class="container"> <div id="red"></div> <div id="orange"></div> <div id="yellow"></div> <div id="green"></div> <div id="blue"></div> </div>
要同時實現垂直和水平對齊,您可以使用position: absolute
到容器top: 50%
left: 50%
和margin-top: -150px; /* Half the height */
margin-top: -150px; /* Half the height */
margin-left: -135px; /* Half the width */
margin-left: -135px; /* Half the width */
:
div { width: 50px; height: 300px; border-radius: 0; display:inline-block; } #red { background-color: red; } #orange { background-color: orange; } #yellow { background-color: yellow; } #green { background-color: green; } #blue { background-color: blue; } .container { width: 270px; position: absolute; top: 50%; left:50%; margin-top: -150px; /* Half the height */ margin-left: -135px; /* Half the width */ }
<div class="container"> <div id="red"></div> <div id="orange"></div> <div id="yellow"></div> <div id="green"></div> <div id="blue"></div> </div>
您可以在.container上設置text-align:center。 更新了代碼:
.container {
width: 100%;
text-align: center;
}
.container > div{
width: 50px;
height: 300px;
border-radius: 0;
display:inline-block;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.