简体   繁体   English

属性选择器vs类选择器的样式

[英]Attribute selectors vs class selectors for styling

Many times I see code like this: 我很多次看到这样的代码:

<input type="text"   class="class1" name="text">
<input type="submit" class="class2" name="submit">

that then gets styled like this: 然后样式如下:

input[type=text]   { styles here...}
input[type=submit] { styles here...}

Why not use the class selector directly ("class1" and "class2" in this example)? 为什么不直接使用类选择器(在此示例中为“ class1”和“ class2”)?

Is this way of styling more cross-browser-y? 这种样式浏览方式是否更跨浏览器? (AFAIK attr selectors don't work in IE6) (AFAIK attr选择器在IE6中不起作用)

Is it faster? 它更快吗?

Has it anything to do with some best practice I am not aware of? 与我不知道的一些最佳实践有什么关系吗?

Thank you! 谢谢!

In 2014, the only situation in which cross-browser support for attribute selectors is an issue is if you're still working on legacy code that relies on quirks mode IE or generally older versions of the browser. 在2014年,唯一的问题是跨浏览器支持属性选择器的问题是,如果您仍在使用依赖于quirks模式IE或通常较旧版本的浏览器的旧代码。 You are correct in that attribute selectors don't work on IE6. 您是正确的,因为属性选择器不适用于IE6。 1 1

If the purpose of "class1" is to identify only input[type=text] elements, and "class2" to identify only input[type=submit] elements, then there is no difference between using a class selector and using an attribute selector. 如果“ class1”的目的仅是识别input[type=text]元素,而“ class2”的目的只是识别input[type=submit]元素,则使用类选择器和使用属性选择器没有区别。 2 If you are working with legacy code, then using classes in lieu of attributes is fine. 2如果使用的是旧代码,则可以使用类代替属性。 Otherwise, unless you're using the classes for some other purpose like a script, they're superfluous. 否则,除非您将类用于脚本等其他目的,否则它们是多余的。

Which is faster? 哪个更快? Who knows? 谁知道? Browsers are known to have specific optimizations for rules with lone class selectors, but whether that translates to actual time saved is another issue, one that's not worth considering unless selectors really are your bottleneck. 众所周知,浏览器对具有单独类选择器的规则进行了特定的优化,但是是否将其转换为实际节省的时间是另一个问题,除非选择器确实是您的瓶颈,否则不值得考虑。


1 People keep pointing out specifically that attribute selectors work on IE7 and IE8 only when you include a doctype for some reason. 1 人们一直特别指出,仅当出于某种原因包含文档类型时,属性选择器才能在IE7和IE8上运行。 That applies to pretty much every version of IE anyway, and honestly, if you're not already using a doctype, then you probably have a very good reason for it, in which case you shouldn't even be considering using any modern CSS features. 无论如何,这几乎适用于IE的每个版本,老实说,如果您尚未使用doctype,则可能有很好的理由,在这种情况下,您甚至不应该考虑使用任何现代CSS功能。 。

2 It's worth noting that if you simply select .class1 rather than input.class1 you will lose the specificity of the input selector. 2 值得注意的是,如果仅选择.class1而不是input.class1您将失去input选择器的特异性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM