Search code examples
htmlcssflexboxvertical-alignment

Vertical-aligning title beside a div


I'm new to HTML/CSS and I still have difficulties with vertical alignment, although I have read several articles on this topic.

Consider the following code.

header {
    display: flex;
}

header div {
    width: 150px;
    height: 150px;
    background-color: grey;
}

header h1 {
    display: inline-block;
    vertical-align: middle;
    background-color: orange;
    margin: 0;
}
<body>
    <header>
        <div></div>
        <h1>My title here</h1>
    </header>
</body>

What I am trying to achieve is this:

expected-result

I have tried the techniques described here but I still don't manage to get this result. What is the best solution?


Solution

  • Use align-items: center; on your header

    vertical-align: middle; and display: inline-block; not needed on h1

    header {
        display: flex;
        align-items: center;
    }
    
    header div {
        width: 150px;
        height: 150px;
        background-color: grey;
    }
    
    header h1 {
        background-color: orange;
        margin: 0;
    }
    <header>
        <div></div>
        <h1>My title here</h1>
    </header>