浏览器如何完成 SCSS 规则评估

How SCSS rule evaluation done by browser

我正在做一个项目,我正在使用内部 UI 库。在其中一个 CSS 文件中,我看到了一些看起来很奇怪的东西。 为了简化事情,我用基本的 html 元素和相应的 css:

进行往复

CSS:

div{
  border:1px solid black;
  width:100px;
  height:100px;
}
.parent
//some comment exists here
.child{
  background-color: red;
}
.anotherdiv{
  background-color: blue;  
}

HTML

<div class='parent same'>Parent
    <div class='child'>Child</div>
</div>
<div class='anotherdiv'></div>

当我试图在 firefox 上检查以上内容时,我在 CSS 控制台下收到以下警告。

Dangling combinator: Ruleset ignored due to bad selector

我试图向后解决问题,即对于给定的 CSS:

.parent
//some comment exists here
.child{
    background-color:red;
}

我认为以上将解决

.parent .child{
  background-color:red;          //applied on inside level element
}

或者,

.parent.child{
  background-color:red;         //applied on same element
}

但其中任何一个都不适用。

而且,为 div 和 class anotherdiv 定义的规则集工作得很好。 我想知道浏览器如何读取 CSS,以及在到达一些弯曲的行时,它如何解析以及如何遵循 CSS 中的规则集。

更新

我交叉检查了文件类型,结果是 .SCSS 下面是我发现的奇怪内容

.accordion-toggle 
 // Inner needs the styles because you can't animate properly with any styles on the element
 .accordion-inner {
      padding: 9px 15px;
      border-top: 1px solid #e5e5e5;
  }

抱歉之前的误会!

假设您所说的 "comment" 在您的源文件中确实以 // 开头,在这种情况下它不是正确的 CSS 注释而只是垃圾(因为正斜杠不是 CSS 标识符或任何有效的 CSS 选择器语法的一部分),这会导致解析错误。

以下字符流:

.parent
//some comment exists here
.child{
    background-color:red;
}

被视为.parent,后跟垃圾,后跟由花括号表示的声明块。 } 之前的所有内容(包括 } 都被丢弃,解析器从该点恢复,继续进行,就好像它刚刚忽略的这个字符流 从未存在过 一样。来自 section 4.1.7 of CSS2.1:

The selector (see also the section on selectors) consists of everything up to (but not including) the first left curly brace ({). A selector always goes together with a declaration block. When a user agent cannot parse the selector (i.e., it is not valid CSS 2.1), it must ignore the selector and the following declaration block (if any) as well.

现在,当解析器看到以下规则时:

.anotherdiv{
  background-color: blue;  
}

它能够读取并应用此规则,因为就解析器而言,之前的规则是您的代码段开头的 div 规则。

您的 CSS rule setrule 是:

.parent
//some comment exists here
.child{
    background-color: red;
}

selectordeclaration block组成。 selector 指向要设置样式的 HTML 元素:

The selector consists of everything up to (but not including) the first left curly bracket*

由于 CSS 条评论,我们知道以下内容:

The /* */ comment syntax is used for both single and multi line comments. There is no other way to specify comments in external stylesheets*.

你的 selector 被解析为:

.parent //some comment exists here .child

这是一个无效的选择器,它输出错误。

由于选择器有问题,浏览器无法根据元素节点评估选择器,整个规则将被忽略。 浏览器永远不会尝试修复 CSS 规则,因为:

  • 可能会对布局造成更大的破坏。
  • 规则可能正确,但当前浏览器无法识别

注意:一些错误的选择器会破坏 CSS 结构,因此后面的所有规则都将被忽略。

read more...