Posts Tagged ‘CSS’

The best CSS selector you’re not using

Wednesday, February 18th, 2009

Update (again): I had initially uploaded a jQuery based fix to get this selector working in IE6, but Emil Bjorklund pointed out that Dean Edwards’ IE7.js also fixes the issue, so I would recommend using that script to get the selector to work in IE6.

Recently, we’ve been making substantial use of a CSS selector that I stumbled on almost accidentally in the w3c docs: the “~=” selector, which can more compatibly be written simply by separating class names with a dot (and no spaces) . It’s certainly no secret, but I haven’t seen it in use much, and that’s a shame because it lends itself to some really clever and intuitive CSS. Here’s the definition for the selector:

Matches any E element whose “foo” attribute value is a list of space-separated values, one of which is exactly equal to “warning”.

It doesn’t sound too interesting, but what we’ve found is that it lets us use very intuitive, almost straight English syntax for our css classes by daisy chaining class names in a logical order.

Consider the situation where your template has a main content area, sometimes with a sidebar, sometimes without. There are plenty of ways to handle this fairly simple problem in CSS, but I’m finding the most elegant solution to be the following:

.main_column {
    min-height: 300px;
}

div.main_column.with_sidebar {
    float:left;
    width: 690px;

}

Now, when our main column needs a sidebar, we can do:

<div class="main_column with_sidebar">
<!-- Content here will be floated left -->
</div>

Why is this better than just defining “.with_sidebar”? Because it may be the case that two different classes (maybe “main_column” and “page_content”) both support a “with_sidebar” version that applies different width & floats depending on which class it’s being applied to. (“main_column .with_sidebar” won’t work because “with_sidebar” is not a descendant class of main_column.)

Taking it a step further, let’s add a green background:

div.main_column.and_green_background {

background-color: green;

}

now, how about:

<div class="main_column with_sidebar and_green_background">
<!-- Content here will be floated left with a green background -->
</div>

Again, there’s nothing here that can’t be solved in other ways, but I just wanted to introduce other people to this oft overlooked selector which, in my opinion, allows for very clever, elegant CSS.