在未知高度div中垂直居中未知高度文本 [英] Center vertically a unknown height text in a unknown height div
问题描述
我知道这是一个常见的问题,我已经问过一个类似的问题。
但是我这次找不到解决方案。
我试图垂直居中的文本,可以有不同的高度在一个DIV,可以有不同的高度。
我只是想用CSS解决这个问题,而不用触摸HTML。
I know this is a common issue, and I've already asked a similar one. But I could not find the solution this time. I am trying to vertically center a text which can have different height in a DIV which can have different height. And I am trying to solve this only with CSS, without touching the HTML.
示例: http://jsfiddle.net/F8TtE/
<div id="test">
<div id="sumup">
<h1 class="titre">Title</h1>
<div id="date">hello guys</div>
</div>
</div>
我的目标是让文字沿垂直和水平方向集中在任何大小。
My goal is to have the text centered vertically and horizontally whatever its size.
推荐答案
这里是:
#test {
text-align:center;
}
#test::before {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
}
#sumup {
display: inline-block;
vertical-align: middle;
}
#test {
height : 180px;
text-align:center;
background: yellow;
}
#sumup {
background-color: #123456;
}
#test:before {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
}
#sumup {
display: inline-block;
vertical-align: middle;
}
<div id="test">
<div id="sumup">
<h1 class="titre">Title</h1>
<div id="date">hello guys</div>
</div>
</div>
编辑:现在是2015年,感谢网络的变化。假设您不支持过时的浏览器,通常使用 Flex模型。
It's now 2015 and thankfully the web changes. Assuming you don't support obsolete browsers, it's usually simpler and cleaner to vertically center elements with the Flex model.
#test {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
#test {
height : 180px;
background: yellow;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
#sumup {
background-color: #123456;
}
<div id="test">
<div id="sumup">
<h1 class="titre">Title</h1>
<div id="date">hello guys</div>
</div>
</div>
这篇关于在未知高度div中垂直居中未知高度文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!