5

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?

4

1 回答 1

2

我认为以下内容可能对您有用。

如果这是您的 HTML:

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

试试这个 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 {
}

参见演示:http: //jsfiddle.net/audetwebdesign/3eLpU/

设置color: inheriton .my-second-widget .item,这将强制嵌套.item.my-second-widget(如果已设置)或(如果已设置)的颜色值.project或最终从主体(设置或默认值)继承颜色值。

如果存在顶级.item规则,它将在.my-second-widget.

于 2013-10-02T11:20:23.390 回答