这是一个很长的路要走,但是有没有可用的工具可以通过消除不必要的特异性来优化CSS选择器?
我发现在编写CSS时,我故意使选择器变得比必要的更加具体,以避免冲突和准文档化。
如果有一种工具可以分析给定的一组规则,根据与其他规则的重叠来确定其“唯一性”,然后剔除任何不必要的特异性,那将是很好的。
我什至无法开始想象工具开发人员将如何处理所需的所有方案,但是以前我在这方面被其他人的独创能力吓了一跳,并认为值得一问。
更新:
我为这个问题添加了一笔赏金,我对它的思考越多,我就越意识到CSS特殊性过滤器的价值。
例如,在Sass和LESS中使用嵌套规则/选择器时,过多的嵌套是一种常见且众所周知的反模式,很容易导致选择器过于具体。
在出色的TutsPlus课程“ 使用Sass和Compass维护CSS”中有一个很好的例子:
body {
div.container {
p {
a {
color: purple;
}
}
}
}
Sass将遵循这些嵌套指令,并产生以下CSS输出,不反对任何不必要的特性:
body div.container p a {
color: purple;
}
但是,如果存在/确实存在特异性过滤器,它将为CSS开发人员带来潜在的好处:
You could organize your stylesheets as a 1:1 mapping of the DOM, similar to what you see when you examine style rules in Firebug and Chrome Dev Tools. A smart editor/IDE could auto-populate styles for DOM elements with shared styles/classes. That redundancy would then, of course, be filtered out by the Specificity Filter/Optimizer.
Stylesheets could have their structure pre-populated by a tool that scans the DOM and translates it to CSS selectors/rules. This means a developer would only need to update the HTML; the CSS "tree" would be kept in sync to reflect the current state of the DOM. A smart editor would let you jump to the CSS definition for an element/class for styling -- or even make its style rules visible in a separate panel.
In a way, this almost seems like a step backward - like a feature you'd find in Dreamweaver or WebAssist to help newbs learn CSS. But the basic idea of a CSS selector optimization tool seems like a no brainer, and the type of workflow automation I've described would be the logical next step -- and the catalyst would be the Specificity Filter.
I looked into some of the better-known CSS editors and web IDEs, but haven't found anything offering this type of functionality beyond targeting a single element and generating a selector for it.
Update 2: CSS Selector Performance
In response to Spliff's comment, here are two great articles on CSS selector performance:
Performance Impact of CSS Selectors by Steve Souders
Efficiently Rendering CSS by Chris Coyier
Both agree that micro-optimizing CSS isn't worth the effort, but that over-qualified descendant selectors are "an efficiency disaster." I haven't benchmarked yet myself, but suspect that the kind of "DOM Mapping" approach I'm suggesting would cause a performance hit without an optimization step, either manual or automated.
Related Questions, Links, and Tools:
实际上,您可以使用HTML5和CSS3来实现此目的。标准技术是使用HTML 5属性“ data-”指定元素,然后对该属性进行CSS选择。这不是属性的目的,但是您可以自定义指定一些元素,甚至可以用来切换网站的主题。
因此,例如,您最终可以通过在CSS中手动指定
其中数据专用性仅与上面的父级匹配。
更新:
好了,举例来说,假设您有一个段落类,但是您想指定该段落可以继承属性的父级或多少个父级。您将对可以从中继承的每个潜在父母使用规则:
因此,这些规则意味着,任何作为div容器的直接子级且具有特异性2的p标签都可以继承div容器的属性。div的蓝色被p继承,具有数据特定性2。
这是一个JSFiddle,您可以在这里看到它!
这样的想法是,使用HTML5,您可以精确地控制允许哪些元素继承哪些属性。(为子元素和父元素)编写了很多额外的代码,但是您可以使用它来摆脱一些不必要的特殊性
我实际上从未见过有人在实践中使用此方法,我几乎只是为您煮熟了,但是我认为它可能非常有用,您认为呢?