Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent conflicts between css rules

What is the best strategy for creating css selectors for html widgets. Those selectors should not be in conflict with child elements nor with possible general selectors.

/* this item class it is already done, has no relation with my widgets´ items
  and i can´t modify it*/        
   .item { color:red; }    

   .my-first-widget{...}
   .my-first-widget .item { color: blue; font-size:16px;}

   .my-second-widget{...} 
   .my-second-widget .item { font-size:14px;} 

Problems with the code above:

  1. If I insert my-second-widget inside a my-first-widget (but not within a my-first-widget .item), the items from my-second-widget will be blue (I want them to inherit color from it´s parent).
  2. I insert my-second-widget inside a project with a rule defined as .item , the items from my-second-widget will be red (I want them to inherit color from it´s parent; not from the unrelated general item´s class).

which is the best solution for styling exportable widgets?

Solution 1 (use parent class a prefix)

   .my-first-widget{...}
   .my-first-widget-item { color: blue; font-size:16px;}

   .my-second-widget{} 
   .my-second-widget-item { font-size:14px;}

Solution 2 (use child selectors)

   .my-first-widget{...}
   .my-first-widget > .item { color: blue; font-size:16px;}

   .my-second-widget{ color: black;} 
   .my-second-widget > .item { font-size:14px;}

With the solution2 i still have a conflict with the general .item selector...

Any other ideas?

like image 783
PsychoJohn Avatar asked Nov 01 '22 13:11

PsychoJohn


1 Answers

I think that the following might work for you.

If this is your HTML:

<div class="project">
    <div class="item">item outside widget</div>
    <div class="my-second-widget"><span class="item">item</span></div>
</div>

try this CSS:

.item {
    color:red;
}
.my-first-widget {
}
.my-first-widget .item {
    color: blue;
    font-size:16px;
}
.my-second-widget {
}
.my-second-widget .item {
    color: inherit;
    font-size:14px;
}

.project {
}

See demo at: http://jsfiddle.net/audetwebdesign/3eLpU/

Set color: inherit on .my-second-widget .item, which will force the nested .item to inherit the color value from .my-second-widget (if it is set), or the color value of .project (if it is set) or ultimately, the body (set or default value).

If the top level .item rule is present, it will be applied outside of .my-second-widget.

like image 51
Marc Audet Avatar answered Nov 09 '22 09:11

Marc Audet