我有一个自定义的Web组件,它基本上是一个SVG图标:
<custom-icon>
<svg>{svg-stuff}</svg>
</custom-icon>
我希望能够通过像这样应用CSS来更改它的大小:
custom-icon {
width: 20px;
}
但是我也想在没有应用CSS时有一个默认的默认值,但是当我内联某些<custom-icon style="width:15px">
之类的CSS时,它将覆盖我随后应用的所有CSS。我如何才能让默认的“ 15px”仅在没有自定义CSS的情况下适用?
MWE:
class CustomIcon extends HTMLElement {
constructor() {
super();
let size = "100px"
this.style.height = size;
this.style.width = size;
this.style.background = "firebrick"
this.style.display = "block"
}
}
window.customElements.define('custom-icon', CustomIcon);
custom-icon {
--icon-size: 50px;
height: var(--icon-size);
width: var(--icon-size);
}
<custom-icon></custom-icon>
通过style
属性应用的CSS位于层叠的底部。实际上,如果您
do n't>通过属性指定回落到样式表时,则通过它进行指定。因此20px
是您未指定15px
时的备用。
较少特定性
选择器的规则集来编写后备CSS(尽管唯一比单一类型选择器(例如custom-icon
)缺乏特定性的是通用选择器(*
),没有帮助),因此您需要将custom-icon
替换为更多特定的内容。另一个选择是采用大锤方法,并在规则集中创建所有规则!important
。