lwc icon indicating copy to clipboard operation
lwc copied to clipboard

Incorrect transpilation of direct child selectors in scoped Light DOM styles with native CSS nesting

Open Mr-VincentW opened this issue 9 months ago • 2 comments

Description

Native CSS nesting syntax fails to transpile correctly in certain edge cases when used with scoped styles in the light DOM, particularly for direct child selectors. This occurs when child selectors are used without the & symbol.

Steps to Reproduce

  1. Transpiles Correctly: CSS with class selectors and the & symbol for child selectors:
.parent-class {
  & > .child-class {
   color: red;
  }
}
/* Results in something like:
 * .parent-class.lwc-6le4c39rot8 {
 *   &.lwc-6le4c39rot8 > .child-class.lwc-6le4c39rot8 {
 *     color: red;
 *   }
 * }
 */
  1. Transpiles Incorrectly: CSS with class selectors but without the & symbol for child selectors:
.parent-class {
  > .child-class {
   color: red;
  }
}
/* Results in something like:
 * .parent-class.lwc-6le4c39rot8 {
 *   > .lwc-6le4c39rot8.child-class.lwc-6le4c39rot8 {  // <-- ".lwc-6le4c39rot8.child-class", works "by coincidence", but not correct
 *     color: red;
 *   }
 * }
 */
  1. Fails for Type Selectors: CSS with type selectors (e.g., h2) and without the & symbol for child selectors:
.parent-class {
  > h2 {
   color: red;
  }
}
/* Results in something like:
 * .parent-class.lwc-6le4c39rot8 {
 *   > .lwc-6le4c39rot8h2.lwc-6le4c39rot8 {  // <-- ".lwc-6le4c39rot8h2", cannot work as desired
 *     color: red;
 *   }
 * }
 */

In this case, the output includes an incorrect concatenation of class and type selectors, which fails to target the intended elements properly.

Expected Results

CSS nesting should transpile correctly for direct child selectors, even when using type selectors without the & symbol. For example:

.parent-class {
  > h2 {
   color: red;
  }
}
/* Results in something like:
 * .parent-class.lwc-6le4c39rot8 {
 *   > h2.lwc-6le4c39rot8 {
 *     color: red;
 *   }
 * }
 */

Browsers Affected

All browsers supporting CSS nesting. Please refer to caniuse for browser compatibility infomation.

Version

  • "lwc": "^8.12.4"
  • "node": ">=18"

Possible Solution

Consider removing the scoping hash from nested selectors, as the top-most ancestor selector is already scoped.

Mr-VincentW avatar Feb 11 '25 02:02 Mr-VincentW

Thanks for such a detailed bug report! Native CSS nesting is a pretty new feature in browsers, so I'm not surprised there's cases that don't work quite right.

wjhsf avatar Feb 11 '25 16:02 wjhsf

This issue has been linked to a new work item: W-17800792

git2gus[bot] avatar Feb 11 '25 16:02 git2gus[bot]