如何将多个类组合成一个语义命名的类? [英] How to compose multiple classes into a single semantically-named class?
问题描述
我一直在阅读 Block-Element-Modifier 命名约定、语义命名样式规则等,我想用一个语义类名替换我的 html 中的多个类名.不过,似乎无法实现.示例:
I've been reading up on Block-Element-Modifier naming conventions, semantically-named style rules, etc. and I'd like to replace multiple class names in my html with a single, semantic class name. Can't seem to make it happen, though. Example:
我想更换我的 Bootstrap 导航栏
I'd like to replace my Bootstrap navbar
<nav class="navbar navbar-default navbar-fixed-top" role="navigation">
与
我知道我可以使用 jQuery 按程序执行此操作,但我不想这样做.我尝试了几种使用变量名、#{} 插值语法、mixin 和 @extend 等的方法,但只是得到语法错误或无效结果.
I know I could use jQuery to do this procedurally, but I'd prefer not to. I've tried several approaches using variable names, #{} interpolation syntax, mixins, and @extend, etc. but just get syntax errors or invalid results.
这难道不是 Sass 的设计初衷吗?
Is this just not something Sass was designed to do?
推荐答案
这难道不是 Sass 的设计初衷吗?
Is this just not something Sass was designed to do?
Sass 确实支持这个用例.
Sass does support this use case.
您需要的是扩展.
像使用非语义方法一样定义
navbar
、navbar-default
和navbar-fixed-top
类:
.navbar { display: table; }
.navbar-default { background-color: deeppink; }
.navbar-fixed-top { position: fixed; top: 0; left: 0; width: 100%; }
下面,用这些扩展你的 header__navbar
类:
.header__navbar {
@extend .navbar;
@extend .navbar-default;
@extend .navbar-fixed-top;
}
一旦您完全摆脱了 HTML 标记中的非语义类,您的 CSS 中就不再需要它们.所以把它们变成占位符选择器,又名无声选择器.为此,请在定义它们的规则和使用它们的 @extend
指令中将 .
替换为 %
.例如:
Once you get rid of non-semantic classes in your HTML markup completely, you no longer need them in your CSS. So turn them into placeholder selectors aka silent selectors. To do so, replace the .
with %
both in the rules where they are defined and in @extend
directives that use them. E. g.:
%navbar { display: table; }
%navbar-default { background-color: deeppink; }
%navbar-fixed-top { position: fixed; top: 0; left: 0; width: 100%; }
.header__navbar {
@extend %navbar;
@extend %navbar-default;
@extend %navbar-fixed-top;
}
这篇关于如何将多个类组合成一个语义命名的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!