我曾经佩服过google ads,它可以再任何网页上出现,而它的样式却不会被寄主网页的CSS给破坏。后来发现它其实是用的iframe,呵呵。
不过倒是引发了我一个思考:如何保证一个区域里的样式不会被外部样式“入侵”。要做到这点其实说难不难,说容易也不太容易。关键是两点:
1. 将该区域里的所有样式全部设为最初的默认值;
2. 保证上面的样式的优先级为最高。
所以呢,下面是一个尚未完善的例子:
#clearAllStyle *, #clearAllStyle a:hover, #clearAllStyle a:link, #clearAllStyle a:visited, #clearAllStyle a:active { position: static; top: auto; right: auto; bottom: auto; left: auto; z-index: auto; float: none; clear: none; display: block; margin: auto; padding: 0; border-width: medium; border-color: inherit; border-style: none; width: auto; height: auto; min-width: 0; min-height: 0; max-width: none; max-height: none; color: #000; background-attachment: scroll; background-color: transparent; background-image: none; background-position: 0% 0%; background-repeat: repeat; font-size: 12px; font-family: sans-serif; line-height: normal; font-style: normal; font-variant: normal; font-weight: normal; text-align: left; text-decoration: none; text-indent: 0; text-transform: none; white-space: normal; letter-spacing: normal; word-spacing: normal; vertical-align: baseline; overflow: visible; visibility: visible; } #clearAllStyle span, #clearAllStyle em, #clearAllStyle strong { display:inline; } #clearAllStyle a #clearAllStyle a:hover, #clearAllStyle a:link, #clearAllStyle a:visited, #clearAllStyle a:active { display:inline; text-decoration:underline; }
这个代码还处于待完善的阶段。我没有对其进行全面的测试,不过基本上能够保证绝大多数的情况了。
注意几点:
1. 我这里考虑的是将所有的CSS属性设为默认值,而并不是将所有的HTML标签设为它们默认的样式。因为其实从实践的角度,每个浏览器里HTML标签的默认样式都是不一致,不可能也没有必要将其回复到默认样式。保证样式不被外部样式入侵,这才是我们的目的。
2. 所谓的“属性的默认值”,是指在没有明确定义某个属性时,这个属性默认呈现出来的那个值。上面的值都是根据《CSS权威指南》里得到的,不过并不是所有的值都有默认值,没有的我就自己加了一个自己想要的那个值。
3. 有一个比较麻烦的问题:某些属性无法被子元素继承,比如text-align。倘若接下来有如下定义:
#clearAllStyle .copyright { text-align: center; }
对于.copyright的子元素,就会仍然靠左。解决的办法是一个很傻的写法:
#clearAllStyle .copyright, #clearAllStyle .copyright * { text-align: center; }
看起来不好看,但是应该没什么大问题。
4. a标签在IE6下,其伪类的定义会被认为是最高优先级,所以需要显式声明。(感谢OoSleePinG指出)
5. 其他还有些元素需要被归为display: inline,比如del。但是,如果我其实不用它,就没必要写了。
如果大家有什么看法,欢迎进一步讨论。