hrsetyono
hrsetyono

Reputation: 4464

Flexbox - Vertically align both blocks and text

I want h2 with a button on the side like seen in the picture below:

enter image description here

I tried flexbox, but by centering the button, it doesn't fill full height anymore.

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>

Is there a way to achieve as pictured? I want to avoid adding Padding or fixed height to the button because then I need to adapt it for multiple media queries.

Upvotes: 2

Views: 48

Answers (2)

ab29007
ab29007

Reputation: 7766

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>

Upvotes: 0

kukkuz
kukkuz

Reputation: 42352

Make your button a flexbox too and vertically align using align-items: center - see demo below:

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

Upvotes: 5

Related Questions