【问题标题】:Vertically aligning two elements [duplicate]垂直对齐两个元素[重复]
【发布时间】:2016-03-22 21:31:12
【问题描述】:
<header>
    <h1>Title</h1>
    <h2>Subtitle</h2>
</header>

我需要在标题内垂直对齐 h1 和 h2。 h2 必须低于 h1。有没有办法在不包装 h1 和 h2 标签的情况下使用 flex 来做到这一点?


编辑

要明确一点 - H1 和 H2 应在标题内垂直对齐。 H1 和 H2 应该位于另一个之下。

【问题讨论】:

  • 确实 h2 将实际上 低于 h1。问题是什么?
  • 通常使用 line-height 的游戏来完成,但一个工作示例 (plnkr/jsfillde) 会有所帮助
  • 问题是 - 如何垂直对齐 h1 和 h2?
  • 你的意思是垂直对齐 h1 & h2 中的文本?
  • 改html可以吗?如果我们再添加一个元素来包装标题?

标签: css flexbox


【解决方案1】:

这就是你想要的

<style>
header{
    display: flex;
    flex-direction: column;
    justify-content: center;
}
h1,h2{
  text-align: center;
}
</style>

<header>
    <h1>Title</h1>
    <h2>Subtitle</h2>
</header>

【讨论】:

  • margin:0; 将其添加到 h1 和 h2 中,这样它们将是精确的中心
【解决方案2】:

你可以用这样的弹性框来做到这一点。

header{
  border: 2px solid red;
  height: 70vh;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

h1,h2{
  margin: 0;
  padding: 0;
  text-align: center;
}

h1{
  background: red;
}

h2{
  background: yellow;
}
<header>
    <h1>Heading 1</h1>
    <h2>Heading 2</h2>
</header>

【讨论】: