CSS trick

Probably everybody know how to match dom elements with css. For example if you want to match all <li> elements. you are doing something like this:

<style>
li{color: red}
</style>

This way every list element will have red text color.

The more advanced example is if you want to select only the active element – an element with a specific class. This way you are adding a style like:

<style>
li.active {color: red;}
</style>

This way only the active elements (list elements with class active) will have red text color.

Ok, but what if we want to match elements which has 2 specific classes?

Let’s say you have following structure:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>CSS Selectors</title>
</head>
<body>
    <ul>
        <li class="first second">test 1</li>
        <li class="first">test 2</li>
        <li class="second">test 3</li>
    </ul>
</body>
</html>

How to make the first list element to be with red color?

The obvious solution is to add an extra class like this:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>CSS Selectors</title>
    <style type="text/css">
        .third{color: red;}
    </style>
</head>
<body>
    <ul>
        <li class="first second third">test 1</li>
        <li class="first">test 2</li>
        <li class="second">test 3</li>
    </ul>
</body>
</html>

but what if there is an easiest solution?

Try this:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>CSS Selectors</title>
    <style type="text/css">
        .first{color: green;}
        .second{color: blue;}
        .first.second{color: red;}
    </style>
</head>
<body>
    <ul>
        <li class="first second">test 1</li>
        <li class="first">test 2</li>
        <li class="second">test 3</li>
    </ul>
</body>
</html>

As you may notice the css selector which is used is .first.second, so no spaces between them.

This way you can assure that only the element which has class first and second will meet the criteria and will be colorized in red. This notation works with ID’s as well, but basically if you have ID, then you know what is the exact element, so it’s useless, but for selection of two classes I think it really useful.

I would like to know if somebody knew about this way of selecting elements?

Demo

Share it:
  • Facebook
  • Twitter
  • Digg
  • StumbleUpon
  • del.icio.us
  • Google Bookmarks
  • Yahoo! Buzz
  • Add to favorites
  • Identi.ca