Alternate text colors with CSS
August 7th, 2008
When I was redesigning this site, I was experimenting many different options for the header. Among the whole set of solutions I tried, I was very happy with the one I’m going to illustrate even though I chosen another one (that is the one you can see now) because it integrates better with the the whole layout.
What I wanted to achieve was basically this:

I thought at various techniques on how to realize that: fixed image, text with alternated background, experiments with PNG transparency, ecc…. All of these things have their pros and cons, but in the end I came up with a simple solution that required just few lines of CSS code and had few cons (in respect to the others).
Let see how I did it. First of all, we need a container for our text. I used a div on the which I set the text id. In #text we’re going to put our text. We’ll use absolute positioning within the div, so #text has to have position: relative set.
Next, we need two spans with the same text within; on these we’re going to set the absolute positioning I said before, setting top: 0; left: 0; on them. And now here is how the trick works. By having absolute positioned the two spans and having put them at the same coordinates (with the same font size), they’re going to overlap each other. Thanks to absolute positioning we can set the height on the spans, and this is the core of the trick, since to make it work we’ll have to set the first span’s height to half the height of the second span.
But that’s not all. If we stop here nothing will work. We also have to use overflow: hidden and z-index: 1000 on the first span. Just as side note, 1000 is not really a mandatory value for z-index, you can use even 1 but 1000 is pretty standard if you want that the class is always on the top.
In this way this is the final result. I really like it but cannot implement on this design as doesn’t integrates well the whole layout. Anyway, it has some cons: you have to manually tweak the font-size and height’s values as it’s not possible to use relative sizes and your code is going to have the text repeated twice, though this can be easily fixed with a bit of javascript.
I tested this under Firefox 3.0.2, Explorer 7, Opera 9.25 and Safari 3.1.2 and it works without any hack though I’m quite sure that it’s going to have some issues with older versions of Explorer.