Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I fail to understand people's infatuation with CSS nesting.

It is nice not to write too much to get some pseudo elements or selectors working, but that's the extent of it.

Tying your CSS to the markup is a recipe for misery and pain. Over all these years, I've never seen it not turn out to be a nightmare.



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.


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.


Totally agree with you. Nesting selectors increase coupling with DOM. I did this a lot and I was not productive. At first seems to reduce code, but them, every change in the template I needed to change in the CSS.

What helped was to start building utility classes which I can reuse them.

As the other guy said, nesting selectors has few good usages, should be used carefully.


I started using Tailwind and couldn't agree more. Everything nowadays seems to be deeply nested and closely tied to a component. Most large React apps have a strict 1 component <-> 1 CSS file relationship. Try deciphering how your styles are being inherited to a component through a maze of nested components and their independent CSS files: nightmare.




Consider applying for YC's Summer 2026 batch! Applications are open till May 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: