停用 css/html 中的“element.style”?

mox*_*mlb 3 html javascript css siteorigin

我在 Chrome 开发者工具窗口的“样式”选项卡中看到以下 css 代码:

element.style {
    height: auto;
    width: 100%;
    margin-top: -148px;
}
Run Code Online (Sandbox Code Playgroud)

我想用 .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; 
}
Run Code Online (Sandbox Code Playgroud)

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

Raj*_*ddy 5

您在 chrome 开发人员窗口中看到的内容就是element style编写的元素上的样式inline

element.style {
 /*this all are the inline written styles*/
}
Run Code Online (Sandbox Code Playgroud)

现在,由于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 中放置的位置)