7

I have a div containing some content. It has a height of 31px and inside it, the button has smaller height.

<div class="headerAndButton">
    <h3 class="h3">
        Click the button to the right
        <button>click me</button>
    </h3>
</div> 

I have another header that does not have a button in it.

<div class="headerAndButton">
    <h3 class="h3">No button here, I only want to have this header have the same vertical alignment, height and margin as the other header</h3>
</div>

I want to vertically align the <h3> text within each div. I have tried to solve the problem with the following SCSS:

.headerAndButton {
  margin-bottom: $space-300;

  h3 {
    min-height: 31px;
    vertical-align: bottom;

    button {
      margin-left: $space
    }
  }
}

The vertical-align property has no visible effect. The text in the without the botton is top aligned. The text in the other is a bit lower. It also becomes top aligned if I remove the button.

How can I make this headers have the same vertical alignment? I am not good at CSS, so maybe there are completely different better ways to solve this.

Yangshun Tay
  • 49,270
  • 33
  • 114
  • 141
user1283776
  • 19,640
  • 49
  • 136
  • 276
  • do you want to just vertical align the elements or should the header tags be on the same height, while one has a button below and the other does not? – Marian Rick Jul 08 '16 at 09:14
  • The button is to the right of the header. I want the header texts to have the same vertical alignment inside of their divs so that it is easy for me that have equal space between the divs containing the headers and the body texts following them – user1283776 Jul 08 '16 at 09:18
  • Do you have the possibility to work with fixed font size for the header? Or do you have to create a dynamic solution? – Marian Rick Jul 08 '16 at 09:23

3 Answers3

14

You could use several methods to vertical align an element. For example you could use new display: flex methods:

display: flex;
justify-content: center;
flex-direction: column;

Example

If its no problem to position: absolute your element you could use

position: absolute;
top: 50%;
transform: translate(-50%, -50%);

There is a quite good tutorial from CSS-Tricks, named Centering in CSS: A Complete Guide.

Marian Rick
  • 3,350
  • 4
  • 31
  • 67
3
display: flex;
justify-content: center;
align-items: center;

just apply this CSS code on headerAndButton

vik
  • 39
  • 2
0

You can use display:table-cell then vertical-align:middle to do that.

JS Fiddle

( I add a border so you can see the h3 is aligned )

Relisora
  • 1,163
  • 1
  • 15
  • 33