css – Left Neighbor Selector

Question:

Faced a problem: you need to place a style for the neighbors that are to the left of the element. In my case, it is necessary to ul element element painted a red.

Here is my html code:

<ul>
  <li><a href="javascript://">Пункт 1</a></li>
  <li><a href="javascript://">Пункт 2</a></li>
  <li><a href="javascript://">Пункт 3</a></li>
  <li><a href="javascript://">Пункт 4</a>
      <ul>
        <li><a href="javascript://">Пункт 1</a></li>
        <li><a href="javascript://">Пункт 2</a></li>
        <li><a href="javascript://">Пункт 3</a></li>
        <li><a href="javascript://">Пункт 4</a></li>
      </ul>
  </li>
</ul>

Of course, my second menu has a position:absolute style and you can just do it like this:

ul > li > ul {position:absolute}
ul > li > ul ~ a {color: red}
<ul>
  <li><a href="javascript://">Пункт 1</a></li>
  <li><a href="javascript://">Пункт 2</a></li>
  <li><a href="javascript://">Пункт 3</a></li>
  <li><ul>
        <li><a href="javascript://">Пункт 1</a></li>
        <li><a href="javascript://">Пункт 2</a></li>
        <li><a href="javascript://">Пункт 3</a></li>
        <li><a href="javascript://">Пункт 4</a></li>
      </ul>
      <a href="javascript://">Пункт 4</a>
  </li>
</ul>

But it looks strange in html.

Sorry for such an idiotic question, of course, you can add some kind of class to items that have a second menu, but I would like to do without it

Answer:

It is not possible to select the previous neighbor using a selector using CSS . And even in the draft CSS4 at the time of writing, this is not possible.

So yes, only

  1. Through the class for the corresponding element. Just add the class to your markup manually.
  2. The nth-child pseudo nth-child and the like, if appropriate.
  3. Inverting the markup (placing items in reverse order in the markup) and applying flexbox.

    We can invert elements either through row-reverse / column-reverse or through the order property.

    Let's say there are elements first and second . And you need to add a selector when first before second . To do this, you need to swap them, then apply the second + first selector.

    First way (preferred): Then assign flex-direction: row-reverse; to the container flex-direction: row-reverse; or flex-direction: column-reverse; depending on the markup:

     .flex { display: flex; flex-direction: row-reverse; } .second + .first { color: red; margin-right: 10px; }
     <div class="flex"> <div class="second"> Second </div> <div class="first"> First </div> </div>

    Second way: Then we make the order second less than first :

     .flex { display: flex; } .second + .first { color: red; margin-right: 10px; } .second { order: 2; } .first { order: 1; }
     <div class="flex"> <div class="second"> Second </div> <div class="first"> First </div> </div>
  4. Through JavaScript. Adding a class or CSS properties via JavaScript.

Scroll to Top