user2726041
user2726041

Reputation: 359

LESS: Target a parent element if it exists

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;
}

Upvotes: 4

Views: 9710

Answers (1)

chazsolo
chazsolo

Reputation: 8484

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;
}

Upvotes: 6

Related Questions