是否有可用的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;
}
}
因此,我们可以快速删除或重新设置样式,而不必声明每个属性。
在我的特定场景中,我想跳过对页面的特定部分应用通用样式,更好地说明如下:
<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
这个问题
您需要将标记插入到HTML文档中,并且它需要以特定的方式显示。此外,您不拥有此文档,因此不能更改现有的样式规则。您不知道样式表可以是什么,也不知道它们可能更改为什么。
这种情况的用例是当您为未知的第三方网站提供可显示的组件时。这方面的例子有:
广告标签
构建插入内容的浏览器扩展
任何类型的小部件
简单的修理
把所有东西都放在iframe中。这有它自己的一组限制:
跨域限制:您的内容根本无法访问原始文档。您不能覆盖内容、修改DOM等。
显示限制:你的内容被锁定在一个矩形内。
如果您的内容可以放入一个框中,那么您可以通过让内容编写iframe并显式地设置内容来绕过问题#1,因为iframe和文档将共享同一个域。
CSS解决方案
最好的方法是显式地覆盖所有可以覆盖的属性,并将它们重写为您认为它们的默认值。
即使您重写了,也无法确保更有针对性的CSS规则不会重写您的规则。在这里,您能做的最好的事情是让覆盖规则目标尽可能明确,并希望父文档不会意外地优于它:在内容的父元素上使用模糊或随机的ID,并在所有属性值定义上使用!important。
在我的特定场景中,我想跳过对页面的特定部分应用通用样式,更好地说明如下:
<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是多么的邪恶:-))