如何在div内以可变高度垂直居中内容? [英] How to vertically center content with variable height within a div?
问题描述
当内容的高度可变时,垂直居中div的内容的最佳方式是什么?在我的特定情况下,容器div的高度是固定的,但是如果存在在容器具有可变高度的情况下将工作的解决方案将是巨大的。此外,我会喜欢没有或很少使用CSS hack和/或非语义标记的解决方案。
What is the best way to vertically center the content of a div when the height of the content is variable. In my particular case, the height of the container div is fixed, but it would be great if there were a solution that would work in cases where the container has a variable height as well. Also, I would love a solution with no, or very little use of CSS hacks and/or non-semantic markup.
c>伪元素: CSS-Tricks:以未知方式居中。
它不需要任何额外的标记,似乎工作非常好。我不能使用 display:table
方法,因为表
元素不服从 max-height
属性。
It doesn’t require any extra markup and seems to work extremely well. I couldn’t use the display: table
method because table
elements don’t obey the max-height
property.
.block {
height: 300px;
text-align: center;
background: #c0c0c0;
border: #a0a0a0 solid 1px;
margin: 20px;
}
.block:before {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
margin-right: -0.25em; /* Adjusts for spacing */
/* For visualization
background: #808080; width: 5px;
*/
}
.centered {
display: inline-block;
vertical-align: middle;
width: 300px;
padding: 10px 15px;
border: #a0a0a0 solid 1px;
background: #f5f5f5;
}
<div class="block">
<div class="centered">
<h1>Some text</h1>
<p>But he stole up to us again, and suddenly clapping his hand on my
shoulder, said—"Did ye see anything looking like men going
towards that ship a while ago?"</p>
</div>
</div>
这篇关于如何在div内以可变高度垂直居中内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!