如何在div容器的中间垂直居中h1?

时间:2015-10-27 08:12:42

标签: html css

如标题中所述,我需要的是在div的中间垂直居中标题h1。

这是一个非常简单的代码:

.container{
width:500px;
height:180px;
background-color:red;
text-align:center;
}

h1{
vertical-align:middle;
}

{{1}}

这是demo here

使用显示表后,文本垂直居中,谢谢大家。现在我正面临一个新问题; (看看jsffidle here please 我想要的是“文本1”和“文本2”将并排显示,并且每个小的蓝色div都在每个红色div的中间的两个红色div下面...有什么帮助吗?

1 个答案:

答案 0 :(得分:7)

解决方案#1

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; /* <--- */
}

FIDDLE

.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>

解决方案#2:Flexbox

.container{
    width:500px;
    height:180px;
    background-color:red;
    text-align:center;
    display: flex;
    align-items: center; /* align vertical */
}

FIDDLE

.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>

解决方案#3 - 转换

h1
{
    position: relative;
    top: 50%;
    transform: translateY(-50%);
}

FIDDLE

.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>

解决方案#4添加高度为100%的伪元素

.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;
}

FIDDLE

.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>