3

我在 Chrome 开发人员工具窗口的“样式”选项卡中看到了这个 css 代码:

element.style {
    height: auto;
    width: 100%;
    margin-top: -148px;
}

我想用我的 .css 文件中的这个 css 代码覆盖它:

.so-widget-sow-simple-masonry-simple-masonry-d75171398898 .sow-masonry-grid-item img {
    width: auto;
    height: 244px;
    margin-top: 0px;
    margin-left: auto;
    margin-right: auto; 
}

但是 的样式定义element.style已经存在。我找不到 .js 这么快。有人能帮我吗?谢谢

4

4 回答 4

5

您在 chrome 开发人员窗口中看到的element style内容与写入的元素样式一样inline

element.style {
 /*this all are the inline written styles*/
}

现在,由于CSS PrioritiesBut with this codes the element.style is allready there,您无法覆盖样式。在这种情况下,规则是内联 CSS 比外部 CSS 具有更高的优先级

所以,你可以做什么??

  1. 你必须要么remove the inline css写在哪里。这样你的外部 css 将适用

  2. 如果由于某种原因您无法修改内联 CSS,那么唯一的选择是set the styles as !important在您的外部 CSS 文件中。这里的人已经提到了这个解决方案,但并不总是推荐这样做。

  3. 获取写在该元素上的所有内联 CSS,并在您的外部文件中创建一个新类,然后将其放在那里,现在将这个类名称赋予该元素。所以原始样式被应用回来。现在指向您必须覆盖的新样式。使用 2 个类时还有新的 CSS 优先级规则。CSS rule which is read last (in the css file, not the order you put in the element) will have priority. 因此,请确保将新的 CSS 规则放在刚刚创建的其他类下方,如上所述。

    • 如果您必须使用 2 个单独的文件来编写这 2 个类怎么办?然后是另一个 CSS 优先级规则。The file that is placed last in the DOM will have the priority(记住它不是在文件加载到 DOM 时,而是关于它在 DOM 中的位置)
于 2016-03-09T09:37:16.697 回答
2

您可以将 !important 添加到每种样式的末尾。

例如使用这个:

height: 244px !important;

代替

height: 244px;
于 2016-03-09T09:18:46.360 回答
1

你总是可以选择:

.so-widget-sow-simple-masonry-simple-masonry-d75171398898 .sow-masonry-grid-item img {
width: auto !important;
height: 244px !important;
margin-top: 0px !important;
margin-left: auto;
margin-right: auto; 
}

重要样式将覆盖内联样式,除非内联样式也有!important子句(但这实际上很少见)。

于 2016-03-09T08:58:28.493 回答
1

当然,您可以删除style元素上的属性:

element.removeAttribute('style');

如果element.style消失了,您的 CSS 文件的规则将可见。

于 2016-03-09T08:59:09.950 回答