如何在自定义元素中提供后备CSS值?

问题描述 投票:1回答:1

我有一个自定义的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 />
javascript css web-component custom-element
1个回答
1
投票
根据the cascade应用顺序。

通过style属性应用的CSS位于层叠的底部。实际上,如果您

do n't>通过属性指定回落到样式表时,则通过它进行指定。因此20px是您未指定15px时的备用。


您可以使用另一个具有

较少特定性

选择器的规则集来编写后备CSS(尽管唯一比单一类型选择器(例如custom-icon)缺乏特定性的是通用选择器(*),没有帮助),因此您需要将custom-icon替换为更多特定的内容。另一个选择是采用大锤方法,并在规则集中创建所有规则!important


最好的选择可能是修复所有可能导致CSS丢失的情况。
© www.soinside.com 2019 - 2024. All rights reserved.