通常我們寫 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;width:500px;height:500px;margin-left:auto;margin-right:auto;overflow:hidden;color:white;}
.white{background:white;width: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
新聞熱點
疑難解答