為什么font-size為0后margin也為0,但line-height為0后margin卻不為0?
在這個問題下:
在按鈕1~4后添加文字后,為什么trigger按鈕上方出現(xiàn)了空格
看到了這個答案:
那不是間距 是 由于 文符帶來的基線冗余,其實就是行高,解決辦法就是font-size:0或者line-height:0;
改了font-size之后的確消除了間距(使margin為0了)
但是改了line-height之后卻沒用
這是font-size的代碼:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>浮動去空格</title>
<style>
button { margin: 0; }
p { clear: both; }
</style>
</head>
<body style="font-size:0;">
<button>按鈕1</button><button>按鈕2</button><button>按鈕3</button><button>按鈕4</button><p><input type="button" id="trigger" value="點擊按鈕浮動"></p>
<script>
var trigger = document.getElementById("trigger"),
? ? buttons = document.getElementsByTagName("button");
var length = buttons.length;
if (trigger && length > 0) {
trigger.onclick = function() {
for (var index = 0; index < length; index += 1) {
buttons[index].style["cssFloat" in trigger.style? "cssFloat": "styleFloat"] = "left";
}
};
}
</script>
</body>
</html>
效果(的確消除了間距,使margin為0了):
這是line-height的代碼:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>浮動去空格</title>
<style>
button { margin: 0; }
p { clear: both; }
</style>
</head>
<body style="line-height:0;">
<button>按鈕1</button><button>按鈕2</button><button>按鈕3</button><button>按鈕4</button><p><input type="button" id="trigger" value="點擊按鈕浮動"></p>
<script>
var trigger = document.getElementById("trigger"),
? ? buttons = document.getElementsByTagName("button");
var length = buttons.length;
if (trigger && length > 0) {
trigger.onclick = function() {
for (var index = 0; index < length; index += 1) {
buttons[index].style["cssFloat" in trigger.style? "cssFloat": "styleFloat"] = "left";
}
};
}
</script>
</body>
</html>
效果(沒有消除間距,margin不為0):
2017-08-24
可以呀,我把你代碼復(fù)制過來試下,完全可以,但你的button標簽后沒有文字,效果不是很明顯,
這里有三種方法可以實現(xiàn)margin為0,達到?jīng)]有空格的效果,
1、font-size設(shè)置為0,如果button后面有文字,這個方法就不太好,font-size為0后,文字根本顯示不出來,而且,不用點擊按鈕,按鈕就自動聚在一起,
2、line-height,line-height不要設(shè)置為0,不然效果出來會很丑,行高和按鈕高度一樣就可以了,我這里設(shè)置的是32px,而且可實現(xiàn)點擊,
3、margin 明明沒設(shè)置,但它存在,是因為一些默認樣式,去掉默認就好了,可以添加*{margin:0;padding:0;}語句,就可以了
你可以試試
2017-07-28