csslint教会我的css哲学

我的css哲学
最近莫名其妙地用上了 csslint,她给了我很多错误和警告,出于好奇想知道什么原因,所以也从中了解到一些 css “哲学”。

为什么 0 后面不要带单位?
比如这种代码就是不允许的。


1
2
3
4
5
6
7
.mybox {
    margin: 0px;
}
 
.mybox {
    width: 0%;
}
原因是什么呢?

出于性能考虑。
属性值为0,在任何浏览器下不带单位都是可以正常工作的。
节省字节
为什么有时一个属性要写两次?
css3 有很多新属性和新属性的值,所以为了兼顾老旧的浏览器,一般会写上一些  fallback 属性,这样就造成了一个属性值需要写两次的情况。比如:


1
2
3
4
.mybox {
    color: red;
    color: rgba(255, 0, 0, 0.5);
}
为什么有人会按字母顺序写 css ?
哈哈,估计这像是 js 的写不写逗号之争。以前我发现 wordpress 官方主题的 css 是这样组织的,看起来形象良好,也不知道是全手写呢?还是通过什么自动化工具弄的。比如下面这段:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
.entry-footer .edit-link a.post-edit-link {
background-color: #222;
-webkit-border-radius: 2px;
border-radius: 2px;
-webkit-box-shadow: none;
box-shadow: none;
color: #fff;
display: inline-block;
font-size: 14px;
font-size: 0.875rem;
font-weight: 800;
margin-top: 2em;
padding: 0.7em 2em;
-webkit-transition: background-color 0.2s ease-in-out;
transition: background-color 0.2s ease-in-out;
white-space: nowrap;
}
我特意去查了一下为什么,网上较真的人还是挺多的。比如 codepen 的创始人做了一个统计,有近万人的投出自己的选票,其中有百分十四的选择了按字母顺序写 CSS ,人还真不少啊。我想这就是一种强迫症和情怀吧。

投票结果:

Grouped by type (45%) was fairly closely followed up by Randomly (39%). Much less popular was Alphabetic (14%) and only a few folks using Line length (2%).

From codepen
为什么不要将样式写在 h1、h2 这些 heading标 签上?

1
2
3
.foo h1 {
    font-size: 110%;
}
比如上面这种写法就不太合理。为什么?

heading 标签样式应该是全局定义的,而不是局部定义的。
统一全站文本字号的等级,有利于以后的维护。
有利于 SEO。
提高 heading 标签的代码重用性。
为什么不要将样式绑定在 html 标签上?

1
2
3
4
5
6
7
div.mybox {
    color: red;  
}
 
.mybox li.active {
    background: red;
}
例如上面的代码就不是最优的,可以改为下面这种:


1
2
3
4
5
6
7
div.mybox {
    color: red;  
}
 
.mybox .active {
    background: red;
}
原因是什么呢?

哈哈,第一点还是减少字节。
降低 css 和 html 的耦合,万一哪天不用这个标签呢。
可以随意改变 HTML 结构和不用修改 CSS 样式。
持续更新中
https://github.com/CSSLint/csslint/wiki/Beware-of-box-model-size
https://github.com/CSSLint/csslint/wiki/Disallow-outline%3Anone
参考链接
https://github.com/CSSLint/csslint


https://perishablepress.com/obsessive-css-code-formatting-patterns-and-trends/
http://csstidy.sourceforge.net/

标题:csslint教会我的css哲学

内容来自曾小乱的blog:https://zengxiaoluan.com/csslint-teaches-me-the-knowledge-of-css/#more-1231

猜你喜欢

转载自www.cnblogs.com/xiguage23/p/10417179.html