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
- Through the class for the corresponding element. Just add the class to your markup manually.
- The
nth-child
pseudonth-child
and the like, if appropriate. -
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 theorder
property.Let's say there are elements
first
andsecond
. And you need to add a selector whenfirst
beforesecond
. To do this, you need to swap them, then apply thesecond + first
selector.First way (preferred): Then assign
flex-direction: row-reverse;
to the containerflex-direction: row-reverse;
orflex-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 thanfirst
:.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>
-
Through JavaScript. Adding a class or CSS properties via JavaScript.