Re: [WICG/webcomponents] CSS selector to style slots with slotted elements (#936)

To show an example where `slotchange` and JS is used to fill this gap, I noticed this pattern in @claviska's Shoelace components.

A component that wants to style based on the presence of slotted nodes will [compute a class based on a JS utility](https://github.com/shoelace-style/shoelace/blob/46ac48071306e9421c0f64f6ea8dc6bec6e9d68a/src/components/button/button.ts#L184
):

```ts
    return html`
      <button
        part="base"
        class=${classMap({
          'button--has-label': this.hasSlotController.test('[default]'),
          'button--has-prefix': this.hasSlotController.test('prefix'),
          'button--has-suffix': this.hasSlotController.test('suffix')
```

`this.hasSlotController.test('[default]')` returns true if the default slot has assigned nodes, which causes the element to have the `button-has-label` class. Then it's styled with:

```css
  .button--has-label.button--small .button__label {
    padding: 0 var(--sl-spacing-small);
  }
  ```

and there's a whole [`HasSlotController` utility](https://github.com/shoelace-style/shoelace/blob/next/src/internal/slot.ts#L3) that will listen for slot change and re-render the component so that those classes can be recomputed.

I think this whole mechanism and render cycle could be replaced with this CSS if we had the right selector:

```css
  button:has(slot:not([name])::hasSlotted(*)) {
    padding: 0 var(--sl-spacing-small);
  }
```

-- 
Reply to this email directly or view it on GitHub:
https://github.com/WICG/webcomponents/issues/936#issuecomment-1085187369
You are receiving this because you are subscribed to this thread.

Message ID: <WICG/webcomponents/issues/936/1085187369@github.com>

Received on Thursday, 31 March 2022 22:24:44 UTC