Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if parent has class using LESS

Tags:

css

sass

less

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?

like image 207
Adam Waite Avatar asked Jan 16 '13 12:01

Adam Waite


People also ask

How do you know if a parent element has a class?

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.

How do you refer to a parent in nested rules inside less?

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() CSS pseudo class?

: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.

Can you target a parent in CSS?

There is currently no way to select the parent of an element in CSS, at least not a way that works across all browsers.


1 Answers

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 {     ... } 
like image 135
zzzzBov Avatar answered Oct 17 '22 10:10

zzzzBov