Be Good Not Bad by Brian Warren

16 June 2006

Using CSS to Style Dates

In a recent project on which I got the opportunity to work, I got to do some cool stuff to conquer some fun challenges. The site hasn’t launched yet, so no linky for you. (Update: The Site is MIOX.com. Update again: Apparently they redesigned. Boo.)

One fun challenge was in styling dates. On the front page of the site, we feature one entry from the news section and another from the company blog. The dates were styled in a fun way, so I thought I’d share how I did it in case anybody wanted to do the same.

The code for the date uses a definition list:

<dl class="post-date">
  <dt>May</dt>
  <dd>06</dd>
</dl>

So, first thing I did was use a background image for list. As well as width and height attributes.


.post-date {
 background: url(/graphics/date_blue.png) 0 0 no-repeat;
 width:47px;
 height:48px;
}

Awesome, that was easy. Let’s add some font styling.


.post-date {
 background: url(/graphics/date_blue.png) 0 0 no-repeat;
 width:47px;
 height:48px;
 font-weight:bold; 
 color:#fff; 
 text-align:center
}

Next we need to specify the font sizes of the month name and day.


.post-date dt {
 font-size:13px;
 }
.post-date dd {
 font-size:18px;
}

Lets add some margins in to move stuff around.


.post-date dt {
 font-size:13px;
 margin: 7px 0 0 0;
 }
.post-date dd {
 font-size:18px;
 margin: -4px 0 0 0; 
}

We used a -4px top margin in the day to tuck it in under the month just a little bit. Having them nice and close helps make it feel more like a calendar. You could also adjust the line-height to get it up in there.

with IE on the left, there is no shadow, with Safari on the right, you can see the text shadow Lastly, if you add a text-shadow to the list, you will get a classy looking little drop shadow behind the text. If used judiciously, the drop shadow can look really nice. The only problem is, very few web browsers currently apply the shadow. Not even Firefox does it. Safari, and other Webkit-based browsers, does render the shadow. It’s just a nice little touch that really caters to the designer in me.


.post-date {
 background: url(/graphics/date_blue.png) 0 0 no-repeat;
 width:47px;
 height:48px;
 font-weight:bold; 
 color:#fff; 
 text-align:center;
 text-shadow: #13708c 0 0 2px
}

That’s all there is to making really classy dates. Much easier than the alternative, which would be to create 12 different month images, and 31 different day images. Then write a script to output each image, spliced together, based on the date of the post. Yuck. This method is really much less yucky and really helps unleash the designer in you.