更新:因为它是 2021 年,使用flexbox甚至更好 - CSS 网格布局而不是inline-block
.
使用inline-block
元素时,这些元素之间总会存在whitespace
问题(该空间大约为 4px 宽)。
所以,你的两个divs
都有 50% 的宽度,加上whitespace
(~ 4px) 的宽度超过 100%,所以它会中断。您的问题示例:
body{
margin: 0; /* removing the default body margin */
}
div{
display: inline-block;
width: 50%;
}
.left{
background-color: aqua;
}
.right{
background-color: gold;
}
<div class="left">foo</div>
<div class="right">bar</div>
有几种方法可以解决这个问题:
1.这些元素之间没有空格
body{
margin: 0; /* removing the default body margin */
}
div{
display: inline-block;
width: 50%;
}
.left{
background-color: aqua;
}
.right{
background-color: gold;
}
<div class="left">foo</div><div class="right">bar</div>
2. 使用 HTML 注释
body{
margin: 0; /* removing the default body margin */
}
div{
display: inline-block;
width: 50%;
}
.left{
background-color: aqua;
}
.right{
background-color: gold;
}
<div class="left">foo</div><!--
--><div class="right">bar</div>
3. 将父母设置font-size
为0
,然后为inline-block
元素添加一些值
body{
margin: 0; /* removing the default body margin */
}
.parent{
font-size: 0; /* parent value */
}
.parent > div{
display: inline-block;
width: 50%;
font-size: 16px; /* some value */
}
.left{
background-color: aqua;
}
.right{
background-color: gold;
}
<div class="parent">
<div class="left">foo</div>
<div class="right">bar</div>
</div>
4.在它们之间使用负边距(不优选)
body{
margin: 0; /* removing the default body margin */
}
div{
display: inline-block;
width: 50%;
margin-right: -4px; /* negative margin */
}
.left{
background-color: aqua;
}
.right{
background-color: gold;
}
<div class="left">foo</div>
<div class="right">bar</div>
5. 下降闭合角
body{
margin: 0; /* removing the default body margin */
}
div{
display: inline-block;
width: 50%;
}
.left{
background-color: aqua;
}
.right{
background-color: gold;
}
<div class="left">foo</div
><div class="right">bar</div>
<hr>
<div class="left">foo</div><div class="right">
bar</div>
6. 跳过某些HTML 结束标签(感谢@thirtydot 提供参考)
body{
margin: 0; /* removing the default body margin */
}
ul{
margin: 0; /* removing the default ul margin */
padding: 0; /* removing the default ul padding */
}
li{
display: inline-block;
width: 50%;
}
.left{
background-color: aqua;
}
.right{
background-color: gold;
}
<ul>
<li class="left">foo
<li class="right">bar
</ul>
参考:
- 在 CSS 技巧上对抗内联块元素之间的空间
- 删除行内块元素之间的空格 by David Walsh
- 如何删除行内块元素之间的空间?
正如@MarcosPérezGude 所说,最好的方法是使用, 并在标签上rem
添加一些默认值(如HTML5Boilerplate)。例子:font-size
html
html{
font-size: 1em;
}
.ib-parent{ /* ib -> inline-block */
font-size: 0;
}
.ib-child{
display: inline-block;
font-size: 1rem;
}