Styling blog dates with CSS

Dates are an often neglected part of a blog layout. If styled properly, they can actually enhance the visual appeal of our layouts. CSS offers a great control over page elements especially when dealing with blocks containing short text. In our example, we'll examine the case of a date containing the string "October 8, 2010". As you can see, we have a month, a day and a year. To start with, here's how our markup should look like:

<div class="post">
    <span class="blog-date">October 8, 2010</span>
    <h2>Post title</h2>
    <p>...</p>
</div>

In this case, the blog date comes before the post title and is a simple span element with a class called .blog-date. We want to add a background image to our date just for creating the visual effect of a calendar date. Our CSS styles are as follows:

body {
  margin: 0 auto;
  padding: 2em 0;
  background: #fff;
  color: #333;
  font: 76%/1 Arial, sans-serif;
  width: 40%;
}

div.post {
  height: 100%;
  padding-bottom: 0.3em;
  border-bottom: 1px dashed #555;
  font-size: 1.1em;
}

div.post h2 {
  float: left;
  margin: 0;
  font: normal 3em Georgia, serif;
  color: #666;
  padding-left: 5px;
  padding-top: 10px;
  text-transform: uppercase;
  letter-spacing: 0.1em;
}

div.post span.blog-date {
  float: left;
  display: block;
  width: 79px;
  height: 50px;
  padding-top: 30px;
  font-size: small;
  text-align: center;
  font-weight: bold;
  background: url(img/date.png) no-repeat 0 0;
  line-height: 1.3;
}

div.post p {
  clear: both;
  margin-top: 0;
  padding-top: 1em;
  line-height: 1.4;
}

Both post date and title have been left-floated. The post title doesn't actually need to have a stated width, so here browsers will apply the shrink-to-fit algorithm, thus assigning to the floated element only the space necessary to host its contents. Instead, our date needs to be dimensioned, since our background image is 79 x 80 pixels. Further, we want the date text appear horizontally and vertically centered inside the image, so we specify an height of 50 pixels and then we add 30 pixels of top padding so that the overall height of our block will be exactly 80 pixels.

But there's a catch: since our elements are floats and there's no container element for them, we need to clear all subsequent paragraphs. To avoid bugs in Internet Explorer 6 and 7 (especially those related to the correct calculations of collapsing margins on cleared elements), we've actually zeroed the top margin of paragraphs, using top padding with a similar value. You can see the final result below.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.