为什么使用属性选择器来匹配类?

我发现 一个例子的响应电子邮件模板,其中有这样的 CSS 选择器,如下:

a[class="btn"]

为什么使用这种语法,如果它可以替换为更简单的:

a.btn

它对移动浏览器或其他东西有什么影响吗? 是否有电子邮件客户端需要这种使用?

48335 次浏览

The [] syntax is an attribute selector.

a[class="btn"]

This will select any <a> tag with class="btn". However, it will not select <a> which has class="btn btn_red", for example (whereas a.btn would). It only exactly matches that attribute.

You may want to read The 30 CSS Selectors you Must Memorize. It's invaluable to any up-and-coming web developer.

Why use an attribute selector to match classes?

The obvious use case for attribute selector: Specific matches

Exact match =, containing/substring *=, prefix ^=, suffix $=, etc.

Yahoo Mail Hack

  • You want to support beta versions of Yahoo Mail
  • You have media queries

Normally apps made before media queries just ignore the whole block - not beta yahoo mail, which just applies all the styles ignoring the media query. It doesn't support attribute selectors though...

For this case you can use attribute selectors to select a class within a media query so that the media query works on most email clients but doesn't trigger media query styles on beta versions of yahoo mail.

read more here

Caniemail data on the attribute-selector having much less support than the class selector.