inlineblock 元素的空隙

几个 inline-block 元素,比如 button,如果在 HTML 中连续写在一起,则它们之间可以没有空隙。但是如果在 HTML 中将它们分行格式化,则它们之间有空隙。例如:

<!DOCTYPE html>
<html>
<head>
<style type="text/css">
button {
  margin: 0;
  border: 1px solid gray;
}
</style>
</head>
<body>
<div>
<button>One</button><button>Two</button><button>Three</button>
</div>
<div>
<button>One</button>
<button>Two</button>
<button>Three</button>
</div>
</body>
</html>

这个问题的解决方法有不少,其中常用的是这 3 种:一、使用浮动;二、使用零 font-size;三、使用负 margin。具体例子如下:

<!DOCTYPE html>
<html>
<head>
<style type="text/css">
div {
  margin: 10px;
}
button {
  margin: 0px;
  border: 1px solid gray;
}
#float-left button {
  float: left;
}
#zero-size {
  font-size: 0;
}
#zero-size button {
  font-size: 14px;
}
#negative-margin {
  font-size: 14px;
}
#negative-margin button {
  margin-left: -7px;
}
</style>
</head>
<body>
<div id="float-left">
<button>First</button>
<button>Second</button>
<button>Third</button>
</div>
<div id="zero-size">
<button>First</button>
<button>Second</button>
<button>Third</button>
</div>
<div id="negative-margin">
<button>First</button>
<button>Second</button>
<button>Third</button>
</div>
</body>
</html>

 第一种方法使用了浮动,它的缺点在于,无法直接将父元素居中显示,要居中只能在外边再包一层 div。第二种方法设置父元素的 font-size 为 0,它的缺点在于,在 Android 自带浏览器上会有问题,而且子元素字体不能用 em 或者比例长度。最后一种方法使用负的 margin,它的缺点在于,这个负的 margin-left 值与父元素的字体大小有关,一般是该字体大小的一半,但是它的可靠性值得怀疑,例如在 IE6 和 IE7 中就不对。

在上面几种方法中,通过增加负的 margin-left,我们还可以使得相邻元素的 border 重合,从而可以得到按钮组这种效果。例如:

button {
  margin: 0px;
  border: 1px solid gray;
}
#float-left button {
  float: left;
  margin-left: -1px;
}
#zero-size {
  font-size: 0;
}
#zero-size button {
  font-size: 14px;
  margin-left: -1px;
}
#negative-margin {
  font-size: 14px;
}
#negative-margin button {
  margin-left: -8px;
}

参考资料:
[1] Fighting the Space Between Inline Block Elements | CSS-Tricks
[2] Bootstrap · Components #buttonGroups
[3] Using font-size: 0 to remove inline-block white-space does not work on Android Browser
[4] web表单设计漫谈之一input按钮在各浏览器之间的兼容性
[5] CSS3 patterned buttons - RedTeamDesign
[6] CSS3 GitHub Buttons
[7] Google+ UI Buttons - Shrapp.nl
[8] CSS3 Buttons – 10+ Awesome Ready-To-Use Solutions

原文地址:https://www.cnblogs.com/zoho/p/2908195.html