利用小数解析差异解决浏览器兼容性问题

通常我们写 css 的时候写的数字都是整数,如 font-size:12px; margin:20px; 那么看到标题可能有人会问,css 属性值可以有小数点么?如果是小数那会显示成什么样子?和整数有什么区别?

首先我们先看个例子,通过例子来观察下小数在各个浏览器的差异。

复制代码
<!DOCTYPE HTML>
<html lang="en-US">
<head>
    <meta charset="UTF-8">
    <title>decimal</title>
    <style type="text/css">
    body{font-family:SimSun;text-align:center;}
    p{margin:20px;height:30px;}
    .font11-9{font-size:11.9px;}
    .font11-4{font-size:11.4px;}
    </style>
</head>
<body>
    <p class="font11-9">这段文字的大小是11.9像素。</p>
    <p class="font11-4">这段文字的大小是11.4像素。</p>
</body>
</html>
复制代码

我们可以看出在 chrome,firefox,ie8 下小数会通过四舍五入的方式转成整数,而 ie6,ie7 会对小数进行下限取整转成整数。通过这一特性我们在某些情况下,用小数来替代 css hack。譬如:

复制代码
<!DOCTYPE HTML>
<html lang="en-US">
<head>
    <meta charset="UTF-8">
    <title>decimal</title>
    <style type="text/css">
    body{font-family:SimSun;font-size:30px;}
    .black{background:black;500px;height:500px;margin-left:auto;margin-right:auto;overflow:hidden;color:white;}
    .white{background:white;100px;height:100px;margin:0.9px;}
    </style>
</head>
<body>
    <div class="black">
        <div class="white"></div>
        <p>在ie6,ie7下红色块离黑色块没有外边距,而其他的浏览器则有 1px 外边距。一般我们是写css hack,如margin:1px;*margin:0;但是我们现在可以通过小数来解决啦。</p>
    </div>
</body>
</html>
复制代码

不仅仅缩短的代码的长度,还去掉了 css hack。

总结:虽说这个小数解决一些兼容性问题很神奇,但是它的缺点也很明显,就是适用范围,只能解决相差1像素的浏览器差异,只能解决 ie6,ie7 下值小1像素的浏览器差异。

浏览器:chrome,firefox,ie8,ie7,ie6

原文地址:https://www.cnblogs.com/axl234/p/3865858.html