We are having rich text editor in which we can insert html. if any input contains <style>
tag then the css is applied to entire window.
is it possible to restrict that CSS to be applied within <div>
not entire window?
7
Yes, it is possible. HTML 5 supports the scoped attribute on style tags, which restricts styles defined within to being applied only to the descendants of its parent. An example below (shamelessly pulled and edited from the MDN article).
You could check your user input for style tags and add the scoped
attribute, if not already present, either before the content is stored, or before you render it to the page.
<article>
<div>
The scoped attribute allows for you to include style elements mid-document.
Inside rules only apply to the parent element.
</div>
<p>This text should be black. If it is red your browser does not support the scoped attribute.</p>
<section>
<style scoped>
p { color: red; }
</style>
<p>This should be red.</p>
<div>
<p>This should also be red</p>
</div>
</section>
</article>
3