隔离 div 内的样式

问题描述 投票:0回答:1

我有一些站点范围的样式和一些自定义样式,并且我希望站点范围的样式不适用于 id 为

custom-styles
的 div 或其任何包含元素。如何在不更改站点宽样式中的 CSS 的情况下实现这一点?

我尝试将

style="all: unset;"
添加到 div (即
#custom-styles, #custom-styles * {all: unset}
),但无济于事。理想情况下,我希望自定义样式 div 中的任何样式都不要从任何地方继承任何样式,以防它们弄乱任何东西。

为了提供一些上下文,用户需要能够添加自己的 CSS,并且它将与一些自定义 HTML 一起插入到他们的网站上,因此我不希望他们的任何网站样式影响自定义 HTML 的样式。我可以在某种程度上控制自定义 HTML,例如通过将他们的自定义 HTML 包装在我自己的 div 中,并使用 id 或类来添加我自己的样式。

<style>
/* sitewide styles */
*,
::before,
::after {
    margin: 0.5em;
    padding: 0.5em;
    border: none;
    box-sizing: inherit;
    font-family: 'Arial';
}
p {color: red !important}
</style>
<p>
This should be red with all the default styles
</p>
<div id='custom-styles' style="all: unset;">
<style>
/* custom styles for this div only */
p {color: green;}
</style>
<p>
I want this (and any other element within this div) to not be red and not have any default styles - it should only have the styles inside the second style tag (and, for example, be green)
</p>
</div>

html css
1个回答
0
投票

我建议避免以这种方式使用内联样式。

all: unset
规则不会影响继承的属性,除非它们被显式重置。

/* Global styles */
*, *::before, *::after {
  margin: 0.5em;
  padding: 0.5em;
  border: none;
  box-sizing: inherit;
  font-family: 'sans-serif';
  background: #222;
}

p {
  color: red !important;
}

/* Reset and customize styles within #custom-styles */
#custom-styles, #custom-styles * {
  all: unset;
  color: green !important;   /* Override global red (important)  */
  background: initial;       /* Reset background to default      */
  font-family: initial;      /* Revert to browser's default font */
}
<p>
  This should be red with all the default styles
</p>
<div id="custom-styles">
  <p>
    I want this (and any other element within this div) to not be red and not have any default styles - it should only have the styles inside the second style tag (and, for example, be green)
  </p>
</div>

© www.soinside.com 2019 - 2024. All rights reserved.