1

我有一个父 div 有几个孩子http://jsfiddle.net/thiswolf/FUqSP/我希望将每个 div 垂直居中在包含 child 的孩子中。例如我想在child_one 中居中 child_two 我有这个css

.parent{
width:300px;
height:300px;
background-color:orange;
display:table-cell;
vertical-align:middle;
}
.child_one{
width:100px;
height:100px;
background-color:purple;
margin-left:auto;
margin-right:auto;
}
.child_two{
width:50px;
height:50px;
background-color:pink;
margin-left:auto;
margin-right:auto;
}
.child_three{
width:25px;
height:25px;
background-color:yellow;
margin-left:auto;
margin-right:auto;
}
.child_four{
width:12px;
height:12px;
background-color:red;
margin-left:auto;
margin-right:auto;
}

这是html

<div class="parent">
<div class="child_one">
<div class="child_two">
<div class="child_three">
<div class="child_four">
</div>
</div>
</div>
</div>
</div>
4

4 回答 4

1

在每个孩子身上添加这个

位置:相对;
最高:25%;

这里是完整的 CSS,

.parent{
width:300px;
height:300px;
background-color:orange;
display:table-cell;

 }
.child_one{
width:100px;
height:100px;
background-color:purple;
margin-left:auto;
margin-right:auto;
 position: relative;
top: 25%;
}
.child_two{
width:50px;
height:50px;
background-color:pink;
margin-left:auto;
margin-right:auto;
 position: relative;
top: 25%;
}
.child_three{
width:25px;
height:25px;
background-color:yellow;
margin-left:auto;
margin-right:auto;
 position: relative;
top: 25%;
}
.child_four{
width:12px;
height:12px;
background-color:red;
margin-left:auto;
margin-right:auto;
 position: relative;
top: 25%;
}

这里的演示:小提琴

于 2012-09-28T09:09:08.787 回答
1

检查此链接

我曾经float:left;实现它。

检查这个小提琴

我已经使用百分比完成了。
对于其他方法来实现这个检查这个链接

我建议您使用百分比来执行此操作。这不会让你感到困惑。

于 2012-09-28T09:17:00.250 回答
0

您可以使用孩子的绝对定位。您必须将每个孩子定位在顶部 50% 和左侧 50%,并给他们一个负的顶部和左侧边距,其宽度和高度的一半。

.parent{
    width:300px;
    height:300px;
    background-color:orange;
    position: relative;
}
.child_one{
    width:100px;
    height:100px;
    background-color:purple;
    position:absolute;
    left: 50%;
    top: 50%;
    margin-left: -50px;
    margin-top: -50px;
}

这只是第一个孩子。你必须对每个孩子做同样的事情。因此,如果宽度为 50px,则使用 -25px 的边距。

http://jsfiddle.net/APdaP/

于 2012-09-28T09:07:53.377 回答
0

根据我在之前的评论中发送给您的链接,您应该尝试以下解决方案:

Css 表法

它会将您的 div 显示为表格单元格,以便您可以将vertical-align其用于您的子 div。

于 2012-09-28T09:13:15.867 回答