很简单的一个页面结构,外层是 .container
,然后内层是 .box1
, .box2
(.box
只是为了少写一点公共样式),.container
宽度 400px
,.box
宽度 150px
<div class="container">
<div class="box box1">
.box .box1
</div>
<div class="box box2">
.box .box2
</div>
</div>
.container {
width: 400px;
height: 300px;
background-color: lightcoral;
}
.box {
width: 150px;
height: 100px;
display: inline-block;
}
.box1 {
background-color: lightgreen;
}
.box2 {
background-color: lightblue;
}
猜一下效果,一个宽的红盒子里面,左边一个绿的,右边挨着一个蓝的?
实际上,中间有间距。也就是说,如果想给左边的盒子加一个右间距 100,希望左右分别靠两边,是不是也不可能了呢?
.margin {
margin-right: 100px;
}
如图所示,下面的那个东西被挤下去了
中间的间距本质上是个空格,回到一开始写的代码
<div class="container">
<div class="box box1">
.box .box1
</div>
<div class="box box2">
.box .box2
</div>
</div>
这里的 box1
, box2
两个标签之间 </div>换行空格空格空格</div>
实际上是有大量的空白字符的。这些在 HTML 里面表现为一个空格。 即看到的那个间距。
解决方案的话,一种是直接给外层定义一个 font-size: 0
让空格消失,但是这样需要单独给子组件设置字体大小(否则默认继承一个 0 过来),如图(文字不是没写,是字体为 0 消失了)
或者是将两个 div 相邻,即如下,同样可以解决,效果如图
<div class="box box1 margin">
.box .box1 .margin
</div><div class="box box2">
.box .box2
</div>