Reputation: 9721
Is there a way of adding CSS rules to an element only if it has an certain child element ? I do know it is not possible to do it with CSS, but I'm not sure if it is possible to do it with LESS.
Upvotes: 6
Views: 7065
Reputation: 930
in 2022 you don't need JS or jQuery to add styles, as is clearly visible from Curtis' earlier answer. to conditionally add the desired CSS (declarations, not rules!) to the parent the CSS file would contain rule like this for example:
.parent:has(li){
/* your CSS declarations to apply */
font-family: my-font;
}
pseudocode: "if .parent has a list-item make parent use my-font"
Upvotes: 0
Reputation: 103388
This isn't possible in CSS or LESS.
I would suggest your best bet is jQuery.
If your parent element is .parent
and your child is .child
, you could do:
$('.parent:has(.child)').addClass('myClass');
See Example: http://jsfiddle.net/d8Lz5/
Upvotes: 5
Reputation: 58611
If it is not possible with CSS, then it is not possible with LESS, which compiles to plain old vanilla CSS.
The problem is, that the LESS is compiled without knowledge of the HTML it is applied to, and without any client side scripting. Therefore, it is impossible to achieve anything with LESS that can not be achieved by using CSS alone.
You could achieve what you want by using client side javascript, or you could wait until CSS4 comes out, and use the parent selectors to the same effect as what you want.
Upvotes: 7