Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to align floated elements such that their bottoms match

I'm writing a web page where I show a title and a date over some text.

Blog post header http://filesmelt.com/dl/head00.png

My HTML:

<div class="post">
    <h2>Post 1</h2>
    <span class="date">February 28, 2011</span>

    <div class="post-content">
        ...
    </div>
</div>

My css:

.post h2
{
    float: left;
}

.date
{
    float: right;
}

.post-content
{
    clear: both;
}

What I want to do is vertically align the title and date such that their bottoms match. Right now they don't:

Blog post header with alignment lines http://filesmelt.com/dl/head01.png

I tried wrapping the two text elements in a div, setting the div's position to relative, and using absolute positioning on the two text elements (and taking out the float declarations). That didn't work because the top margin is not preserved due to the wrapper div collapsing, even though I gave it a clearfix class.

like image 999
AJM Avatar asked Mar 04 '11 07:03

AJM


2 Answers

Many of the other answers tell you to correct the difference by applying a static number for padding/line-height which I think is a bad solution. If you "correct" a difference with a static number and in the future the difference changes you have to change all the static numbers. Imagine you apply a padding to the Date div and later the font-size of the h2 changes, you'd have to change the padding.

Try this:

<div class="wrapper">
 <h2>Post 1</h2>
 <span class="date">February 28, 2011</span>
</div>

And css:

.post h2 {
    display: inline-block;
}

.wrapper {
  position: relative;
}

.date {
    display: inline-block;
    position: absolute;
    right: 0;
    bottom: 0;
}
like image 169
Bazzz Avatar answered Nov 15 '22 08:11

Bazzz


Use padding-top for for class Date

.date
{
    float: right;
    padding-top:15px;//Distance between the red lines in second image
}
like image 43
SNR Avatar answered Nov 15 '22 06:11

SNR