是否有可用的CSS规则可以删除之前在样式表中为特定元素设置的任何样式?

一个很好的例子可能是在一个移动优先的RWD站点中,在这个站点中,用于小屏幕视图中的特定元素的许多样式都需要“重置”或删除桌面视图中的相同元素。

一个CSS规则可以实现如下功能:

.element {
  all: none;
}

使用示例:

/* mobile first */
.element {
   margin: 0 10;
   transform: translate3d(0, 0, 0);
   z-index: 50;
   display: block;
   etc..
   etc..
}

@media only screen and (min-width: 980px) {
  .element {
    all: none;
  }
}

因此,我们可以快速删除或重新设置样式,而不必声明每个属性。


当前回答

你有没有可能在找!重要规则?它不会撤销所有声明,但它提供了一种重写它们的方法。

当在样式声明上使用!important规则时,该声明将覆盖CSS中所做的任何其他声明,无论它位于声明列表中的哪个位置。虽然,important与专一性无关。

https://developer.mozilla.org/en-US/docs/CSS/Specificity The_ !important_exception

其他回答

对于那些试图弄清楚如何真正从元素中删除样式,而不从文件中删除css的人,这个解决方案使用jquery:

$('.selector').removeAttr('style');

如果你在类中设置CSS, 你可以使用jQuery removeClass()方法轻松删除它们。 下面的代码删除了.element类:

    <div class="element">source</div>   
    <div class="destination">destination</div>
      <script>
        $(".element").removeClass();
      </script>

如果未指定参数,则该方法将删除 所选元素中的所有类名。

在我的特定场景中,我想跳过对页面的特定部分应用通用样式,更好地说明如下:

<body class='common-styles'>
    <div id='header'>Wants common styles</div>
    <div id='container'>Does NOT want common styles</div>
    <div id='footer'>Wants common styles</div>
</body>

在打乱CSS重置并没有带来多大成功(主要是因为规则优先级和复杂的样式表层次结构)之后,出现了无处不在的jQuery来拯救它,它很快就完成了这项工作,而且相当脏:

$(function() {
    $('body').removeClass('common-styles');
    $('#header,#footer').addClass('common-styles');
});

(现在告诉你用JS来处理CSS是多么的邪恶:-))

更好的解决方案

下载“复制/粘贴”样式表,将css属性重置为默认值(UA样式): https://github.com/monmomo04/resetCss.git

Thanks@Milche Patern! I was really looking for reset/default style properties value. My first try was to copy the computed value from the browser Dev tool of the root(html) element. But as it computed, it would have looked/worked different on every system. For those who encounter a browser crash when trying to use the asterisk * to reset the style of the children elements, and as I knew it didn't work for you, I have replaced the asterisk "*" with all the HTML tags name instead. The browser didn't crash; I am on Chrome Version 46.0.2490.71 m. At last, it's good to mention that those properties will reset the style to the default style of topest root element but not to the initial value for each HTML element. ‎So to correct this, I have taken the "user-agent" styles of webkit based browser and implemented it under the "reset-this" class.

Useful link:

下载“复制/粘贴”样式表,将css属性重置为默认值(UA样式): https://github.com/monmomo04/resetCss.git

用户代理风格: 浏览器默认的HTML元素CSS http://trac.webkit.org/browser/trunk/Source/WebCore/css/html.css

Css的特殊性(注意特殊性): https://css-tricks.com/specifics-on-css-specificity/

https://github.com/monmomo04/resetCss.git

如果有人来这里寻找一个答案,利用iframe在这里

<iframe srcdoc="<html><body>your-html-here</body></html>" />

https://caniuse.com/iframe-srcdoc