Steven Matthews
Steven Matthews

Reputation: 11275

Selecting a class underneath a class with CSS

I am trying to select a class underneath a class, say I have a class named "A" on an element, and under it, I've got another element with a class name of "B".

There are other instances of "B" in the DOM, but none of them but one is under "A".

To select ONLY the "B" under the "A", would I use:

.A B {

CSS HERE

}

Or am I doing it wrong?

Here's the structure:

<h2 class="A">
<span>TITLECONTENT</span>
</h2>
<p>CONTENT</p>
<div class="B" addthis:title="TITLECONTENT " addthis:url="URL">

Upvotes: 3

Views: 5485

Answers (4)

TimCodes.NET
TimCodes.NET

Reputation: 4699

no you forgot the dot,

.A .B {

}

(assuming you mean your html is like this:)

<div class="A">
   <div class="B"></div>
</div>

Whenever you reference a class, you use a . Whenever you reference an id, you use a # Whenever you reference a tag name, you use no prefix e.g. div {}

Use the least specificity you need to target different elements

Targeting an element with multiple classes you append the second class with no space: .one.two

Targeting a descendant element you include a space: .one .descendant

Upvotes: 4

U-DON
U-DON

Reputation: 2140

You forgot a dot, but if you want all class B elements that are directly under class A elements, use the greater-than sign. So A has to be the direct parent of B.

.A > .B {
    /* CSS here. */
}

Upvotes: 0

Didier Ghys
Didier Ghys

Reputation: 30666

The most general form is

.A .B { ... }

This will target any element with class B which has a parent with class A, whether it is a direct parent or not:

<span class="B">
    <span class="A" >
    </span>
</span>

as well as

<span class="B">
    <div>
        <span class="A" >
        </span>
    <div>
</span>

If .B is a direct children of .A you can target it with this:

.A > .B { ... }

CSS Child selector

Upvotes: 6

mkk
mkk

Reputation: 7693

almost correct. You have to do

.A .B <- please note dot before B.

Also, if in the future you would need to select an element that has BOTH ` and B at the same time, you do it like this:

.A.B

which would target something like div class="A B" but will NOT target div class="A" nor div class="B"

Upvotes: 0

Related Questions