更少的 CSS 嵌套类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5117133/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
LESS CSS nesting classes
提问by newbie_86
I'm using LESS to improve my CSS and am trying to nest a class within a class. There's a fairly complicated hierarchy but for some reason my nesting doesn't work. I have this:
我正在使用 LESS 来改进我的 CSS 并试图在一个类中嵌套一个类。有一个相当复杂的层次结构,但由于某种原因,我的嵌套不起作用。我有这个:
.g {
float: left;
color: #323a13;
.border(1px,#afc945);
.gradient(#afc945, #c8da64);
.common;
span {
.my-span;
.border-dashed(1px,rgba(255,255,255,0.3));
}
.posted {
.my-posted;
span {
border: none;
}
}
}
I can't get the .g.posted
to work. it just shows the .g
bit.
If i do this it's fine:
我无法开始.g.posted
工作。它只是显示了.g
一点。如果我这样做很好:
.g {
float: left;
color: #323a13;
.border(1px,#afc945);
.gradient(#afc945, #c8da64);
.common;
span {
.my-span;
.border-dashed(1px,rgba(255,255,255,0.3));
}
}
.g.posted {
.my-posted;
span {
border: none;
}
}
I'd like to nest the .posted
in .g
though. Any ideas?
不过我想把它嵌套.posted
进去.g
。有任何想法吗?
回答by mingos
The &
character has the function of a this
keyword, actually (a thing I did not know at the moment of writing the answer). It is possible to write:
该&
角色具有的功能this
关键字,居然(事我不知道在写答案的时刻)。可以写成:
.class1 {
&.class2 {}
}
and the CSS that will be generated will look like this:
将生成的 CSS 将如下所示:
.class1.class2 {}
For the record, @grobitto was the first to post this piece of information.
为了记录,@grobitto 是第一个发布这条信息的人。
[ORIGINAL ANSWER]
[原答案]
LESS doesn't work this way.
LESS 不是这样工作的。
.class1.class2 {}
- defines two classes on the same DOM node, but
.class1.class2 {}
- 在同一个 DOM 节点上定义了两个类,但是
.class1 {
.class2 {}
}
defines nested nodes. .class2
will only be applied if it is a child of a node with the class class1
.
定义嵌套节点。.class2
仅当它是具有类的节点的子节点时才会应用class1
。
I've been confused with this too and my conclusion is that LESS needs a this
keyword :).
我也对此感到困惑,我的结论是 LESS 需要一个this
关键字:)。
回答by grobitto
.g {
&.posted {
}
}
you should add "&" before .posted
您应该在 .posted 之前添加“&”
回答by Nesha Zoric
If the ampersand is located right next to the child element in nesting, it is compiled into a double class selector. If there is space between & and selector it will be compiled into child selector. Read more about nesting in Less here.
如果&符号位于嵌套中的子元素旁边,则将其编译为双类选择器。如果 & 和选择器之间有空格,它将被编译为子选择器。在此处阅读有关 Less 中嵌套的更多信息。