In short, I’d like to select a child element that has either Parent A or Parent B.
I’m wondering if there’s a way to simplify my selectors in this scenario, or if what I have here is the only way to do it. Also, is there a best practice in this scenario? Below are some simplified examples:
/* long example (probably not best practice) */
#parent-a .common-child {
color: #000;
}
#parent-b .common-child {
color: #000;
}
/* shortest example I know of */
#parent-a .common-child, #parent-b .common-child {
color: #000;
}
Is there any way to do something like:
#parent-a||#parent-b .common-child {
color: #000;
}
It might not look like a big deal in these simple examples, but in my actual CSS I have several dozen selectors that chain down through the DOM a bit, and I want to optimize the file size / readability.
Thanks!
This would be the most simplified solution. They have to be separated. All you can do is combine similar styles into one line like in the above.
However, I would say that you’re almost leaving the realm of use for an ID selector. An ID is meant to be unique, and the styles that apply to it should be unique as well. If you ever add a
parent-cor further, you should definitely consider adding a single class to those elements rather than selecting each one by its ID.color: #000is a very broad style. If that were the only style being applied to both of these elements, it would make sense to set the style on a parent higher up so that it gets inherited by all its children, grandchildren, and so on.Without seeing more of your structure, we can’t really advise you on best practices. CSS and its optimization is very highly based on what else is around it and being specific.