Section styling

If you use HTML5 section elements to structure content groupings on a page, and every level in the structure has a h1 heading, how do you style each heading level?

In the previous post, Structural engineering, I wrote that through the magic of the section element, you can make a browser grasp the structure of your document. Using section elements also allow each level in the structure to have a h1 heading. For example, the items in the following outline can all have h1 headings:

The Daily Planet
   News
      Local news
      National news
      International news
   Sports

Now say you want different styles for each heading level. The h1 type selector is obviously a no-go:

h1 {
   style declarations
}

You could use the section type selector with descendent selectors, but then you get CSS like this:

section h1 {style declarations}
section section h1 {style declarations}
section section section h1 {style declarations}

It leaves a bad taste in the mouth. The HTML5 spec discourages using semantic elements like section for styling purposes. Nicole Sullivan at stubbornella.org gives a good overview of the issue. She also suggests that that way coding madness lies. See this scary CSS example.

Another solution is to define and apply heading classes to h1 elements:

<h1 class="head1">
...
<h1 class="head2">
...

This is fine if you don’t have too many heading elements on your page. If you’re using section elements, you probably have lots of them. It also assumes you can edit the heading elements. Some content groupings may be syndicated and come with their own heading elements.

I think the best solution is to define and apply classes to the section elements instead of the h1 elements:

<section class="level1">
...
<section class="level2">
...

You can use descendent heading selectors with the classes to style the headings:

.level1 h1 {
   style declarations...
}

.level2 h1 {
   style declarations...
}

The fact the class names help you parse nested section elements in your markup is gravy.