带有串联选择器 (&-) 的较少扩展功能不起作用

标签 less extend

我想用 LESS 做一些事情,但它没有按我想要的方式工作。 我有这个代码:

.pl, #pl {
    &-logo {
        max-width: 100%;
        height: auto;

        &-test1:extend(.pl-logo) {
          background-image: url('url');
        }

        &-test2:extend(.pl-logo) {
          background-image: url('url');
        }

        &-test3:extend(.pl-logo) {
          background-image: url('url');
        }
    }
}

但它不起作用,我只是:

.pl-logo, #pl-logo {
    max-width: 100%;
    height: auto;
}

.pl-logo-test1, #pl-logo-test1 {
    background-image: url('url');
}

.pl-logo-test2, #pl-logo-test2 {
     background-image: url('url');
 }

.pl-logo-test3, #pl-logo-test3 {
   background-image: url('url');
}

相反:

.pl-logo, .pl-logo-test1, .pl-logo-test2, .pl-logo-test3, #pl-logo {
    max-width: 100%;
    height: auto;
}

.pl-logo-test1, #pl-logo-test1 {
    background-image: url('url');
}

.pl-logo-test2, #pl-logo-test2 {
     background-image: url('url');
 }

.pl-logo-test3, #pl-logo-test3 {
   background-image: url('url');
}

我认为 LESS 更具进化性,是我的代码错误还是 LESS 无法正确编译?

还有其他方法可以实现我想要的功能吗?

谢谢

最佳答案

正如 Harry 已经明确指出的,您不能扩展动态形成的选择器和 How do I extend a class/mixin which has dynamically formed selector将为您提供一些解决方案。

或者,您可以尝试更改 HTML 并使用两个类:.pl-logo、#pl-logo 基类和 test* 样式类:

< class="pl-logo test2">

现在您可以使用以下 Less 代码:

.pl, #pl {
    &-logo {
        max-width: 100%;
        height: auto;

        &.test1 {
          background-image: url('url');
        }

        &.test2 {
          background-image: url('url');
        }

        &.test3 {
          background-image: url('url');
        }
    }
}

上面的内容编译成 CSS 如下:

.pl-logo,
#pl-logo {
  max-width: 100%;
  height: auto;
}
.pl-logo.test1,
#pl-logo.test1 {
  background-image: url('url');
}
.pl-logo.test2,
#pl-logo.test2 {
  background-image: url('url');
}
.pl-logo.test3,
#pl-logo.test3 {
  background-image: url('url');
}

上面的.pl-logo.test1表示同时拥有pl-logotest1类。 (#pl-logo.test1 具有 id=pl-logo 和 class=test1,请参阅:How to combine class and ID in CSS selector?)

或者当您无法更改 HTML 使用属性选择器时:

    [class^="pl-logo-"], [class*=" pl-logo-"], [id^="pl-logo-"], [id*=" pl-logo-"] {
                max-width: 100%;
                height: auto;
        }
.pl, #pl {
    &-logo {
        &.test1 {
          background-image: url('url');
        }

        &.test2 {
          background-image: url('url');
        }

        &.test3 {
          background-image: url('url');
        }
    }
}

关于带有串联选择器 (&-) 的较少扩展功能不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30045107/

相关文章:

css - CSS 中的变量——为什么不能使用它们?

css - LESS/是否可以扩展嵌套自身的最近祖先?

python - 用 swig 和 python 扩展全局 c 变量数组

css - 如何扩展 Bootstrap ​​类

php - 何时实现和扩展?

css - 覆盖更少的mixin

css - 如何在 LESS 中转义 html 字符?

css - 当参数作为空白发送时,如何避免输出中出现 ' '?

Javascript,简单的扩展方法,允许扩展对象的多个版本

php - 在 PHP 中扩展一个类