How do I select an element that has a certain class?

Carolyn picture Carolyn · Jun 5, 2013 · Viewed 178.8k times · Source

My understanding is that using element.class should allow for a specific element assigned to a class to receive different "styling" than the rest of the class. This is not a question about whether this should be used or not, but rather I'm trying to understand how this selector is intended to work. From looking at a ton of examples on the internet, I believe the syntax is correct and do not understand why this is not working.

Here is an example:

CSS:

h2 {
    color: red;
}

.myClass {
    color: green;
}

h2.myClass {
    color: blue;
}

HTML:

<h2>This header should be RED to match the h2 element selector</h2>
<div class="myClass">
    <h1>This header should be GREEN to match the class selector</h1>
    <h2>This header should be BLUE to match the element.class selector</h2>
</div>

Answer

PSL picture PSL · Jun 5, 2013

It should be this way:

h2.myClass looks for h2 with class myClass. But you actually want to apply style for h2 inside .myClass so you can use descendant selector .myClass h2.

h2 {
    color: red;
}

.myClass {
    color: green;
}

.myClass h2 {
    color: blue;
}

Demo

This ref will give you some basic idea about the selectors and have a look at descendant selectors