Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js: use CSS class for child element

I have a component v-popup.vue

<template>
  <div class="overlay">
    <div class="popup">
      <slot></slot>
    </div>
  </div>
</template>

and I want to style it from the parent, for example:

<template>
  <v-popup class="custom-popup">
    Popup content
  </v-popup>
</template>

<style>
  .custom-popup {
    padding: 20px;
  }
</style>

How can I configure v-popup.vue component to make custom-popup class to be automatically added to div.popup, not div.overlay ?

like image 590
lusarz Avatar asked Jan 01 '23 06:01

lusarz


1 Answers

Scoped Styles

  • Using scoped styles (in both parent and child) is a good idea and will make this solution easier.

  • Instead of creating a new custom-popup class, use a deep selector in the parent. This allows the parent to define extra styles for child components that use the same selector.

  • The deep selector looks like this: >>> unless you're using a SCSS/SASS pre-processor. Then you use ::v-deep instead.

<template>
  <v-popup>
    Popup content
  </v-popup>
</template>

<style scoped>
  >>> .popup {
    padding: 20px;
  }

  /* If using SCSS/SASS, do this instead */
  /*
  ::v-deep .popup {
    padding: 20px;
  }
  */
</style>

The child will use both its own .popup class and the one from the parent.

If you didn't use scoped styles, it would quickly become a problem if you wanted to import the child in multiple parents and use different styles each time.

like image 147
Dan Avatar answered Jan 05 '23 15:01

Dan