基于 CSS 类的 LESS 条件设置 LESS 变量

标签 less

我需要设置一个 Less 变量来匹配网站的事件主题,即每个主题都有不同的颜色。

我想根据定义主题的 HTML 主体 CSS 类将 @themeColor 设置为正确的颜色。

例如:

body.themeBlue { @themeColor: blue; }
body.themeRed { @themeColor: red; }

这样我只需要在其他 Less 文件中使用 @themeColor 变量。

任何人都可以帮忙吗?
根据这个( http://www.lesscss.org/#-scope )可以做这样的事情,但我不能让它工作。这里发生了什么?

最佳答案

LESS 文件无法读取应用于 html 的实际类 body元素在运行时(您可能需要实现一个 javascript 解决方案来执行类似的操作)。

如果您只想基于 body 准备好所有主题的 css 以供使用类,实现这一点的最佳方法是在 mixin 中包含所有必要的基于主题的 css,然后在主题类下应用它。这减少了代码重复。例如:


//mixin with all css that depends on your color
.mainThemeDependentCss() {
  @contrast: lighten(@themeColor, 20%);
  h1 {color: @themeColor;}
  p {background-color: @contrast;}
}

//use the mixin in the themes
body.themeBlue {
  @themeColor: blue;
  .mainThemeDependentCss();
}

body.themeRed {
  @themeColor: red;
  .mainThemeDependentCss();
}

CSS 输出
body.themeBlue h1 {
  color: #0000ff;
}
body.themeBlue p {
  background-color: #6666ff;
}
body.themeRed h1 {
  color: #ff0000;
}
body.themeRed p {
  background-color: #ff6666;
}

有关处理主题方面或方式的其他一些答案,请参阅:
  • LESS CSS - Change variable value for theme colors depending on body class
  • LESS.css variable depending on class
  • LESS CSS: abusing the & Operator when nesting?
  • 关于基于 CSS 类的 LESS 条件设置 LESS 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15366576/

    相关文章:

    css - 如何使用 bootstrap3 创建具有两种颜色的导航栏

    css - less 循环中的空间

    css - 减:计算值

    css - 使用 Less 每 0.5s 改变一个变量值

    twitter-bootstrap - 使用 bootstrap + font-awesome 减少 CSS "alias"

    python - 阻止 Django 缩小我的 less 文件

    css - 什么是 LESS 源映射?

    html - 当我尝试预览 LESS CSS 样式表时,为什么在 Chrome 中出现错误?

    css - 基于体型的可变性较小

    javascript - Dom 网格、固定内部的流体等等