html显示父亲div在高度大于孩子的子div的中心

时间:2017-02-10 07:29:14

标签: html css

我有一个像:

<div style="background-color: blue; height: 10px">
    <div style="height: 20px; width: 10px">
    </div>
</div>

这里我有一个div来容纳一个div,其高度是其父div的两倍。

显示子项的高度是其父项的两倍,但其额外的10px高度显示在底部。

如果父div为10px且子div为20px,我想要的是,孩子应该在底部和顶部平均显示额外的10px,就像父母居中一样。

这样做的正确方法是什么?

2 个答案:

答案 0 :(得分:0)

您可以使用位置aboslute,然后减去父级高度的一半:

<div style="background-color: blue; height: 100px; width:100px">
    <div style="height: 200px; width: 100px; background-color: green; opacity: 0.5; position: absolute; top:-50px">
    </div>
</div>

请参阅此处的codepen:http://codepen.io/fennefoss/pen/qRQdyP

答案 1 :(得分:0)

下面发布的代码没有绝对定位也适用。

.parent {
	background-color: blue; 
	height: 10px;
}

.child {
	height: 20px;
	width: 50px;
	background-color: red;
	position: relative;
	top: 50%;
	transform: translateY(-50%);
}
<div class="parent">
    <div class="child"></div>
</div>