Search code examples
htmlcssvertical-alignment

How to align h2 and p on same basline in div


I have a post header div with height of 70px/4.375em In it is a category h2 and a p timestamp

I want it to be aligned as demonstrated in this picture (made in Photoshop)

Here is my HTML:

<div class="post-header" style="background-color:#9377d8">
    <h2 class="category">Technology</h2>
    <p class="timestamp">Saturday, today</p>
</div>

And my CSS:

.post-header{
    height:4.375em;
    width:25em;
    margin-bottom:0;
    float:left;
}
.category{
    color:white;
    display:inline;
    float:left;
    margin:0.625em;
}

.timestamp{
    color:white;
    display:inline;
    float:right;
    margin:0.625em;
}

Please help me with the CSS to get the design that I want


Solution

  • You can change your CSS as follows:

    .post-header {
        height:4.375em;
        width:25em;
        margin-bottom:0;
        display:block;
    }
    .category {
        color:white;
        display:inline-block;
        width:45%;
        margin:0.625em;
    }
    .timestamp {
        color:white;
        display:inline-block;
        text-align:right;
        margin:0.625em;
        width:40%;
    }
    

    This way, you get better control over your layout since you can specify both the width and the vertical align of the element. As we're at it, I'd use percentages for margins, but of course it goes on you

    Visit fiddle to see it in action