省略 CSS 块的最后一个分号 [英] Leaving out the last semicolon of a CSS block

查看:57
本文介绍了省略 CSS 块的最后一个分号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于此的几个问题:

  • 这是好的做法吗?
  • 在大规模范围内,它会缩短加载时间吗?
  • 它会导致浏览器崩溃"吗?
  • JavaScript (/jQuery) 中的最后一个函数是否也是如此?

我的意思是这样的:

#myElement {
  position: absolute;
  top: 0;
  left: 0
}

推荐答案

这是好的做法吗?

手动排除分号不是一个好习惯.这纯粹是因为在添加更多样式时很容易被忽略,特别是如果您在团队中工作:

It's not good practice to manually exclude semicolons. This is purely because it's easy to overlook when adding more styles, especially if you're working in a team:

想象一下你开始于:

.foo {
    background-color: #F00;
    color: #000             <-- missing semi-colon
}

然后有人添加了一些样式:

And then someone adds some styles:

.foo {
    background-color: #F00;
    color: #000             <-- missing semi-colon
    width: 30px;
    z-index: 100;
}

突然,另一个开发人员正在浪费时间弄清楚为什么他们的 width 声明不起作用(或者更糟的是,没有注意到它不起作用).保留分号更安全.

Suddenly the other developer is wasting time figuring out why their width declaration isn't working (or worse yet, doesn't notice that it's not working). It's safer to leave the semi-colons in.

它会大规模地缩短加载时间吗?

毫无疑问,对于每个块,您将节省几个字节.这些加起来,特别是对于大型样式表.与其自己担心这些性能提升,不如使用 CSS 压缩器,例如 YUI Compressor 为您自动删除结尾的分号.

Most definitely, for every block, you'd save a couple of bytes. These add up, especially for large style sheets. Instead of worrying about these performance gains yourself, it's better to use a CSS compressor, such as the YUI Compressor to automatically remove the ending semi-colons for you.

它会导致浏览器崩溃"吗?

不,这是安全的,因为浏览器正确地实现了规范的这一部分.CSS2 规范这样定义了一个声明:

No, it's safe, as browsers implement this part of the specification correctly. The CSS2 specification defines a declaration thusly:

声明要么是空的,要么是由一个属性名称、一个冒号 (:) 和一个属性值组成.

A declaration is either empty or consists of a property name, followed by a colon (:), followed by a property value.

更重要的是:

...同一选择器的多个声明可以组织成分号 (;) 分隔的组.

...multiple declarations for the same selector may be organized into semicolon (;) separated groups.

这意味着 ; 用于分隔多个声明,但不需要终止它们.

This means that ; is used to separate multiple declarations, but it is not needed to terminate them.

JavaScript 中的最后一个函数是否也是如此?

JavaScript 是一个完全不同的野兽,具有完全不同的规范.这个特定的问题已经被深入回答了之前很多次堆栈溢出.

JavaScript is a whole different beast with a completely different specification. This particular question has been answered in depth many times before on Stack Overflow.

这篇关于省略 CSS 块的最后一个分号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆