简体   繁体   中英

How do I select previous siblings before specific class?

My react app is creating a list of steps:

let steps = this.props.formSteps.map((step, i) => {
            let stepNum = i +1;
            return (
                <li className={ i == this.props.currentStepsIndex ? "steps__step active" : "steps__step"} key={"li-"+i}
                 onClick={this.handleClick.bind(this, i)}>
                  {step.name}
                </li>
            );
})
return(
  <div className="steps-container">
    <ul className="steps">
      {steps}
    </ul>
  </div>
);

With 3 steps, the generated html looks something like this:

<ul class="steps">
  <li class="steps__step">Step 1</li>
  <li class="steps__step">Step 2</li>
  <li class="steps__step active">Step 3</li>
</ul>

I want to select all the previous li steps before the active class and set the background to like green or something.

How do I accomplish this using css?

You may do something like this. You invert the logic and you select all next sibling to remove the background:

 .steps__step { background:green; } .active, .active ~ .steps__step { background:none; } 
 <ul class="steps"> <li class="steps__step">Step 1</li> <li class="steps__step">Step 2</li> <li class="steps__step active">Step 3</li> <li class="steps__step">Step 4</li> <li class="steps__step">Step 5</li> </ul> 

I am not aware of any css selectors for sibling elements that come before a specific sibling. However, in your specific case you might get the desired result by selecting the elements without the "active" class.

Something like:

.steps__step:not(.active) {
   background-color: green;
}

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