我怎样才能使子项在父项中垂直居中?
并且,child 和 parent 的宽度和高度是固定的,但未知。
我是怎么实现的?
<div class="parent">
<div class="child"></div>
</div>
最佳答案
我最喜欢的将盒子垂直和水平居中的技术需要两个容器。
外容器
- 应该有
display: table;
内容器
- 应该有
display: table-cell;
- 应该有
vertical-align: middle;
- 应该有
text-align: center;
内容框
- 应该有
display: inline-block;
- 应重新调整水平文本对齐方式,例如。
text-align: left;
或text-align: right;
,除非你希望文本居中
此技术的优雅之处在于,您可以将内容添加到内容框中而无需担心其高度或宽度!
只需将您的内容添加到内容框中即可。
演示
body {
margin : 0;
}
.outer-container {
position : absolute;
display: table;
width: 100%; /* This could be ANY width */
height: 100%; /* This could be ANY height */
background: #ccc;
}
.inner-container {
display: table-cell;
vertical-align: middle;
text-align: center;
}
.centered-content {
display: inline-block;
text-align: left;
background: #fff;
padding : 20px;
border : 1px solid #000;
}
<div class="outer-container">
<div class="inner-container">
<div class="centered-content">
<p>You can put anything here</p>
<p>Yes, really anything!</p>
</div>
</div>
</div>
另见 this Fiddle !
关于css - 怎么实现css垂直和水平居中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37097732/