CSS classes and Wordpress

While developing a simple Wordpress theme, I was struck (literally) by the fact that the documentation on CSS and Wordpress is lacking of some of the most essential parts of CSS development. One question really needs an answer: how can CSS work together with a dynamic environment like Wordpress? CSS is a static language because it was designed when the web was made up of static HTML pages. CSS has no conditional statements, if we don't consider the newest features of @media rules as conditional constructs. Let's try to answer to this question.

The return of classitis?

Let's face it: without CSS classes, you can't write a good stylesheet for Wordpress. This happens because a Wordpress theme is not only made up by simple and predictable page elements, but also by third-party additional gadgets, widgets, plugins and, what's more, user-defined code.

Writing down all the possible use cases is practically impossible. That's why CSS classes are so useful: they allow you to write generalized styles that can be applied to a wide variety of possible scenarios.

Without classes, you cannot handle third-party elements. For example:

div.widget {

  margin-top: 1em;
  margin-bottom: 1em;


Now let's say that you have a plugin that installs a list of popular posts. You may have the following final markup:

 <div class="widget custom-widget"></div>

You launch your site and you notice that the list is not centered. With classes, you have just to write this:

div.custom-widget {
  width: 200px;
  margin-left: auto;
  margin-right: auto;

The final result will be a list of links vertically spaced and horizontally centered. The same base class, widget, can also be applied to many other custom plugins and widgets.

Classes allow you to add per-page styles. Now you may say: "Wait a minute, and the body#id technique?". Well, this technique is surely useful when you have a static site with just a few pages. But what happens when you have dozens pages and you have to choose an ID for each page? This will surely get you mad, because it's something that's quite difficult to handle in a live production environment.

So you can write something like this:

  <body class="home alternate-banner xmas"></body>

that can be used to add some special styles just for the Christmas time:

body.xmas {
  background-color: #c00;

body.alternate-banner.xmas #header {
  background: url(images/santa-claus.jpg) no-repeat;

To sum up: classes are not bad when you need them. They're bad only when you have a simpler choice.

Leave a Reply

Note: Only a member of this blog may post a comment.