“!important”不应在“keyframes”上使用
!important
在某些浏览器中,关键帧声明中的“内部”将被完全忽略,因此,不应在所有浏览器中使用它来保持一致。
不兼容的代码示例:
@keyframes kf {
from { margin-top: 50px; }
50% { margin-top: 150px !important; } /* Noncompliant; ignored */
to { margin-top: 100px; }
}
兼容解决方案:
@keyframes kf {
from { margin-top: 50px; }
50% { margin-top: 150px; }
to { margin-top: 100px; }
}
"calc"操作数应正确隔开
calc
是CSS3函数,它提供了在CSS中进行简单数学运算(加,减,除,乘)的可能性。运算符周围没有空格,calc
将无效。
更准确地说,在操作员之前,必须有单个空格或换行符以及缩进。在运算符之后,必须有单个空格或换行符。
不兼容的代码示例:
#div1 {
position: absolute;
width: calc(100%- 100px); /* Noncompliant; no space after the % sign */
}
兼容解决方案:
#div1 {
position: absolute;
width: calc(100% - 100px);
}
“linear-gradient”方向应有效
linear-gradient
用CSS3进行了标准化。在此之前,可以使用不同的非标准值来定义渐变的方向。由于这些值不是标准的,因此并非所有浏览器都支持它们,因此,在支持CSS3的最新浏览器版本中,不应再使用它们来获得预期的渐变。
当a
的第一个参数linear-gradient
无效<side-or-corner>
时,此规则会引起问题angle
。
不兼容的代码示例:
.foo {
background: -webkit-linear-gradient(to top, #fff, #000);
background: linear-gradient(top, #fff, #000);
}
.bar {
background: linear-gradient(45, #fff, #000);
}
兼容解决方案:
.foo {
background: -webkit-linear-gradient(top, #fff, #000);
background: linear-gradient(to top, #fff, #000);
}
.bar {
background: linear-gradient(45deg, #fff, #000);
}
颜色定义应有效
默认情况下,无效的颜色定义将被解释为黑色,这可能会对网站的预期外观产生意想不到的影响。
此规则提出了一个问题,当一个颜色定义(color,background-color)
是无效的。当颜色定义由十六进制字符组成时,它被认为是有效的:
- 常用:6或8个字符(定义了字母时)
- 速记变体:3或4个字符(定义了字母时)
不兼容的代码示例:
a {
color: #3c; /* Noncompliant; shorthand should be made of 3 characters */
}
div {
backgr
兼容解决方案:
a {
color: #3cc;
}
div {
background-color: #3cb371ac;
}
CSS文件不能为空
当CSS文件为空(即:仅包含空格)时,会引起问题。
字体声明应至少包含一个通用字体系列
如果用户浏览器中没有可用的font
或font-family
声明中定义的字体名称,则浏览器将使用其默认字体显示文本。建议始终为每个声明定义一个通用字体系列, font
或者font-family
比依靠默认浏览器字体来减少降级的情况。所有浏览器都应该实现通用字体匹配这些家庭的名单:Serif,Sans-serif,cursive,fantasy, Monospace
。
不兼容的代码示例:
a {
font-family: Helvetica, Arial, Verdana, Tahoma; /* Noncompliant; there is no generic font family in the list */
}
兼容解决方案:
a {
font-family: Helvetica, Arial, Verdana, Tahoma, sans-serif;
}
“rule”应有效
W3C规范定义了有效的at-rules
。只有官方的和特定at-rules
于浏览器的才可以用来获得最终渲染中的预期效果。
不兼容的代码示例:
@encoding“ utf-8”;
兼容解决方案:
@charset“ utf-8”;
单位应有效
W3C规范定义了units
可以与长度一起使用的。不属于支持列表的单位可能是拼写错误,并且会被用户视为UI错误。
每当没有正式支持某个单位时,此规则就会引起问题。
不兼容的代码示例:
a {
width: 10pixels; /* Noncompliant; "pixels" is not a valid unit */
}
兼容解决方案:
a {
width: 10px;
}
CSS属性应该有效
W3C规范定义了有效的CSS属性。仅应使用官方属性和特定于浏览器的属性来获得最终渲染中的预期效果。
该规则忽略:
$sass,@less
和var(--custom-property)
可变语法。- 供应商前缀的属性(例如
-moz-align-self
,-webkit-align-self
)。
不兼容的代码示例:
a {
colour: blue; /* Noncompliant; colour is not part of the specifications */
}
兼容解决方案:
a {
color: blue;
}
较低特异性的选择器应优先于较高特异性的选择器
CSS中的指令顺序很重要:文件中后面出现的具有相同特异性的指令具有优先权。但是,当具有更高特异性的选择器(例如p a { color: green;})
出现在选择器优先于选择器(例如:)之前时a { color: green;
},优先级将赋予第一个选择器。即使它正常工作,在阅读时也很难预期样式表的行为,因为它违反了最后一条指令优先的原则。
不兼容的代码示例:
p a {
color: green;
}
a {
color: blue;
}
兼容解决方案:
a {
color: blue;
}
p a {
color: green;
}