简体   繁体   中英

CSS Select Sibling of An Element with A Specific Sub-Element?

The snippet below is a part of a much larger structure with many .step elements.

I need to match all .stepText elements that are next to .stepTitleAndImages ul.standard

In other words, match all .stepText elements that have .step parent that has .stepTitleAndImages child that has .stepImages.standard child

<div class="step">
  <div class="stepTitleAndImages">
    <h3 class="stepTitle"></h3>
    <ul class="stepImages standard"></ul>
    <div class="clearer"></div>
  </div>
  <div class="stepText "></div>  **HOW TO SELECT ALL ELEMENTS LIKE THIS ONE?**
  <div class="clearer"></div>
</div>

<div class="step">
  <div class="stepTitleAndImages">
    <h3 class="stepTitle"></h3>
    <ul class="stepImages medium"></ul>
    <div class="clearer"></div>
  </div>
  <div class="stepText "></div>
  <div class="clearer"></div>
</div>

PS: I cannot modify the HTML. Cannot use anything other than pure CSS.

Just use this for selecting first case

.step:nth-child(1) .stepText {
... Your CSS here
}

For second one use

.step:nth-child(2) .stepText {
... Your CSS here
}

For selecting both use

.step .stepText {
... Your CSS here
}

Then you should require jquery for that

Selecting Parents sibling is not possible only with pure CSS yet, You can achieve this by a single line of jquery:

$('ul.standard').parent().siblings(".stepText").css(...your CSS here);

This cannot be done with your HTML structure and with pure CSS. The closest solution to your problem, changing the HTML structure and with pure CSS, would be to move the standard class to its parent tag:

<div class="stepTitleAndImages standard"> <h3 class="stepTitle"></h3> <ul class="stepImages"></ul> <div class="clearer"></div> </div>

This would allow you to use the adjacent sibling selector ( + ), which matches the second selector if it's the direct next sibling of the first , like this:

.stepTitleAndImages.standard + .stepText { /* Styles */ }

A more flexible approach would be to use the general sibling selector which would match any sibling preceded by the first selector , not only the direct next one:

.stepTitleAndImages.standard ~ .stepText { /* Styles */ }

The :has pseudo-class is in development by Mozilla , but it hasn't hit any stable browsers yet. With it, and with your HTML structure, you could go:

.stepTitleAndImages:has(.standard) + .stepText { /* Styles */ }

Unfortunately, currently you can't solve this in any other way with CSS (and with your HTML structure) only.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM