Flexbox - 垂直对齐块和文本

时间:2016-12-23 06:52:48

标签: html css html5 css3 flexbox

我希望h2旁边有一个button,如下图所示:

enter image description here

我尝试了flexbox,但是以button为中心,它不再填满整个高度。

header {
  display: flex;
  background-color: blue;
  color: white;
  margin-bottom: 2em;
}
.header1 {
  align-items: center;
}
.button {
  margin-left: auto;
  background-color: yellow;
}
<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>

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

2 个答案:

答案 0 :(得分:5)

使用button使flexbox成为align-items: center垂直对齐 - 请参阅下面的演示:

&#13;
&#13;
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;
}
&#13;
<header class="header2">
  <h2>Button full height but Text not centered</h2>
  <a class="button" href="https://google.com">Read More</a>
</header>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

header {
  display: flex;
  background-color: blue;
  color: white;
  margin-bottom: 2em;
}

.header1 { align-items: center; }

.button {
  margin-left: auto;  
  background-color: yellow;
  display:block;
vertical-align:middle;
  line-height:30px;
  position:relative;
  padding:0 10px;
}
a span {
    display:block;
    height:50%;
  margin-top:-15px;
}
<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"><span></span>Read More</a>
</header>