使用精灵图显示日期

Avatar of Chris Coyier
Chris Coyier

DigitalOcean 为您旅程的每个阶段提供云产品。立即开始使用 200 美元的免费额度!

LearningjQuery.com 对其博客文章的日期进行了非常酷的展示。查看一下

字体和垂直显示的年份应该立即让您想到使用了图像来实现这一点。但请注意,日期信息以文本形式显示在标记中,正如它应该的那样。

在 Firebug 中快速查看一下,就能发现其简洁之美!

精灵图的最佳实践

希望很明显的是,每个日期都没有自己独特的图形。日期是从单个图形(css 精灵图!)中拼凑而成的,其中图形的不同较小部分显示在三个不同的区域:日、月和年。也许您会从 Joost de Valk 几乎一年前发布的类似技术 中认出这一点。

看看这个美丽的例子

HTML 代码

最终的 HTML 代码将类似于这样

<div class="postdate">
        <div class="month m-06">Jun</div>
        <div class="day d-30">30</div> 
        <div class="year y-2009">2009</div> 
</div>

我们有一个包装器和三个区域。这为我们提供了匹配这些示意图所需的内容

在 WordPress 等 CMS 中,生成该代码的后端代码将类似于这样

<div class="postdate">
        <div class="month m-<?php the_time('m') ?>"><?php the_time('M') ?></div>
        <div class="day d-<?php the_time('d') ?>"><?php the_time('d') ?></div> 
        <div class="year y-<?php the_time('Y') ?>"><?php the_time('Y') ?></div> 
</div>

CSS 代码

CSS 是精灵图真正发挥作用的地方。使用我们在 HTML 中设置的这些特殊类名,我们可以设置要使用的图像的哪些部分。

首先,我们在父元素上设置相对定位。然后我们在其中绝对定位这三个区域中的每一个。我们设置所有三个区域都使用相同的背景图像(我们的精灵图),设置它们各自的宽度和高度,并将文本移出页面。

然后,我们设置每个月(12 种可能性)、日(31 种可能性)和年(向后延伸 10 年),并使用显示所需特定区域所需的特定背景定位。

.postdate {
  position: relative;
  width: 50px;
  height: 50px;
  float: left;
}
.month, .day, .year { 
  position: absolute; 
  text-indent: -1000em;
  background-image: url(/wp-content/themes/ljq/images/dates.png);
  background-repeat: no-repeat;
}
.month { top: 2px; left: 0; width: 32px; height: 24px;}
.day { top: 25px; left: 0; width: 32px; height: 25px;}
.year { bottom: 0; right: 0; width: 17px; height: 48px;}

.m-01 { background-position: 0 4px;}
.m-02 { background-position: 0 -28px;}
.m-03 { background-position: 0 -57px;}
... more like this ...

.d-01 { background-position: -50px 0;}
.d-02 { background-position: -50px -31px;}
.d-03 { background-position: -50px -62px;}
... more like this ...

.y-2006 { background-position: -150px 0;}
.y-2007 { background-position: -150px -50px;}
.y-2008 { background-position: -150px -100px;}
... more like this ...

尽情享受吧!