【问题标题】:Can't vertical center h1 inside div [duplicate]不能在 div 内垂直居中 h1 [重复]
【发布时间】:2020-04-14 00:25:22
【问题描述】:

尝试在 div 中垂直居中标题时遇到了一些麻烦。 CSS如下:

.container {
  background: #a3f;
  padding-left: 3% !important;
}

.container h4 {
  vertical-align: middle;
  text-align: center;
  background: #f02;
}

我尝试了一些solutions(也有this),但文本继续在div的顶部。

【问题讨论】:

  • 尝试为标题添加display: inline-block;,看看它是否有效

标签: html css


【解决方案1】:

我提供了几种 (5) 方法:

1。 grid(使用网格的两种方式)

.container {
  background: #a3f;
  height: 100px;
  
  display: grid;
  place-items: center;
  /* or */ /* place-content: center; */
}

.container h4 {
  background: #f02;
}
<div class="container">
  <h4> The header </h4>
</div>

2。 flex

.container {
  background: #a3f;
  height: 100px;
  
  display: flex;
  justify-content: center;
  align-items: center;
}

.container h4 {
  background: #f02;
}
<div class="container">
  <h4> The header </h4>
</div>

3。 translate(-50%, -50%)

.container {
  background: #a3f;
  height: 100px;
  position: relative;
}

.container h4 {
  background: #f02;
  
  position: absolute;
  left: 50%; top: 50%;
  margin: 0; padding: 0;
  -ms-transform: translate(-50%, -50%);
  transform    : translate(-50%, -50%);  
}
<div class="container">
  <h4> The header </h4>
</div>

4。 table

.container {
  background: #a3f;
  height: 100px;
  
  width: 100%;
  display: table;
  text-align: center;
}

.container h4 {
  display: table-cell;
  vertical-align: middle;
}
<div class="container">
  <h4> The header </h4>
</div>

5。 transform: translateY(-50%);position: relative;

.container {
  background: #a3f;
  height: 100px;
  
}

.container h4 {
  background: #f02;
  
  text-align: center;
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}
<div class="container">
  <h4> The header </h4>
</div>

【讨论】:

  • 由于其他原因,我无法使用第 5 种方法,但第一种方法完美。谢谢!!
  • 很高兴它有帮助。我只是想给你一些选择。谁知道将来你会发现其他有用的东西。
【解决方案2】:

也许使用弹性盒子?

.container {
  background: #a3f;
  padding-left: 3% !important;
  height: 500px;
  
  display:flex;
  justify-content:center;
  align-items:center;
}

.container h4 {
  /*vertical-align: middle;*/
  text-align: center;
  background: #f02;
}
<div class="container">
<h4>Blabla</h4>
</div>

【讨论】:

    猜你喜欢
    • 2014-01-01
    • 1970-01-01
    • 2017-09-25
    • 1970-01-01
    • 2016-01-26
    • 2017-07-29
    • 1970-01-01
    • 1970-01-01
    • 2014-05-10
    相关资源
    最近更新 更多