无法在div内垂直居中放置h1

时间:2019-12-22 09:29:20

标签: html css

尝试在div中垂直放置标题时遇到麻烦。 CSS如下:

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

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

我已经尝试过一些solutions(也是this),但是文本在div的顶部继续。

2 个答案:

答案 0 :(得分:1)

也许正在使用flexbox?

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

答案 1 :(得分: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>

相关问题