繁体   English   中英

html在子div的中心显示父div,其高度大于子div

[英]html show parent div on center of child div having height greater than child

我有一个像这样的div:

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

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

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

我想要什么,如果父div为10px,子div为20px,则子项应在底部和顶部均等显示10px,就像父项位于居中位置。

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

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

<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

下面没有绝对定位的代码也可以正常工作。

 .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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM