2

Say I have the following

.selected {
  font-weight: bold;
}
.selected ~ div {
  color: red;
}
<div class="numbers">
  <div><p>1</p></div>
  <div><p>2</p></div>
  <div class="selected"><p>3</p></div>
  <div><p>4</p></div>
  <div><p>5</p></div>
</div>

Within these 5 divs, the position of the selected div may change (ie the user clicks something and now 2 is selected instead of 3), hence why I need these fancy CSS rules.

I can select divs that come after the selected element. How do I select divs that come before it?

I've tried something like .numbers div:not(.selected ~ div){}, but that doesn't seem to work.

snazzybouche
  • 2,241
  • 3
  • 21
  • 51

1 Answers1

5

You can't.

CSS stands for Cascading Style Sheet, and it's interpreted from top to bottom. And so is applied its rules.

You can't use CSS to change anything before the selected element. Not the parent, nor the previous siblings.

You'll need to use javascript to implement that functionality.

Phiter
  • 14,570
  • 14
  • 50
  • 84
  • That... makes a lot of sense.Thanks for clearing up my misunderstanding. Thanks to your answer, I was able to solve this by selecting all of the divs to have the property that only the ones before the selected should have, and then styling the selected and the divs after it to ignore that property. Many thanks. – snazzybouche Apr 23 '18 at 12:45
  • This [answer](https://stackoverflow.com/a/36118012/4802649) might be helpful, although I'd not recommend using that sort of hack. – Phiter Apr 23 '18 at 12:46