Home

CSS: How to select elements that have only one specific class

If you want to select HTML elements that have only a specific class foo, without selecting elements that have any other classes (eg. foo bar) checkout the solutions bellow.

Select elements with only one specific class

Implementation:

<!DOCTYPE html>
<html lang="en">
  <head>
    <style>
      *[class='foo'] {
        color: red;
      }
    </style>
  </head>
  <body>
    <div class="foo">Foo</div>
    <div class="foo bar">Foo Bar</div>
  </body>
</html>

The result:

Foo
Foo Bar

Select elements with multiple specific classes

The same solution also works to select elements with more than one class:

<!DOCTYPE html>
<html lang="en">
  <head>
    <style>
      *[class='foo bar'] {
        color: blue;
      }
    </style>
  </head>
  <body>
    <div class="foo">Foo</div>
    <div class="foo bar">Foo Bar</div>
    <div class="foo bar baz">Foo Bar Baz</div>
  </body>
</html>

The result:

Foo
Foo Bar
Foo Bar Baz

Considerations

If you are attempting the above, make sure you have a good reason to do so. It is not a best practice and may trip your fellow devs.

You should only use the above solutions when the bellow solution is not viable for some reason:

<!DOCTYPE html>
<html lang="en">
  <head>
    <style>
      *.my-specific-selector {
        color: green;
      }
    </style>
  </head>
  <body>
    <div class="foo">Foo</div>
    <div class="foo bar">Foo Bar</div>
    <div class="foo bar baz">Foo Bar Baz</div>
    <div class="foo bar baz my-specific-selector">
      Best practice ftw!
    </div>
  </body>
</html>

The result:

Foo
Foo Bar
Foo Bar Baz
Best practices ftw!