vue.jsvuejs3tailwind-css

Tailwind Peer class not working while using Vue components


App.vue

<script setup lang="ts">
import ParentComp from "./components/ParentComp.vue";
</script>

<template>
  <ParentComp />
</template>

ParentComp.vue

<script setup lang="ts">
import ChildComp from "./ChildComp.vue";
</script>

<template>
  <div class="peer text-3xl bg-emerald-700">
    <ChildComp child-num="1" />
    <ChildComp child-num="2" />
  </div>
</template>

ChildComp.vue

<script setup lang="ts">
const props = defineProps<{
  childNum: string
}>();
</script>

<template>
  <h1 class="peer-first:bg-green-600 peer-last:bg-red-600">
    Child {{ childNum }}
  </h1>
</template>

What I'm trying to do

I want the first child have a green background and the second (last element) to have a red background.

Expected result

First child will bg-green-600, second child will bg-red-600.

expected result

Current result

Got children with bg-emerald-700 background from parent-element.

current result


Solution

  • Pseudo-classes

    These are not peer modifiers but pseudo-classes.

    <script src="https://cdn.tailwindcss.com"></script>
    
    <div>
      <p class="first:bg-green-600 last:bg-red-600">First (first)</p>
      <p class="first:bg-green-600 last:bg-red-600">Second</p>
      <p class="first:bg-green-600 last:bg-red-600">Third (last)</p>
    </div>

    Type-oriented pseudo-classes

    The first-of-type and last-of-type pseudo-classes apply to specific types of elements within a parent. In the example, -of-type is used on paragraphs, so only the paragraphs' order is considered, even if an h1 is first.

    <script src="https://cdn.tailwindcss.com"></script>
    
    <div>
      <h1>This is not a &lt;p&gt; (paragraph) element, so it does not count as the first in the first-of-type selector.</h1>
      <p class="first-of-type:bg-green-600 last-of-type:bg-red-600">First paragraph (first)</p>
      <p class="first-of-type:bg-green-600 last-of-type:bg-red-600">Second paragraph</p>
      <p class="first-of-type:bg-green-600 last-of-type:bg-red-600">Third paragraph (last)</p>
    </div>

    Peer-modifiers

    peer-modifiers are utility classes that apply styles to elements based on the state of a related sibling element with a peer class. In the case of first and last, there is no mention of sibling elements. It specifies which position among the given elements you want to apply the styling to.

    Any classes related to positions (which element should have this style) are not about sibling elements or conditions. It simply sets the style for the Xth element and that's it. That’s why they are not categorized as peer-modifiers.

    <script src="https://cdn.tailwindcss.com"></script>
    
    <div>
      <input type="checkbox" checked class="peer" />
      <p class="first-of-type:peer-checked:bg-green-600 last-of-type:peer-checked:bg-red-600">First (first)</p>
      <p class="first-of-type:peer-checked:bg-green-600 last-of-type:peer-checked:bg-red-600">Second</p>
      <p class="first-of-type:peer-checked:bg-green-600 last-of-type:peer-checked:bg-red-600">Third (last)</p>
    </div>



    Custom coloring with Vue (or JavaScript)

    In the example provided, I believe it can be perfectly achieved using TailwindCSS pseudo-classes. However, if this were a more complex model and we were relying solely on the child component's index, we would need to 'calculate' whether the specific child component is the first or last.

    Example #1 (with isFirst, isLast props)

    For child components created using a loop, you can determine if a child is the first (index === 0) or last (index === children.length - 1) based on the loop index. This information needs to be passed to the child components, which I did using isFirst and isLast props. These props can then be used during formatting to assemble dynamic class names.

    const { createApp, ref } = Vue
    
    const ChildComponent = {
      props: {
        childNum: Number,
        isFirst: Boolean,
        isLast: Boolean,
      },
      template: `
        <div>
           <h1 :class="{ 'bg-green-600': isFirst, 'bg-red-600': isLast }">
             Child #{{ childNum }}
           </h1>
        </div>
      `,
    }
    
    const ParentComponent = {
      components: {
        'child-component': ChildComponent,
      },
      setup() {
        const children = ref([
          { num: 1 },
          { num: 2 },
          { num: 3 },
        ])
    
        return { children }
      },
      template: `
        <div>
          <child-component 
            v-for="(child, index) in children"
            :key="child.num"
            :child-num="child.num"
            :is-first="index === 0"
            :is-last="index === children.length - 1"
          />
        </div>
      `,
    }
    
    const app = createApp({
      components: {
        'parent-component': ParentComponent,
      },
      template: `
        <parent-component />
      `,
    });
    
    app.mount('#app');
    <script src="https://unpkg.com/vue@3.3.4/dist/vue.global.prod.js"></script>
    <script src="https://cdn.tailwindcss.com"></script>
    
    <div id="app"></div>

    <div>
      <h1
        :class="{
          'bg-green-600': isFirst,
          'bg-red-600': isLast,
        }"
      >
        Child #{{ childNum }}
      </h1>
    </div>
    

    Example #2 (with peer)

    Bringing the peer modifier inside the child element is a bit more challenging. In a Tailwind CSS discussion #8777, using group-[] to monitor the default large group was suggested. It indeed works.

    const { createApp, ref } = Vue
    
    const ChildComponent = {
      props: {
        childNum: Number,
        isFirst: Boolean,
        isLast: Boolean,
      },
      template: `
        <div>
           <h1 :class="{ 'peer-checked:group-[]:bg-green-600': isFirst, 'peer-checked:group-[]:bg-red-600': isLast }">
             Child #{{ childNum }}
           </h1>
        </div>
      `,
    }
    
    const ParentComponent = {
      components: {
        'child-component': ChildComponent,
      },
      setup() {
        const children = ref([
          { num: 1 },
          { num: 2 },
          { num: 3 },
        ])
    
        return { children }
      },
      template: `
        <div>
          <child-component 
            v-for="(child, index) in children"
            :key="child.num"
            :child-num="child.num"
            :is-first="index === 0"
            :is-last="index === children.length - 1"
          />
        </div>
      `,
    }
    
    const app = createApp({
      components: {
        'parent-component': ParentComponent,
      },
      template: `
        <input type="checkbox" checked class="peer" />
        <parent-component class="group" />
      `,
    });
    
    app.mount('#app');
    <script src="https://unpkg.com/vue@3.3.4/dist/vue.global.prod.js"></script>
    <script src="https://cdn.tailwindcss.com"></script>
    
    <div id="app"></div>

    Parent

    <input type="checkbox" class="peer" />
    

    Child

    <!-- Source: https://github.com/tailwindlabs/tailwindcss/discussions/8777#discussion-4194432 -->
    
    <div>
      <h1 class="peer-checked:group-[]:bg-green-600">
        Child #{{ childNum }}
      </h1>
    </div>
    

    Example #3 (with group-peer plugin)

    Within the same discussion #8777, there was another example where a plugin was used to create a group that forwards the original peer.

    tailwind.config = {
      plugins: [
        function groupPeer({ addVariant }) {
          let pseudoVariants = [
            // ... Any other pseudo variants you want to support. 
            // See https://github.com/tailwindlabs/tailwindcss/blob/6729524185b48c9e25af62fc2372911d66e7d1f0/src/corePlugins.js#L78
            "checked",
          ].map((variant) =>
            Array.isArray(variant) ? variant : [variant, `&:${variant}`],
          );
    
          for (let [variantName, state] of pseudoVariants) {
            addVariant(`group-peer-${variantName}`, (ctx) => {
              let result = typeof state === "function" ? state(ctx) : state;
              return result.replace(/&(\S+)/, ":merge(.peer)$1 ~ .group &");
            });
          }
        },
      ],
    }
    
    const { createApp, ref } = Vue
    
    const ChildComponent = {
      props: {
        childNum: Number,
        isFirst: Boolean,
        isLast: Boolean,
      },
      template: `
        <div>
           <h1 :class="{ 'peer-checked:group-[]:bg-green-600': isFirst, 'peer-checked:group-[]:bg-red-600': isLast }">
             Child #{{ childNum }}
           </h1>
        </div>
      `,
    }
    
    const ParentComponent = {
      components: {
        'child-component': ChildComponent,
      },
      setup() {
        const children = ref([
          { num: 1 },
          { num: 2 },
          { num: 3 },
        ])
    
        return { children }
      },
      template: `
        <div>
          <child-component 
            v-for="(child, index) in children"
            :key="child.num"
            :child-num="child.num"
            :is-first="index === 0"
            :is-last="index === children.length - 1"
          />
        </div>
      `,
    }
    
    const app = createApp({
      components: {
        'parent-component': ParentComponent,
      },
      template: `
        <input type="checkbox" checked class="peer" />
        <parent-component class="group" />
      `,
    });
    
    app.mount('#app');
    <script src="https://unpkg.com/vue@3.3.4/dist/vue.global.prod.js"></script>
    <script src="https://cdn.tailwindcss.com"></script>
    
    <div id="app"></div>

    Parent

    <input type="checkbox" class="peer" />
    

    Child

    <div>
      <h1 class="group-peer-checked:bg-green-600">
        Child #{{ childNum }}
      </h1>
    </div>
    

    tailwind.config.js

    // Source: https://github.com/tailwindlabs/tailwindcss/discussions/8777#discussioncomment-3778184
    
    export default {
      plugins: [
        function groupPeer({ addVariant }) {
          let pseudoVariants = [
            // ... Any other pseudo variants you want to support. 
            // See https://github.com/tailwindlabs/tailwindcss/blob/6729524185b48c9e25af62fc2372911d66e7d1f0/src/corePlugins.js#L78
            "checked",
          ].map((variant) =>
            Array.isArray(variant) ? variant : [variant, `&:${variant}`],
          );
    
          for (let [variantName, state] of pseudoVariants) {
            addVariant(`group-peer-${variantName}`, (ctx) => {
              let result = typeof state === "function" ? state(ctx) : state;
              return result.replace(/&(\S+)/, ":merge(.peer)$1 ~ .group &");
            });
          }
        },
      ],
    }