Example scenario: I would like to hide a sub-navigation menu if the user has javascript enabled so that it can be revealed on a click of a navigation link further up in the nav hierarchy. Modernizr adds a class 'js' to the html tag if javascript is enabled so I can use that for detection.
In SASS I can do something like this:
div.subnav{ display: block; html.js & { display: none; } }
Can this be done using LESS? Can I target a parent from within another rule?
Use the parentElement property to select the parent of the element. Use the classList. contains() method to check if the parent contains the class. The method returns true if the element's class list contains the class and false otherwise.
It is possible to reference the parent selector by using the &(ampersand) operator. Parent selectors of a nested rule is represented by the & operator and is used when applying a modifying class or pseudo class to an existing selector.
:has() The :has() CSS pseudo-class represents an element if any of the selectors passed as parameters (relative to the :scope of the given element) match at least one element.
There is currently no way to select the parent of an element in CSS, at least not a way that works across all browsers.
Can this be done using LESS?
Yes.
The code you provided works in LESS. The & combinator
works the same.
In the end, the selectors generated for:
div.subnav { ... html.js & { ... } }
will be:
div.subnav { ... } html.js div.subnav { ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With