Polymer 2,在来自父级的自定义元素中更改 CSS

Polymer 2, change CSS in custom element from parent

假设我有一个自定义元素

<template>
<style include="stylesheet"></style>
<div class="main">
stufff
<other-custom-element></other-custom-element>
</div>
</template>

并且"other-custom-element"是

<template>
<style include="stylesheet"></style>
<div class="main">
stufff
</div>
</template>

并且"stylesheet"是

.main {
  padding: 10rem;
}

如果不从该元素中删除填充,我该如何做到这一点,以便来自 "other-custom-element" 的填充不会显示在自定义元素上?当我在父页面时,只希望填充消失。

到目前为止我已经尝试过:

other-custom-element .main{
  padding: 0;
}

并给 "other-custom-element" 一个 class 并尝试:

.other-custom-element-className .main {
  padding: 0;
}

我不是很擅长 Polymer,我也没有制作这个网站,我只是 CSS 让它看起来不错的人。我认为在我继续尝试解决这个问题的同时在这里提问也没什么坏处,以防有人早点发现或已经知道。如果我在有人回答之前找到解决方案,我一定会分享。

尝试删除 other-custom-element.other-custom-element-className 这些会破坏它。问题是 Polymer 使用 ShadowRoot,它不允许 css 更改它的 children。因此,每个聚合物元素都需要自己的 css 文件,该文件始终与元素本身相关。您会找到文档 here.

据我所知,简短的回答是,您不能从父元素更改子元素参数,至少不能肯定是我这样做的方式。这是我发现的,我的解决方案是有效的。

因此,我将为问题添加一些维度,以便您理解我的解决方案以及我这样做的原因。

<other-custom-element>是一个页面,它所在的元素也是一个页面。两者都是页面,因此都需要边距等,我无法删除它们。解决方案是按照它本来的用途(在我看来)使用聚合物:制作一页元素。

做聚合的一种方法是让页面充满可互换的元素。这样如果你想再次使用它们就可以了。

这意味着让 <other-custom-element> 看起来像这样:

<template>
<style include="stylesheet"></style>
<style> /*custom css*/ </style>
<div class="main">
<other-page-element1></other-page-element1>
</div>
<div class="main">
<other-page-element2></other-page-element2>
</div>
<div class="main">
<other-page-element3></other-page-element3>
</div>
</template>

而不是这个:

<template>
<style include="stylesheet"></style>
<style> /*custom css*/ </style>
<div class="main">
stuff
</div>
</template>

这让我现在可以做的是使用新页面,我可以像这样简单地从 <other-custom-element> 页面中提取元素(无论是部分还是全部)。

<template>
<style include="stylesheet"></style>
<style> /*custom css*/ </style>
<div class="main">
<this-page-element>
</div>
<div class="main">
<other-page-element2>
</div>
</template>

这是处理这个问题的正确方法,而不是尝试做一些 css 选择器(无论如何都行不通)。

希望我的回答能帮助遇到 css 聚合物问题的其他人!