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;
}
Using Inline-Blocks
Using your HTML elements as posted, try the following CSS:
Since you have two child elements in
#header
, a left logo image and a right text block, just usetext-align: justify
to force the logo to the left and the text to the right.To get this to work, you need at least two rows in the
#header
.To generate a second row, use a pseudo element:
#header:after
which will place a 100% wide empty inline-block after the date. Thewidth: 100%
forces it to start and fill a 2nd row and thevertical-align: top
gets rid of the extra white space below the baseline.To deal with the white space in the height, set
line-height: 0
in#header
which will allow the height of the pseudo-element to collapse to 0. However, you need to reset theline-height: 1.5
in#dates
to get legible text.Pros and Cons
With this approach, the elements will eventually wrap to two lines as the page width gets smaller.
If you want to keep the elements on a single line, you might be better off using CSS tables.
See demo: http://jsfiddle.net/audetwebdesign/3U3w4/
Using
display: flex;
property you can set items to horizontally and vertically center.Example
I think, the best way for vertical align is using
css:display-table
andcss"display-table-cell
properties. If you want align to right content in id="dates" you should usecss:display-inline-table
inside this block.See Fiddle
You can make use of css
display:table
:Example
You may need to give the #dates a width if you want it to be aligned to the right