Lit-element静态样式未生效求助:仅首个元素样式生效
Hey Marcos, I see the issue with your checkbox component's styles—let's break this down and fix it!
The Root Cause
Looking at your styles getter, your second style rule uses a selector that doesn't actually match your input element:
input[checkbox i]{ background-color:red; }
This selector targets <input> elements that have a checkbox attribute (like <input checkbox>), but your component renders an input with type="checkbox". That's why this rule never applies—there's no element matching that selector in your shadow DOM.
Fixing the Selector
You have two straightforward ways to fix this:
- Use the class selector you already added to the input:
.checkbox-mj { background-color: red; } - Target the input by its type:
input[type="checkbox"] { background-color: red; }
Updated Styles Example
Here's how your corrected styles getter would look with the class selector:
static get styles() { return css` .checkWrapper{ font-family: Roboto; background-color: red; font-weight: 500; font-size:14px; color:#283D3B; border:none; outline:none; height: 150px; width: 300px; border-radius: 3px; overflow:hidden; padding:3px; } .checkbox-mj { background-color: red; } `; }
Key Notes for Lit Element Styles
Since Lit uses Shadow DOM for style encapsulation, your selectors need to be precise to match elements inside the component's shadow tree:
- Double-check selector syntax: Small mistakes (like targeting the wrong attribute) will break style application.
- Prefer class selectors over element/attribute selectors when possible—they're more explicit and less likely to break if you adjust your HTML structure later.
- If you ever need to style the component itself from within, use the
:host()pseudo-class.
This should resolve the issue where only the first style rule was working. Let me know if you run into any other snags with Lit's styling system!
内容的提问来源于stack exchange,提问作者Marcos Collado

