Search code examples
cssvue.jsvuejs3shadow-domscoped

How to apply CSS style in scoped shadow object using Vue3?


I have this sample code:

<template>
    <custom-button>
     #shadow-root (open)
     <a href="#"></a>
     <other-custom></other-custom>
    </custom-button>
</template>
<style scoped lang="scss">
  custom-button{
    :deep(a) {
     outline:1px red solid;
     }
  }
</style>

But the style does not apply. I tried with scoped and slotted but no results. How can apply a style to the anchor? Thank you.

NEW SAMPLE

test.vue

<template>
  <custom-button>
  </custom-button>
</template>

<style scoped lang="scss">
.custom-button {
  :deep(a) {
    outline: 3px red solid;
  }
}
</style>

custom-button.vue

<template>
   <a href="#">Link</a>
</template>
<script>
export default {
  name: 'custom-button',
};
</script>

This does not work using Tolbxela demo.


Solution

  • UPDATE

    Yes, it does not work for the second sample. I am not really sure why, but I suppose, that the scoped CSS will be applied only at the App level.

    But why not do it simpler and just put the style directly into the custom-button.vue?

    <template>
       <a href="#">Link</a>
    </template>
    <script>
    export default {
      name: 'custom-button',
    };
    </script>
    <style scoped>
    a {
      outline: 3px red solid;
    }
    </style>
    

    It does work well this way. Here is the updated Codesandbox

    Or you can do something like this

    <template>
     <div class="wrapper">
      <custom-button></custom-button>
     </div> 
    </template>
    
    <style scoped lang="scss">
     .wrapper > a {
        outline: 3px red solid;
     }
    </style>
    

    At first, there should be one curly bracket more in the style.

    <style scoped lang="scss">
      .custom-button {
        :deep(a) {
          outline:3px red solid;
        }
      }
    </style>
    

    Then, if you omit all custom elements, the code works as intended.

    <template>
        <button class="custom-button">
         #shadow-root (open)
         <a href="#">Link</a>
       </button>
    </template>
    

    The result

    Here is the Codesandbox