Hacker News new | ask | show | jobs
by roman-holovin 1759 days ago
I feel that problem is that some CSS has to be tied to markup and some of it - doesn't.

There is bunch of CSS features and techniques that work only when you enforce certain parent-child relationships of the CSS rules.

Simplest example of it is 'position:absolute' that requires some parent node to have 'position: relative' to be useful. But there is more to that, both flexbox and grid require certain properties to applied to both parent and children nodes at the same time.

Nesting is one way to enforce those relationships and make sure that they are co-located in the stylesheet code.

Something like that is, in my view, good usage of the nesting:

   .parent {
       display: flex;

       & > .child {
          flex: 1 1 auto;
       }
   }

   .child {
       color: red
   }
I specifically added an example that changes color for class `child` and I think this should not be included in the nested rule because this part of the styling is not affected by a parent in any meaningful way.
1 comments

I agree. I find this approach works very well. The component's own styles are just related to how it looks: color, images, fonts, etc. The parent's styles tell a child where to go in the layout. In general I find if I maintain this division, my css remains sane and I can reuse a component in just about any scenario.

In your example, if .child had flex defined internally, then that becomes a bad time in my experience.