tags:

views:

33

answers:

2

I'm looking for a way to apply some CSS to elements differently, depending on what follows it. For example, with this HTML:

<ul>
  <li>
    <span class="title">Some Title</span>
    <span class="subtitle">With Some Subtitle</span>
  </li>
  <li>
    <span class="title">Only a Title</span>
  </li>
</ul>

I want to apply different rules to .title depending on wether or not there is a .subtitle.

The closest I can figure out is the adjacent sibling selector

.title + .subtitle { /* rules */ }

But that applies the rules to the .subtitle elements that are preceded by a .title. Instead I want the rule to apply to .title elements with a .subtitle element after it.

NOTE: it's not vital this is widely supported by browsers for my current usage. My only target that matters is webkit based at the moment.

+4  A: 

There's no sibling-combinator for "older" siblings in the CSS3 spec.

In this case, you might be able to get away with :only-child.

li > span.title:only-child { /* rules */ }
Patrick McElhaney
This works in this particular case. Thanks. Though it would be pretty awesome if that qualified selector actually worked.
Squeegy
Sneaky selector. I like it.
jessegavin
+1  A: 

I think this would require backtracking in the layout engine and thus isn't available. you could do this in jQuery rather simply however:

$('span.title + span.subtitle').prev().addClass('cssClass')
Scott Evernden