Native web component: style host differently depending on slotted content

Solution 1:

The easiest and cleanest implementation of such a problem I can solve by using a named slot.

example of web component

  class MyComp extends HTMLElement {
    constructor() {
      super();
      const shadow = this.attachShadow({ mode: 'open' });
      this.shadowRoot.innerHTML = `
      <style>
        .flex {
          display: flex;
          justify-content: space-between;
        }
        .row {
          flex-direction: row;
          background: red;
        }
        .column {
          flex-direction: column;
          background: green;
        }
      </style>
      <div>
        <div class="flex row"><slot name="row"></slot></div>
        <div class="flex column"><slot name="column"></slot></div>
      </div>`;
    }
  }

  customElements.define('my-comp', MyComp);


usage in HTML

    <my-comp>
        <div slot="row">This is row 1</div>
        <div slot="row">this is row 2</div>
        <div slot="row">This is row 3</div>
    </my-comp>
    <my-comp>
        <div slot="column">This is colum 1</div>
        <div slot="column">This is colum 2</div>
        <div slot="column">This is colum 3</div>
    </my-comp>

example screenshotscreenshot

Another good way to have a attribute which can add respective classes to root elements to modify css based on it