如何通过自定义类覆盖Web组件:host伪元素的margin-top属性?
解决Web组件宿主元素顶部外边距移除问题
你当前的写法问题在于嵌套了:host伪元素,浏览器无法识别这种嵌套语法,所以样式不会生效。
原错误代码:
:host(.remove-margin-top) { :host { margin-top: 0; } }
正确写法
直接通过:host(.remove-margin-top)选中带有remove-margin-top类的组件宿主元素,然后设置margin-top: 0即可:
:host { margin-top: auto; } :host(.remove-margin-top) { margin-top: 0; }
原理说明
:host(.remove-margin-top)的选择器优先级比基础的:host更高,所以当组件添加remove-margin-top类时,新的margin-top: 0会覆盖原来的margin-top: auto。
如果需要更灵活的控制,也可以用属性选择器的方式:
:host([remove-margin-top]) { margin-top: 0; }
使用时给组件添加属性即可:<your-component remove-margin-top></your-component>
内容的提问来源于stack exchange,提问作者Emiliano Rodriguez
相关产品推荐
相关产品推荐

