4

So I have a box:

<div class="box">Box</div>

And sometimes this box may be wrapped in an a tag:

<a href="#"><div class="box">Box in an A tag</div></a>

Is there a way in LESS to specifically target A tags that are parents of .box?

e.g.

a {
   color: red;
}

a [that is a parent of .box] {
   color: blue;
}
seven-phases-max
  • 11,765
  • 1
  • 45
  • 57
user2726041
  • 359
  • 4
  • 20

1 Answers1

6

No, you cannot select ancestor elements using LESS or CSS, but LESS has what is called the parent selector, or &.

The & operator represents the parent selectors of a nested rule and is most commonly used when applying a modifying class or pseudo-class to an existing selector

So, in your case, instead of changing the color of the parent, you could use & to target instances of .box that have an a parent, e.g.

.box {
  color: red;

  a & {
    color: blue;
  }
}

This translates to:

.box {
  color: red;
}
a .box {
  color: blue;
}
Community
  • 1
  • 1
chazsolo
  • 7,873
  • 1
  • 20
  • 44
  • What is there are more deeply nested structures such as there are great-grandparent where `div`s are nested inside of `span` element where `span` element is nested inside of `div` element? How do you target those using LESS? Thank you in advance. – NikolaS Aug 09 '21 at 14:02