James Donnelly James Donnelly - 2 months ago 12
Less Question

Apply a tag selector to the immediate parent of a rule within a deeply-nested structure

There are a couple of similar questions I've found (like How to specify a html tag on a LESS CSS nested class?), but none of them seem to work for rules nested more than one level deep.

Here's the structure I have:

article {
.foo {
...
}
}


Here,
.foo
can be one of many different types of element. For the sake of this question, lets say that one of these elements is the
a
element. I'm wanting to extend the above structure to select the
.foo
element whose tag is specifically
a
from within the
.foo
rule.

The problem with the answer on the question I've linked to above, and the various other similar questions, is that the following will not work:

article {
.foo {
a& { ... }
}
}


Instead of prefixing the
.foo
with the
a
tag, like this:

article a.foo { ... }


...the entire chain gets prefixed:

aarticle .foo { ... }


(Here's a live example).

How can I target
.foo
elements whose tag is
a
within the
.foo
rule?

Answer

Looks like you're getting tangled up in wanting ├╝ber-optimized LESS. If I understand correctly, either way your compiled CSS will be

article .foo {
    general `article .foo` styles
}
article a.foo {
    additional styles specific to `article a.foo`
}

In LESS you could write that as is, or you could do

article {
    .foo {
        general `article .foo` styles
    }
    a.foo {
        additional styles specific to `article a.foo`
    }
}

or depending on your styles you might be able to do

article .foo {
    general `article .foo` styles
}
a.foo {
    additional styles specific to `a.foo`
}