Bootstrap 3 with LESS: how to handle bootstrap's nested rules?

时间秒杀一切 提交于 2019-11-27 16:18:30

In the first place i will agree with the comment of @seven-phases-max, but i think i can explain your problem with the :extend pseudo class.

If you take a look into Bootstrap's less/form-groups.less file, you will find the following code:

.input-group-lg > .form-control,
.input-group-lg > .input-group-addon,
.input-group-lg > .input-group-btn > .btn {
  .input-lg();
}

The preceding code mean that the .input-group-lg > .input-group-btn > .btn child combinator will be compiled in your CSS too.

Now consider the following example Less code and consider that when nested the extend() will be applied on all parents:

.class1 {
color:green;
> .class2 {
color:red;
}
}
div {
  > div {
        &:extend(.class2 all);
  }
}

Which will compile into the following CSS code:

.class1 {
  color: green;
}
.class1 > .class2,
.class1 > div > div {
  color: red;
}

In the above CSS the .class1 > div > div is not the selector you will need.

You can solve the above with the following Less code:

div {
  > div:extend(.class1 > .class2 all){}
}  

These Less code will compile into the following CSS code:

.class1 > .class2,
div > div {
  color: red;
}

This example show you that you also will have to find class relations compiled into Bootstrap's CSS and use them in your :extends(); these relation can easily change as already mentioned by @seven-phases-max.

Also notice that in the case that the example Less code also contains an .class2 which is not nested such as:

.class2 {
p:4;
}

The .class2 class will change you extended class to:

div {
  > div:extend(.class1 > .class2 all, .class2 all){}
}  

In your compiled CSS you will find the following code:

.class1 > .class2,
div > div,
.class1 > div > div {
  color: red;
}

Where the .class1 > div > div due to the .class2 all makes no sense. Also when the Less code contains other appearances of the .class2 for instance:

.class3 {
.class2 {
property: 4;
}
} 

The .class2 all in the :extend() will cause a lot of unwanted selectors.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!