html - h1 和 h2 水平和垂直居中

标签 html css

<分区>

如何在垂直和水平方向上对齐 h1h2,同时保持高度为视口(viewport)的 100%?

我添加了 align-items: center; justify-content: center; 到容器和 text-align: center; vertical-align: center; 到标题类。将 display: block; 添加到任何一个都不执行任何操作。

预期:

How I want it to look

实际:

How mine looks

到底是怎么回事?是导航栏吗?

#welcome-section {
  height: 100vh;
  align-items: center;
  justify-content: center;
}

.welcome-header {
  text-align: center;
  vertical-align: center;
}
<div id="welcome-section">
  <h1 class="welcome-header">Namaste, Kevin here.</h1>
  <h2 class="welcome-header">And I'm a front-end developer</h2>
</div>

最佳答案

如果您使用 flex 对齐属性,则需要 flex 显示。

#welcome-section {
  height: 100vh;
  display:flex;/*this is  what was missing */
  flex-flow:column;/*this is  what was missing too*/
  align-items: center;
  justify-content: center;
}

https://codepen.io/gc-nomade/pen/MqJgVG

body {
  margin:0;
}

#welcome-section {
  height: 100vh;
  align-items: center;
  justify-content: center;
  display: flex;       /*this is  what was missing */
  flex-flow: column;  /*this is  what was missing too*/
}

.welcome-header {
  text-align: center;
  /*vertical-align: center; useless*/
}
<div id="welcome-section">
  <h1 class="welcome-header">Namaste, Kevin here.</h1>
  <h2 class="welcome-header">And I'm a front-end developer</h2>
</div>

关于html - h1 和 h2 水平和垂直居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52104825/

上一篇:html - 为什么 flex 元素不缩小过去的内容大小?

下一篇:javascript - 塌边向上开口

相关文章:

html - 定位多个背景图像

javascript - Jquery:运行时出现问题

尽管提到了 Lib,jQuery 脚本仍无法正常工作

javascript - 解释为什么这个 HTML 只能在 Firefox 中使用,而不能在任何其他浏览器中使用?

javascript - 使用 css 和 js 动态创建六边形设计

html - 如何在结构为 <ul> <li> 的菜单之间添加分隔符

html - 无法根据屏幕分辨率应用样式表

jquery - 使用动画删除背景图像

JavaScript按钮onclick不起作用

html - 我能否让 CSS3 边框图像在所有现代浏览器(IE 9+、Chrome 和 Firefox)上工作?