CSS: advanced heading styles

After setting fonts, colors and vertical margins on headings, we'd like to get more advanced styles for this kind of elements. In this post I'm going to show you how to achieve this result with a minimum effort. Advanced styles include background images and negative indentation, the latter for creating the effect of hanging headings. But first things first. Let's draw a basic HTML structure to work with.

<div id="main">
  <div class="post">
    <h2>...</h2>
    <small class="date">...</small>
    <!--paragraphs-->
    <h3>...</h3>
    <!--paragraphs-->
    <h4>...</h4>
    <!--paragraphs-->
  </div>
  <!--more posts-->
</div>

First of all, we need to define our global styles:

body {
 margin: 0;
 padding: 2em 0;
 background: #a0a0a0;
 color: #333;
 border-top: 1em solid gray;
 font: 76%/1 Verdana, sans-serif;
}

h2, h3, h4 {
 font-size: 100%;
 margin: 0;
}

p {line-height: 1.4;}

The font size of headings has been normalized to 100%. This is important because it prevents browsers from applying their calculations on font sizing. Note that also the vertical margins of headings have been reset. Now let's move to the h2 element:

div.post h2 {
 font: normal 2.5em Impact, "Arial Black", sans-serif;
 letter-spacing: 0.1em;
 background: url(img/note.gif) no-repeat 0 0;
 padding: 5px 105px 15px 55px;
 color: #a40;
 position: relative;
 left: -15px;
 height: 100%;
 text-transform: uppercase;
}

We've set a background image on the left edge of this heading. To make room for the image, we did need a left and bottom padding proportional to the actual size of the image. The declaration height: 100% is used here only to avoid some problems with IE 7 and lower. Further, the heading has been pushed leftwards thanks to the negative relative positioning specified on this element. Now we can move to the other headings:

div.post h3, div.post h4 {
 padding-bottom: 5px;
 font-family: "Trebuchet MS", Trebuchet, sans-serif;
 color: #555;
 position: relative;
 left: -10px;
}

div.post h3 {font-size: 1.6em;}
div.post h4 {
  font-size: 1.4em;
  text-transform: uppercase;
}

We use negative relative positioning again to create the effect of an hanging heading. This is due to the fact that IE 6 has a poor support to negative text indentation. You can see a demo below.

Demo

Live demo

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.