CSS 用空格连接或分隔的类名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16858926/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 23:04:14  来源:igfitidea点击:

Class names concatenated or separated by a space

css

提问by Bart Weber

When do you separate style classes with a space? So for example: what is the difference between the following two blocks of css?

什么时候用空格分隔样式类?所以举个例子:下面两块css有什么区别?

Block 1:

第 1 块

div {
    color: brown;
}

div.special {
    font-size: 18px;
}

Block 2:

第 2 块

div {
    color: brown;
}

div .special {
    font-size: 18px;
}

This is the HTML:

这是 HTML:

<div class="special">The quick brown fox jumps over the lazy dog.</div>

I tried both versions. Only with block 1 the text wil be in font size 18.

我试过两个版本。仅在块 1 中,文本的字体大小为 18。

回答by j08691

You separate classes by a space when you want to refer to descendant element and you concatenate them when you want to refer to a single element with multiple classes.

当您想引用后代元素时,用空格分隔类,当您想引用具有多个类的单个元素时,将它们连接起来。

For example, to refer to a div with two classes, e.g. <div class="foo bar">you could use:

例如,要引用具有两个类的 div,例如<div class="foo bar">您可以使用:

div.foo.bar {...}

To refer to the child span element <div class="foo"><span class="bar">stuff</span></div>you could use:

要引用<div class="foo"><span class="bar">stuff</span></div>您可以使用的子跨度元素:

div.foo .bar {...}

回答by Sampson

A space indicates nesting:

空格表示嵌套:

div .foo /* .foo is inside div */

No space indicates further specificity:

没有空格表示进一步的特异性:

div.foo /* any div that is also .foo */

回答by Liam

div.specialrefers to

div.special指的是

<div class="special"> <- this

div .specialrefers to

div .special指的是

<div>
    <p class="special"> <-  this
</div>

Not neccassily a pBTW

不是pBTW

回答by Nick Andriopoulos

The space notes that this is a child item.

空格指出这是一个子项。

IE

IE

div.special 

targets a div that has the class specialwhile

以具有该类的 div 为目标,special

div .special

targets an element with class specialinside a divelement

以元素内具有类specialdiv元素为目标

回答by Mr. Alien

div.specialwill select the divelement which has class .specialand it wont select any other element with class .specialso if you have something like <ul class="special">will be excluded, where as this div .specialwill select all the elements having class .specialwhich are nested inside divso this will select <ul class="special">so it concludes that the 1st one is stricter than the second one

div.special将选择div具有类的元素,.special它不会选择具有类的任何其他元素,.special因此如果您有类似的东西<ul class="special">将被排除在外,因为这div .special将选择具有.special嵌套在内部的类的所有元素,div因此这将选择<ul class="special">因此得出的结论是第一个一个比第二个更严格

So in your case either you can simply use .specialor you can use div.special

因此,在您的情况下,您可以简单地使用.special,也可以使用div.special