Apply css in dynamic injected html Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Apply css in dynamic injected html without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I am doing something like StackOverflow editor. Fetch markdown text, transfer it to HTML, and inject it into the preview area. But when I tried to apply CSS to the injected HTML elements, it was ignored. In browser inspection, I can not find the stylesheet I write for the elements. I guess this is about the order of CSS rendering. Any suggestion will be appreciated.

<template>
  <div>
    <div class="item">
      <label for="content">Contents</label>
      <textarea name="content" id="content" v-model="mdtext"></textarea>
    </div>
    <div id="preview"></div>
  </div>
</template>

<script>
import marked from 'marked'

export default {
  data () {
    return {
      mdtext: ''
    }
  },
  watch: {
    mdtext: function () {
      document.getElementById('preview').innerHTML = marked(this.mdtext)
    }
  }
}
</script>

<style scoped>
...
#preview p{
  width: 100%;
  word-break: break-all;
  word-wrap: break-word;
}
...
</style>

enter image description here

Answer

You’re using scoped css, which makes Vue add that data-v- attribute to the p as well. However, the generated <p> doesn’t not have that same data-v- attribute, which is why it’s not working.
You can easily fix it by using the deep selector:

<style scoped>
#preview >>> p {

}
</style>

Reference: https://vue-loader.vuejs.org/guide/scoped-css.html#deep-selectors

We are here to answer your question about Apply css in dynamic injected html - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji