2016-11-08 156 views
3

我正在開發一個主題型聚合物網絡組件。由於每custom-style文檔,我做了以下內容:如何將自定義樣式僅應用於特定元素?

<link rel="import" href="themes/my-element-theme.html"> 
    <style is="custom-style" include="my-element-theme"></style> 

然而,這是一把鈍刀,因爲它適用的自定義主題,以我的所有元素。

一個解決方案是我的範圍內的所有主題樣式的CSS類,如下所示:

:root custom-element.my-element-theme { 
    font-family: 'Noto Sans', 'Myriad Pro', Calibri, Helvetica, Arial, sans-serif; 
} 

然而,這使得它難以自定義樣式應用到整個文檔。

有沒有辦法將自定義樣式更有選擇性地應用到元素,比如使用CSS選擇器?什麼是最佳做法?

回答

0

您絕對可以使用選擇器來選擇性地將樣式應用到您的可移動主題元素。

最好使用自定義屬性和mixins並將其值設置爲目標元素。這裏有一個例子:

<!DOCTYPE html> 
 
<html> 
 
<head> 
 
    <link href="http://polygit.org/components/polymer/polymer.html" rel="import" /> 
 
    <style is="custom-style"> 
 
    .container1 my-elem { 
 
     --my-elem-span: { 
 
     color: red; 
 
     } 
 
    } 
 
    
 
    .container2 my-elem { 
 
     --my-elem-span: { 
 
     color: blue; 
 
     } 
 
    } 
 
    </style> 
 
</head> 
 
<body> 
 
    <div class="container1"> 
 
    <my-elem>hello red</my-elem> 
 
    </div> 
 
    <div class="container2"> 
 
    <my-elem>hello blue</my-elem> 
 
    </div> 
 
    
 
    <dom-module id="my-elem"> 
 
    <template> 
 
     <style> 
 
     :host { display: block; } 
 
     
 
     :host span { 
 
      @apply(--my-elem-span); 
 
     } 
 
     </style> 
 
     
 
     <span><content></content></span> 
 
    </template> 
 
    
 
    <script> 
 
     Polymer({ 
 
     is: 'my-elem' 
 
     }); 
 
    </script> 
 
    </dom-module> 
 
</body> 
 
</html>

而且像你這樣通過將CSS規則在一個單獨的樣式模塊可以外部化你的風格。

<dom-module id="my-elem-theme"> 
    <template> 
    <style> 
     .container1 my-elem { 
     --my-elem-span: { 
      color: red; 
     } 
     } 

    .container2 my-elem { 
     --my-elem-span: { 
     color: blue; 
     } 
    } 
    </style> 
    </template> 
</dom-module> 

然後導入你的方式:

<link rel="import" href="my-elem-theme.html"> 
<style is="custom-style" include="my-elem-theme"></style> 
相關問題