Wednesday, April 2, 2008

HTML/CSS text shadows

I was trying to do a quick HTML/CSS shadow the other day. It happens often you need a noticeable title to specify what the page is doing if it is not too complex (i.e. you have enough space). I just wanted a simple shadow behind it.

It is quite simple, here:

<html>
<head>
<title>Shadow text example</title>
<style>
#title {
position: relative;
}

h1.clear, h1.primary, h1.shadow {
font: 56px Arial;
font-weight: bold;
font-style: italic;
padding-bottom: 20px;
margin: 0px;
}

h1.primary, h1.shadow {
text-decoration: underline;
color: #dda020;
position: absolute;
}

h1.shadow {
color: #808080;
left: 3px;
top: 3px;
}

#other_content {
position: relative;
}
</style>
</head>
<body>
<div id="title">
<h1 class="shadow"><nobr>Sudoku solver</nobr></h1>
<h1 class="primary"><nobr>Sudoku solver</nobr></h1>
<h1 class="clear">&nbsp;</h1>
</div>
<div id="other_content">More content goes here...</div>
</body>
</html>

Take a look here.

Here you have a few elements:
  • div#title - This is the element that represents the title. It contains three children:
    • h1#shadow - The shadow of the title,
    • h1#primary - Primary text of the title. This one and the previous one should have the same text in them,
    • h1#clear - The clearing element,
  • div#other_content - The other content that follows the title.

The h1#primary is the text that is displayed and it should be made as a normal text without a shadow - set its color or whatever else to your preferences. Shadow should probably only change the color and the "depth", as was done above. The clearing element is there only to give the size to the div#title. The reason is that whenever you do a position: absolute on the element, it will get out of the normal flow of elements. This also means that its size will not affect the size of the other elements, including its parent.

The clearing element is a fake element with only one non-breaking space. This space makes it high as the other two (primary and shadow). All three elements have the same font, padding and margin settings, so they will occupy the same space. The nobr elements are there to make the width appropriate. Otherwise, if you shrink the width of the browser, it will break the text, so the single space in the clearing element will not be high enough to allocate the space for the other two.

There are other solutions - one of them is, for example, this one. I liked this one because it works with the layout of the HTML elements.