This question is not an opinion based. I want to get short of "best practice" answer from professional frontends. My new firm asked me to "if a element is inside a div do not give ‘color’ to that div but specifically give to the child element of it." they meant:
dont
.parent {color: white}
do
.parent p {color: white}
and then they asked me to don’t use multiple selectors:
they meant don’t to this:
.parent .card .title h2
So when I asked what is the purpose of this they told me they could use the code I wrote later and if I write like this they cant use it in another webpage.
Questions
- If a div’s childs are the same color, should I specifically write to colors to each child elements or should I use
.parent {color: black}
- Is my employer’s second request nonsense or a valid request?
>Solution :
In my experience, your first example (.parent { color: white }) is relatively valid and pretty common; however, it is true that it relies on inheritance. What if tomorrow your client (or someone else) decides that they don’t want this child to be inside of .parent? What if they want it on a different part of the page? Code that relies on inheritance like this can often be harder to change – though it is true that it might not matter in a small-scale example, or that often we write style "components", i.e. a button or a card, in which it would make sense to use inheritance.
In recent years, it’s become more and more common to take the sort of TailwindCSS-like approach and create utility classes, such as .white-text, which can be used independent of how the markup on the page is structured. In fact, I’d say that libraries/tools like TailwindCSS have become more and more popular precisely because they aren’t reliant on your markup the way traditional CSS tools are, and they create fluidity and allow easy changes.
As for the second request, I think it boils down to something similar, along with the reusability you employer was talking about. Something like .parent .child h2 span will break if the page itself is changed even slightly, and requires you to make changes in multiple places every time you want to change the HTML.