Flexbox - 垂直对齐块和文本

hrs*_*ono 2 html css html5 css3 flexbox

我希望h2有一个button侧面如下图所示:

在此输入图像描述

我尝试了flexbox,但是通过居中button,它不再填满整个高度.

header {
  display: flex;
  background-color: blue;
  color: white;
  margin-bottom: 2em;
}
.header1 {
  align-items: center;
}
.button {
  margin-left: auto;
  background-color: yellow;
}
Run Code Online (Sandbox Code Playgroud)
<header class="header1">
  <h2>Text centered but Button not full Height</h2>
  <a class="button" href="https://google.com">Read More</a>
</header>

<header class="header2">
  <h2>Button full height but Text not centered</h2>
  <a class="button" href="https://google.com">Read More</a>
</header>
Run Code Online (Sandbox Code Playgroud)

有没有办法实现如图所示?我想避免为按钮添加填充或固定高度,因为我需要调整它以进行多个媒体查询.

kuk*_*kuz 5

让你button一个flexbox也和垂直对齐使用align-items: center-参见下面的演示:

header {
  display: flex;
  background-color: blue;
  color: white;
  margin-bottom: 2em;
}
.header1 {
  align-items: center;
}
.button {
  margin-left: auto;
  background-color: yellow;
  display: flex;
  align-items: center;
}
Run Code Online (Sandbox Code Playgroud)
<header class="header2">
  <h2>Button full height but Text not centered</h2>
  <a class="button" href="https://google.com">Read More</a>
</header>
Run Code Online (Sandbox Code Playgroud)

  • 很好,从来不知道解决方案会如此简单.我有很多东西要学习flexbox. (2认同)
  • 我正要点击**发布你的答案**,我看到了你的答案.:) (2认同)