把CSS全部归零

本文介绍了一种通过CSS将特定区域的样式与外部样式隔离的方法,确保内部样式不受外部影响。作者详细列举了实现这一目标所需的CSS属性设置,并讨论了实践中可能遇到的问题及解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我曾经佩服过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。但是,如果我其实不用它,就没必要写了。

如果大家有什么看法,欢迎进一步讨论。

转载于:https://www.cnblogs.com/ddshou/archive/2009/05/05/1449724.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值