仅当元素具有特定子元素时才向其添加规则

时间:2022-08-22 14:11:47

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.

是否有一种方法只有在元素具有某个子元素时才将CSS规则添加到元素中?我知道用CSS做不可能,但我不确定是否可以用LESS做到这一点。

2 个解决方案

#1


4  

If it is not possible with CSS, then it is not possible with LESS, which compiles to plain old vanilla CSS.

如果使用CSS是不可能的,那么LESS是不可能的,它编译为普通的旧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.

问题是,编译LESS时不知道它应用的HTML,也没有任何客户端脚本。因此,单独使用CSS无法实现LESS无法实现的任何功能。

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.

你可以通过使用客户端javascript实现你想要的,或者你可以等到CSS4出来,并使用父选择器达到你想要的效果。

#2


5  

This isn't possible in CSS or LESS.

这在CSS或LESS中是不可能的。

I would suggest your best bet is jQuery.

我建议你最好的选择是jQuery。

If your parent element is .parent and your child is .child, you could do:

如果你的父元素是.parent而你的孩子是.child,你可以这样做:

$('.parent:has(.child)').addClass('myClass');

See Example: http://jsfiddle.net/d8Lz5/

参见示例:http://jsfiddle.net/d8Lz5/

#1


4  

If it is not possible with CSS, then it is not possible with LESS, which compiles to plain old vanilla CSS.

如果使用CSS是不可能的,那么LESS是不可能的,它编译为普通的旧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.

问题是,编译LESS时不知道它应用的HTML,也没有任何客户端脚本。因此,单独使用CSS无法实现LESS无法实现的任何功能。

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.

你可以通过使用客户端javascript实现你想要的,或者你可以等到CSS4出来,并使用父选择器达到你想要的效果。

#2


5  

This isn't possible in CSS or LESS.

这在CSS或LESS中是不可能的。

I would suggest your best bet is jQuery.

我建议你最好的选择是jQuery。

If your parent element is .parent and your child is .child, you could do:

如果你的父元素是.parent而你的孩子是.child,你可以这样做:

$('.parent:has(.child)').addClass('myClass');

See Example: http://jsfiddle.net/d8Lz5/

参见示例:http://jsfiddle.net/d8Lz5/