Search code examples
cssflexboxvertical-alignment

I'm unable to vertically center <h2> in a <div> tag


I've got a problem with centering in another tag . I have no problem with horizontal align in a flexox or in a old fashion way but vertical is still a problem for me.

div {
    display: inline-block;
    background-color: green;    
    width: 130px;
    height: 45px;
    margin-top: 20px;
    text-align: center;
    
}
h2 {
    font-size: 20px;
    font-weight: 100;
    display: flex;
    justify-content: center;
    align-content: center;

Solution

  • There are several problems:

    1. The h2 element is not in a flex container (you have to set display: flex on the parent div)
    2. The properties justify-content and align-content have to be set on the flex container, not the flex item.
    3. For centering a flex item vertically in a flex container with flex-direction: row, you have to use align-items rather than align-content

    div {
        display: flex;
        justify-content: center;
        align-items: center;    
        width: 130px;
        height: 45px;
        margin-top: 20px;
        text-align: center;
        background-color: green;    
    }
    
    h2 {
        font-size: 20px;
        font-weight: 100;
    }
    <div>
      <h2>Headline 2</h2>
    </div>