如标题中所述,我需要的是在div的中间垂直居中标题h1。
这是一个非常简单的代码:
.container{
width:500px;
height:180px;
background-color:red;
text-align:center;
}
h1{
vertical-align:middle;
}
{{1}}
使用显示表后,文本垂直居中,谢谢大家。现在我正面临一个新问题; (看看jsffidle here please 我想要的是“文本1”和“文本2”将并排显示,并且每个小的蓝色div都在每个红色div的中间的两个红色div下面...有什么帮助吗?
答案 0 :(得分:7)
将display:table;
添加到容器,将display:table-cell;
添加到h1
.container{
width:500px;
height:180px;
background-color:red;
text-align:center;
display:table; /* <---- */
}
h1{
vertical-align:middle;
display:table-cell; /* <--- */
}
.container {
width: 500px;
height: 180px;
background-color: red;
text-align: center;
display: table;
}
h1 {
vertical-align: middle;
display: table-cell;
}
<div class="container">
<h1> title in multiple lines, so i can't use line-height, i must use something else </h1>
</div>
.container{
width:500px;
height:180px;
background-color:red;
text-align:center;
display: flex;
align-items: center; /* align vertical */
}
.container {
width: 500px;
height: 180px;
background-color: red;
text-align: center;
display: flex;
align-items: center;
/* align vertical */
}
<div class="container">
<h1> title in multiple lines, so i can't use line-height, i must use something else </h1>
</div>
h1
{
position: relative;
top: 50%;
transform: translateY(-50%);
}
.container {
width: 500px;
height: 180px;
background-color: red;
text-align: center;
}
h1 {
position: relative;
top: 50%;
transform: translateY(-50%);
}
<div class="container">
<h1> title in multiple lines, so i can't use line-height, i must use something else </h1>
</div>
.container:before {
content:'';
display: inline-block;
height: 100%;
vertical-align: middle;
margin-right: -4px; /* to counter inline-block whitespace */
}
h1 {
display: inline-block;
vertical-align: middle;
}
.container {
width: 500px;
height: 180px;
background-color: red;
text-align: center;
}
.container:before {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
margin-right: -4px;
/* to counter inline-block whitespace */
}
h1 {
display: inline-block;
vertical-align: middle;
}
<div class="container">
<h1> title in multiple lines, so i can't use line-height, i must use something else </h1>
</div>