中心在容器div中水平分割

时间:2014-07-23 09:52:08

标签: html css

我有多个div,它们是一个设置的宽度,我想在容器div中居中。子div的数量可能会有所不同,所以无论有多少div与父div一起,我都需要它们居中。注意:容器div必须具有position:absolute

<div class="wrapper">
  <div class="f" ></div>
  <div class="f" ></div>
  <div class="f"></div><div class="f">
  </div><div class="f"></div>
</div>

和CSS

.wrapper {
    position: absolute;
    width: 80%;
    top: 0;
    left: 0;
    text-align: center;
    margin: 0px auto;
    border: 0.2rem solid black;
    height: 0.8rem;
}

.f {
    -webkit-box-shadow: inset 0.2rem 0 0 white;
    box-shadow: inset 0.2rem 0 0 white;
    background-color: red;
    width: 35px;
    height: 0.8rem;
    position: relative;
    float: left;
}

jsfiddle是here

2 个答案:

答案 0 :(得分:1)

移除浮动并在子项上设置display:inline-block,然后从容器中移除高度,以便根据需要自动扩展。

Demo Fiddle

CSS

.wrapper {
    position: absolute;
    width: 80%;
    top: 0;
    left: 0;
    text-align: center;
    margin: 0px auto;
    border: 0.2rem solid black;
}
.f {
    -webkit-box-shadow: inset 0.2rem 0 0 white;
    box-shadow: inset 0.2rem 0 0 white;
    background-color: red;
    width: 35px;
}
i {
    font-size: 0;
    height: 0.8rem;
    position: relative;
    display:inline-block;
}

答案 1 :(得分:0)

简单添加此css

JSFIDD

    .wrapper {
position: absolute;
width: 80%;
top: 0;
left: 0;
text-align: center;
margin: 0px auto;
border: 0.2rem solid black;
height: 0.8rem;
    left:50%;
    margin-left: -40%; /*width/2*/
}