Last week I found I neat use of the :empty CSS3 selector to easily style elements that
are next to elements that sometimes are empty.
During the week we've implemented a lot of design work for our new Backbone
powered application at work. The application has a couple of views, with a
tabbed navigation. The layout contains of a left-oriented sidebar and a main
container for main content. Some views take use of the sidebar and fill it with
data while others don't.
By using the :empty selector we were able to adjust the right margin of
the main content container depending on if we had any data in the sidebar or
not. The container needs a margin since we are absolute positioning the sidebar
to make sure it takes up the full vertical space in the viewport.
The selector we use looks like this:
.sidebar:empty + #content {
/* Rules that should apply to the
main content container when
the sidebar is empty go here
*/
}
What the selector actually does is selecting elements with the id content that
follow an empty element with the class sidebar. The '+' is called the adjacent
sibling selector, read more here.
Inside this block we are able to apply rules to the #content element, i.e its
margin-left should not make room for the sidebar.
The caveat is that :empty is not supported in Internet Explorer versions below 9,
read more about support at www.caniuse.com.
Lucky for us, this application is not open to the public and therefore we are able
to require users to use IE9+ or other modern browsers.