David Refoua
David Refoua

Reputation: 3617

Should I use a `&` when selecting direct children using `>`?

While writing less, I noticed that the following two snippets:

A.

.parent-el {
   & > .direct-child { ... }
}

B.

.parent-el {
   > .direct-child { ... }
}

will produce exactly the same css:

.parent-el > .direct-child {
   ...
}

 

I have several questions:

Upvotes: 1

Views: 76

Answers (2)

mmshr
mmshr

Reputation: 947

Are there any differences between A and B?

There will be no difference in the compiled CSS. The & in LESS is replaced with the outer selector in compiled CSS. So, A is really the same as doing:

.parent-el {
    .parent-el > .direct-child { ... }
}

This, of course, is redundant and defeats the purpose of using LESS in the first place.

Is this intentional and by design?

The & really is not used as I believe it was intended in your example. A good example of using a & in LESS would be something like this:

.parent-el {
    // define .parent-el styles
    &__child { 
        // define .parent-el__child styles
    }
}

In the above example, the & allows you to shorten the declaration of .parent-el__child.

Which one should I use, and why?

You should use B. In this case, using the & is redundant and unnecessary.

Upvotes: 1

TheDev
TheDev

Reputation: 415

the use of the "&" is optional, when you insert the selector inside another becomes implicit that the intention is to start from your "parent".

Although I get less code when we do not use "&" I prefer to use it because the code is cleaner

Upvotes: 0

Related Questions