html - 不能在div中垂直居中h1

标签 html css

<分区>

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

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

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

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

最佳答案

我有几 (5) 种方法:

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

.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。 翻译(-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。 表格

.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%); with 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>

关于html - 不能在div中垂直居中h1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59443042/

上一篇:html - 如何将文本框放在图片旁边

下一篇:html - 有没有办法在 html 静态网站上隐藏 .html 扩展名?

相关文章:

java - 为什么我们需要 JSF 标签,如果我们有 HTML 标签

一个切换元素的jquery多个按钮

javascript - 在 html 中的按钮上使用外部文件

html - 并排的两个无序列表

css - 如何重叠两个div

javascript - 如何在调整大小时使光标与控制点同步?

javascript - 使用包含选择器在多列中搜索

javascript - 如何使用 JavaScript 访问 SharePoint 外部的 SharePoint 数据?

javascript - 通过单击选项卡而不是单击网站的任何部分来隐藏选项卡

html - 内联列表缩进