OhDaeSu
OhDaeSu

Reputation: 525

How to change only one element of a class without giving it an ID?

My question:

Is it possibile to ONLY change one element of a class without (a) giving it an own ID and (b) without doing inline-style in the HTML document?

Why do I want to do that?

I am using a software where the program creates classes and ids by itself (for a questionnaire). I cannot change or add classes/ids nor can I change the html. The only thing I can do is grab those already defined classes with CSS and style them (which is what I want to do).

Example:

JSFiddle: http://jsfiddle.net/nyGWc/

In this example I only want to change the background-color of the second ".class2" to green (whereas the first ".class2" div should remain red).

<div class="class0">
    <div class="class1">
        <div class="class2">
            This div has a red background color. 
        </div>
    </div>
</div>

<div class="class0">
    <div class="class1">
        <div class="class2"> 
            This div should be green without adding an ID to it. 
        </div>
    </div>
</div>

CSS:

.class1 {
    height: 3em;
}

.class2 {
    background-color: red;
}

What I've tried so far:

I've tried to use :nth-child(2) and :nth-of-type(2) but as far as I've understood it, it only selects the target child under a parent element? In my example the div elements with the class ".class2" are not siblings. So those won't work.

Thanks a lot!

Upvotes: 0

Views: 3038

Answers (2)

Rupam Datta
Rupam Datta

Reputation: 1879

As you rightly said, since the class2 elements are not siblings, you cannot use nth-child. So the solution to your problem is using nth-child for class0. Here is the code

.class0:nth-child(2) .class2{
    background-color: green;
}

FIDDLE

Upvotes: 4

T0xicCode
T0xicCode

Reputation: 4941

Select the second class0, then select its child class2. Using nth-of-type allows the .class0 elements to not need to be under the same parent element.

.class0:nth-of-type(2) .class2 {
    background-color: green;
}

Fiddle

Upvotes: 2

Related Questions