0

One of my AngularJS directives uses CSS in its template. How do I protect this CSS from external CSS classes defined by user?

 <selectable-data-list items="myItems"></selectable-data-list> 

the template consists of a div field as:

<style>
 .selectable-data-list{
     position: relative;
 }
 .selectable-data-list .someclass{
     position: absolute;
     top: 0;
     right: 0;
 }
</style>
<div class="selectable-data-list">
    <!--some additional elements -->
    <div class="someclass">something</div>
</div>

So, if a user adds a class .someclass{position: relative;}, that will have my directives required UI jumbled or messed up.

So, how do I protect it??

I know a way to do it by using some long random string as a class name. But is there an alternative way to do it?

Sreekanth Reddy Balne
  • 3,264
  • 1
  • 18
  • 44

2 Answers2

1

You can't protect your ccs. I use multiple directives and with their own css templates and I get conflicting css rules all the time.

The best thing to do is to define your css classes thoroughly for your directives. This will minimize conflicting css rules by users and yourself. Because !important will not help if you have several css rules pointing to the same object.

nitrodmr
  • 198
  • 2
  • 8
0

I don't think you can entirely protect it TBH. If you are worried about accidental overwrite you could make the classnames more unique - possibly even a generated GUID of some sort. Or consider an ID, really you are trying to make your selector more specific than any potential external CSS, and ID is specific to the element.

You can css values with !important , but you should take a look at What are the implications of using "!important" in CSS? - especially the part about "what's wrong with using !important". Even then, if the consumer creates a selector which is more specific and has the !important flag, it'll win.

Hopefully someone else will have a more definitive answer.