rsk82
rsk82

Reputation: 29377

how to select given element AND all its children simultaneously?

ok I know how to do both these things separately:

#elemID {  } /* selects only one element */
#elemID * {  } /* selects all its children elements but not the element itself */

And I know I can do it like this:

#elemID, #elemID * { }

But is there a way to avoid this repeating ?

Upvotes: 21

Views: 6372

Answers (3)

Chrysaloid
Chrysaloid

Reputation: 53

As others have stated there is no native solution for this problem.

But in current year you can achieve this with CSS Nesting, a feature adapted from CSS pre-processors like LESS by Chrome and many other browsers. Look here to check which browsers support it.

You do it like this:

/* V1 */
#elemID {
    &, & * {
        /* Your style here */
    }
}

& is like a copy of the enclosing selector so with this you basically achieve the #elemID, #elemID * selector you've mentioned but only writing #elemID once.

If you plan to have many similar selectors you can make the code slightly more compact like this:

/* V2 */
#elemID { &, & * {
    /* Your style here */
}}

I do not recommend it for production or any publicly published code but if you have a modern browser it is great for personal purposes i.e. applying your custom styles to various websites.


As mentioned in the comments the formula can be even simpler/shorter:

/* V3 */
#elemID {
    &, * {
        /* Your style here */
    }
}
/* V4 */
#elemID {
    *, & {
        /* Your style here */
    }
}
/* V5 */
#elemID { &, * {
    /* Your style here */
}}
/* V6 */
#elemID { *, & {
    /* Your style here */
}}

All 6 versions mentioned here are equivalent, but I personally would prefer V3 or V5 over others.

Upvotes: 3

BoltClock
BoltClock

Reputation: 723398

No, there is nothing shorter than that.

Note that if you really only want all the children of #elemID, and not all the descendants, you need to use the child combinator:

#elemID, #elemID > *

And as Šime Vidas has commented, some properties like color are automatically inherited by descendant elements by default. If you're trying to give text color to #elemID, you should not need to apply it explicitly and recursively to the elements inside it. See the SitePoint Reference on inheritance in CSS for details.

Upvotes: 18

Klemen Slavič
Klemen Slavič

Reputation: 19841

No. But you could select its parent if an equivalent selector exists:

.parent * { ... }

Upvotes: 0

Related Questions