1

I want to select the first level .box of each one of these three .box siblings, but not their children .box(s). (Does this make sense?)

Here's my markup:

<div class="box">
    <div class="box">
        test
    </div>
</div>

<div class="box">
    <div class="box">
        test2
    </div>
</div>

<div class="box">
    <div class="box">
        test3
    </div>
</div>

How can I perform this selection with CSS?

2 Answers 2

6

This is not possible unless you specifically refer to the parent of the outer boxes somehow. For example, if you know that all of this is going to be inside #foo, then #foo > .box will do the job.

However, you can select boxes which are in another box with .box > .box or .box .box, so in this manner it might be possible to do what you need using the classic workaround of "undoing changes". For example, to turn only the outer boxes blue:

.box { background: blue } /* make a far-reaching change */
.box .box { background: transparent } /* then undo it partially */

Of course the inner boxes will still show the blue background of their parents, but you get the idea.

Sign up to request clarification or add additional context in comments.

3 Comments

Well if that's the only way, that's the only way. Thanks so much for your help!
Specifying the parent - as in the #foo > .box example - is a powerful and elegant way to do this. The desired .box elements must have a parent, even if it's <body>.
This was in the event that I could not edit the existing markup. I'd also like to add to the answer saying if you are using jQuery as a selector you can use :not to preform this selection: .box:not(.box > .box)
2

The better way to select just the first ones is to use the > in your css selector so use it like this:

body>.box {
    css here
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.