Search code examples
htmlalignmentvertical-alignmentcss

How to align an inline-block horizontally and vertically


What is the best/cleanest using CSS to align the #dates div to the right side of the header, and vertically in the middle.

I tried float: right, but that does not allow the vertical-align. I want to avoid using floats, so I am using inline-block, and using relative positioning. Is there a more correct approach?

I do not like the fact that I have to do a top of 30px, and using trial and error until it centers.

<div id="header">
    <a id="logo" href="~/" runat="server">
        <img src="Images/Interface/logo.png" alt="logo" />
    </a>
    <div id="dates">
        <div id="hijri-date">2 Ramadhaan, 1435 AH</div>
        <div id="gregorian-date">Sunday 29 June 2014</div>
    </div>
</div>

#header
{
    background-color: white;
    padding: 15px;
    position: relative;
}

#logo
{
    display: inline-block;
    vertical-align: middle;
}

    #logo img
    {
        vertical-align: bottom; /* to get rid of text descender space underneath image */
    }

#dates
{
    display: inline-block;
    position: absolute;
    right: 30px;
    top: 30px;
    font-size: 14px;
    font-family: 'Open Sans';
    color: #696969;
    background: url(Images/Interface/date-icon.png) no-repeat;
    background-position-y: center;
    padding-left: 32px;
}

Solution

  • You can make use of css display:table:

    #header {display:table; width:100%;}
    #logo,
    #dates {display:table-cell; vertical-align:middle}
    

    Example

    You may need to give the #dates a width if you want it to be aligned to the right