如何防止样式进入div

时间:2017-06-09 18:57:44

标签: javascript html css

我有一个有趣的情况,我正试图找到解决方案。

需要包含一个脚本,用于在页面上构建HTML元素。问题是全局默认CSS样式与此构建元素交互并阻止其运行。

所以我们的“.core-design form”有一个属性,它被应用于这个构建元素的表单。我们的样式都不需要使用,因为脚本在自己的样式表中调用。

有没有办法阻止包含此元素的div从我们的.core-design获取任何和所有样式?

编辑:为细节添加一些清晰度。

1)核心设计类附加在许多站点的每个页面上。

2)目标子元素是元素名称,而不是类。

3)我能够添加样式来定位生成内容周围的div,但是由于其范围而希望避免修改.core-design样式表。

4)生成的内容会引入自己的样式表。

5)我无法控制所引入的内容,并且将来可能会发生变化。

6)Codepen of the situation I am currently in

body {
  // the .core-design is applied here which contains the form styles.
}
form {
  min-height:300px;
  min-width:300px;
  background-color:black;
}
<body>
  <div class="controlled">
    <div class="generated">
      <form>
        <!--
        I need to prevent this form/generated div from inheriting any styles. Including any other sub-components inside of it. The only item I 'control' is the wrapping div.
        -->
      </form>
    </div>
  </div>
</body>

4 个答案:

答案 0 :(得分:0)

解决方案1:

简单,它就是CSS选择器。

将一个名为ignore-this的类添加到您要忽略的表单中。

然后将全局css更新为form:not(.ignore-this)

以下示例,CSS应用于第一种形式,但跳过第二种形式。

.core-design form:not(.ignore-this) {
  background: red;
}
<div class="core-design">
  <form>
    form 111111
  </form>
  <form class="ignore-this">
    form 222222
  </form>
</div>

解决方案2(更新)

由于您无法控制core-design css,您可以做的是添加如下的css规则并将类名添加到要重置CSS样式的表单中:

form.ignore-this{
  all: unset;
}
  

CSS all速记属性会将除unicode-bidi和direction之外的所有属性重置为其初始值或继承值。

     

参考:https://developer.mozilla.org/en/docs/Web/CSS/all

     

enter image description here

.core-design form {
  background: red;
  border: 2px solid green;
}

form.ignore-this{
  all: unset;
}
<div class="core-design">
  <form>
    form 111111
  </form>
  <form class="ignore-this">
    form 222222
  </form>
</div>

答案 1 :(得分:0)

不太清楚,但我认为你有css覆盖问题。 如果您知道div的类和ID的名称,您可以更改核心设计的ID和类名,这样它们就不会相同。 喜欢: 如果你有一个名为.navi的类并且div包含.navi css将尝试覆盖div的那个或者核心的那个。 确保您的核心类和ID名称与div的唯一名称相同

答案 2 :(得分:0)

是的,有办法。您可以使用all CSS属性。更多信息https://developer.mozilla.org/en-US/docs/Web/CSS/all

不支持IE :(,但有可用的polyfill。

答案 3 :(得分:0)

这应该重置所有样式:

div.className * { 

     all: initial; 
     all: unset; 

}