Why use an attribute selector to match classes?

CssCss Selectors

Css Problem Overview


I have found an example of responsive email templates where there are such CSS selectors such as the following:

a[class="btn"]

Why is this syntax used if it could be replaced with the simpler:

a.btn

Does it have any impact on mobile browsers or anything else? Are there email clients that require this usage?

Css Solutions


Solution 1 - Css

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.

Solution 2 - Css

> 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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionducinView Question on Stackoverflow
Solution 1 - CssCatView Answer on Stackoverflow
Solution 2 - CssZach JenszView Answer on Stackoverflow