css less 不要作用到子对象_less-css - 是否可以获取父级的父级?

Is it possible to get a parent's parent?

I tried & & { } but that didn't work.

I'm trying to style a child element based on it's grandparent.

解决方案

Depends on Code Structure, and may Require Some Repetition of Code

You cannot do it directly in most cases (see second example for exception).

If Grandparent is an element

This requires some repetition, but does allow for the grandparent to not be the outermost wrapper (so there could be a great grandparent).

LESS

grandparent {

/* grandparent styles */

parent {

/* parent styles */

child {

/* child styles */

}

}

&.specialGrandpa {

child {

/* child styles with special Grandpa */

}

}

&.specialGrandma {

child {

/* child styles with special Grandma*/

}

}

}

CSS Output

grandparent {

/* grandparent styles */

}

grandparent parent {

/* parent styles */

}

grandparent parent child {

/* child styles */

}

grandparent.specialGrandpa child {

/* child styles with special Grandpa */

}

grandparent.specialGrandma child {

/* child styles with special Grandma*/

}

If Grandparent is a class, ID, etc., and is the outermost wrapper

No repetition involved here, but you cannot have a great grandparent in the mix. Also this is only for LESS 1.3.1+ version (earlier version incorrectly add a space):

LESS

.grandparent {

/* grandparent styles */

.parent {

/* parent styles */

.child {

/* child styles */

.specialGrandparent& {

/* child styles with special grandparent*/

}

}

}

}

CSS Output

.grandparent {

/* grandparent styles */

}

.grandparent .parent {

/* parent styles */

}

.grandparent .parent .child {

/* child styles */

}

.specialGrandparent.grandparent .parent .child {

/* child styles with special grandparent*/

}

This code works by appending to the "front" of the grandparent selector, so that is why the grandparent must be a class, ID, or other selector itself.

Addendum

Based on comment about desire to have a red background when the span is empty. This does not put the background on the parent, but "fakes" it using the child.

span:empty:after {

content: '';

position: absolute;

top: -1px;

right: -10px;

left: -1px;

bottom: -10px;

display: block;

background-color: red;

z-index: -1;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值