如何设置样式:使用适当的特殊性,无需使用!root [英] How to style :root without !important using proper specificity
本文介绍了如何设置样式:使用适当的特殊性,无需使用!root的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在自定义元素内,因为在父页面上设置了边框颜色
,所以我无法制作 border-颜色
可以工作,而不必求助于!important
Inside a Custom Element because border-color
is set on the parent page, I can not make border-color
work without resorting to !important
:host([player="O"]) {
color: var(--color2);
border-color: var(--color2) !important;
}
选择器工作正常,颜色已设置,
,所以这是一个特异性问题
The selector works fine, the color is set,
so it is a Specificity issue
问题:没有!important
可能吗?
window.customElements.define('game-toes', class extends HTMLElement {
constructor() {
super();
let shadowRoot = this.attachShadow({
mode: 'open'
});
shadowRoot.innerHTML = 'Toes';
shadowRoot.appendChild(document.querySelector('#Styles').content.cloneNode(true));
}
});
:root {
--boardsize: 40vh;
--color1: green;
--color2: red;
}
game-toes {
width: var(--boardsize);
height: var(--boardsize);
border: 10px solid grey;
background: lightgrey;
display: inline-block;
}
<TEMPLATE id="Styles">
<STYLE>
:host {
display: inline-block;
font-size:2em;
}
:host([player="X"]) {
color: var(--color1);
border-color: var(--color1);
}
:host([player="O"]) {
color: var(--color2);
border-color: var(--color2) !important;
}
</STYLE>
</TEMPLATE>
<game-toes player="X"></game-toes>
<game-toes player="O"></game-toes>
Qomponents
推荐答案
您正在使用CSS变量,因此您仍然可以像这样依靠它们:
You are using CSS variable so you can still rely on them like this:
window.customElements.define('game-toes', class extends HTMLElement {
constructor() {
super();
let shadowRoot = this.attachShadow({
mode: 'open'
});
shadowRoot.innerHTML = 'Toes';
shadowRoot.appendChild(document.querySelector('#Styles').content.cloneNode(true));
}
});
:root {
--boardsize: 40vh;
--color1: green;
--color2: red;
}
game-toes {
width: var(--boardsize);
height: var(--boardsize);
border: 10px solid var(--playercolor,grey);
color:var(--playercolor,#000);
background: lightgrey;
display: inline-block;
}
<TEMPLATE id="Styles">
<STYLE>
:host {
display: inline-block;
font-size:2em;
}
:host([player="X"]) {
--playercolor: var(--color1);
}
:host([player="O"]) {
--playercolor: var(--color2);
}
</STYLE>
</TEMPLATE>
<game-toes player="X"></game-toes>
<game-toes player="O"></game-toes>
<game-toes ></game-toes>
这篇关于如何设置样式:使用适当的特殊性,无需使用!root的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文