开发者

CSS selector to apply rules to an element if before another element

开发者 https://www.devze.com 2023-01-10 11:15 出处:网络
I\'m looking for a way to apply some CSS to elements differently, depending on what follows it.For example, with this HTML:

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.


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 */ }


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')
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号