1

I want to access the anchor tags followed by ul elements only. I am using SCSS.

<ul>
 <li>
  <a href="#">Menu link 1</a>
  <ul><!--more code here --></ul>
 </li>
 <li>
  <a href="#">Menu link 2</a>
 </li>
 <li>
  <a href="#">Menu link 2</a>
 </li>
 <li>
  <a href="#">Menu link 1</a>
  <ul><!--more code here --></ul>
 </li>
</ul>
Manuel Abascal
  • 5,616
  • 5
  • 35
  • 68
  • Please check out this [Stackoverflow post](https://stackoverflow.com/a/1817801/4742088). You cannot target a previous sibling using CSS. – Helenesh Jan 29 '19 at 17:19

2 Answers2

2

Css only has backwards looking selectors, so it is not possible to do what your want. But there is an alternative solution that resembles your behavior closely, the last-child selector

In your case, you need to combine this with the :not() selector.

You will get:

a:not(:last-child) {
    background: lightblue;
}
<ul>
 <li>
  <a href="#">Menu link 1</a>
  <ul><!--more code here --></ul>
 </li>
 <li>
  <a href="#">Menu link 2</a>
 </li>
 <li>
  <a href="#">Menu link 2</a>
 </li>
 <li>
  <a href="#">Menu link 1</a>
  <ul><!--more code here --></ul>
 </li>
</ul>
Ferrybig
  • 18,194
  • 6
  • 57
  • 79
  • I tried this and I got the one of anchor tags selected. However, not all of them. Maybe I am doing something. I just want to select the anchor tag followed by an ul element to add a :after pseudo class to it and add a arrow image as background. I dont want that image on anchor that are not followed by an ul element. Maybe there is another way to accomplish this with CSS or jQuery? – Manuel Abascal Jan 29 '19 at 17:29
  • I updated the post, when I use the css rule, I get both the first and last entry, as those both have the `ul` element – Ferrybig Jan 29 '19 at 19:09
2

Several options for that:

  1. Using a double selector such :not(:last-child) increases a bit performance degradation. So you should better put your generic CSS for the case in which <a> is followed by <ul> and then use a:only-child to select and format the other case.
  2. Or you can put <ul> before <a>, then use Flexbox to change the order in the following way:

.parent, .parent ul{
  list-style: none;
  padding: 0;
}
.parent > li {
  display: flex;
  flex-flow: column nowrap;
  padding: 5px;
  border-bottom: solid 1px #ccc;
}
.parent ul {
  order: 2;
}
ul + a {
  color: red;
}
<ul class="parent">
 <li>
  <ul><li>dummy list item</li></ul>
  <a href="#">Menu link 1</a>
 </li>
 <li>
  <a href="#">Menu link 2</a>
 </li>
 <li>
  <a href="#">Menu link 2</a>
 </li>
 <li>
  <a href="#">Menu link 1</a>
  <ul><!--more code here --></ul>
 </li>
</ul>
Daniel Abril
  • 418
  • 3
  • 11