有一个具有动态内容的div。父母的身高是身体的100%,孩子是未知的。仅当子内容高度小于父级时,translateY(-50%)技术才有效。但如果它更多的孩子div(绿色)开始溢出父(黄色),如下图所示。 设置父div的正确方法是增加高度并添加一些填充。
.body {
height: 300px;
background: red;
}
.parent {
height: 100%;
position: relative;
background: rgb(105, 199, 115);
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: green;
width: 200px;
}
<div class="body">
<div class="parent">
<div class="child">
Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content,
</div>
</div>
</div>
答案 0 :(得分:2)
为何定位?!
你可以把div放在这里:
我使用它作为中心,在它的父级中具有动态高度的div:
<style>
.body {
height: 300px;
background: red;
display:table;
width: 100%;
}
.parent {
display:table-cell;
vertical-align: middle;
background: rgb(105, 199, 115);
}
.child {
background: green;
width: 200px;
margin: auto;
}
</style>
<div class="body">
<div class="parent">
<div class="child">
Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content,
</div>
</div>
</div>