以多个并排的div为中心

时间:2014-11-13 12:40:31

标签: html css

我正在尝试制作多个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或者他们使用我不想使用的静态定位。

有人能指出我正确的方向吗?

2 个答案:

答案 0 :(得分:10)

这会导致容器的宽度为50px。一个快速的解决方案是将容器的width设置为100%:

&#13;
&#13;
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%;
}
&#13;
<div class="container">
  <div id="red"></div>
  <div id="orange"></div>
  <div id="yellow"></div>
  <div id="green"></div>
  <div id="blue"></div>
</div>
&#13;
&#13;
&#13;

您可以使用text-align中心与容器对齐到中心:

&#13;
&#13;
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;
}
&#13;
<div class="container">
  <div id="red"></div>
  <div id="orange"></div>
  <div id="yellow"></div>
  <div id="green"></div>
  <div id="blue"></div>
</div>
&#13;
&#13;
&#13;

要同时实现垂直和水平对齐,您可以position: absolute使用容器top: 50% left: 50%margin-top: -150px; /* Half the height */ margin-left: -135px; /* Half the width */

&#13;
&#13;
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 */
}
&#13;
<div class="container">
  <div id="red"></div>
  <div id="orange"></div>
  <div id="yellow"></div>
  <div id="green"></div>
  <div id="blue"></div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

您可以在.container上设置text-align:center。更新了代码:

.container {
    width: 100%;
    text-align: center;
}

.container > div{
    width: 50px;
    height: 300px;
    border-radius: 0;
    display:inline-block;  
}

http://jsfiddle.net/jermund/wzdLrs0m/

相关问题