You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Polymer 2:父页面如何移除子自定义元素的CSS内边距且不影响自身

How to override inner .main padding in a Polymer custom element from the parent page

Let's break down why your current CSS isn't working, then walk through two solid solutions to fix this.

Why your existing selectors fail

Polymer custom elements use Shadow DOM, which creates a style-isolated environment for the element's internal content. This means CSS rules from the parent page can't "penetrate" the Shadow DOM to target elements like .main inside <other-custom-element>. Your attempts with other-custom-element .main or .other-custom-element-className .main don't work because those selectors can't reach into the isolated Shadow tree.


This is the cleanest approach if you can modify the shared stylesheet:

  1. Update the shared stylesheet to use a CSS variable with a default value:
/* Shared stylesheet */
.main {
  padding: var(--main-padding, 10rem); /* 10rem is the fallback default */
}
  1. In your parent page's CSS, override this variable specifically for <other-custom-element>:
/* Parent page styles */
other-custom-element {
  --main-padding: 0;
}

This will only remove the padding for .main inside <other-custom-element> on your parent page, while leaving the default 10rem padding intact for the element elsewhere.


Solution 2: Use CSS Shadow Parts (requires modifying the custom element's template)

If you have access to edit <other-custom-element>'s template, you can expose the .main element to the parent page using a part attribute:

  1. Modify the child element's template to add the part attribute:
<!-- other-custom-element template -->
<template>
  <style include="stylesheet"></style>
  <div class="main" part="main"> stufff </div>
</template>
  1. Target the exposed part in your parent page's CSS:
/* Parent page styles */
other-custom-element::part(main) {
  padding: 0;
}

This lets you directly style the internal .main element without breaking Shadow DOM isolation.


内容的提问来源于stack exchange,提问作者Raults

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:50:24