html中三个盒子并排间距

如题所述

第1个回答  2022-12-13
div盒子并排显示在各大网页中是很寻常的页面效果,但是实现这种效果的方法确不止一种

方法一:使用float

.father{
width: 660px;
height: 150px;
margin: 0 auto;
border: 2px solid red;
overflow: hidden;
}
.son{
width: 150px;
height: 150px;
float: left;
text-align: center;
line-height: 150px;
margin-right: 20px;
}
.last{
margin-right: 0;
}
<div class="father">
<div class="son" style="background-color: pink;">son1</div>
<div class="son" style="background-color: rebeccapurple;">son2</div>
<div class="son" style="background-color: sandybrown;">son3</div>
<div class="son last" style="background-color: slategrey;">son4</div>
</div>
登录后复制

原本的浮动之后再设置外边距,外层盒子的宽度会不够导致最后一个盒子在第二排显示
为什么不显示?
原因:父元素:660px < 150px4 + 20px4 = 680px
因此还需要再重新定义最后一个盒子的右外边距为0

方法二:使用 display:inline-block

.father{
width: 660px;
height: 150px;
margin: 0 auto;
border: 2px solid red;
font-size: 0;
}
.son{
width: 150px;
height: 150px;
display: inline-block;
*display: inline;
*zoom: 1;
text-align: center;
line-height: 150px;
margin-right: 20px;
font-size: 14px;
}
.last{
margin-right: 0;
}
<div class="father">
<div class="son" style="background-color: pink;">son1</div>
<div class="son" style="background-color: rebeccapurple;">son2</div>
<div class="son" style="background-color: sandybrown;">son3</div>
<div class="son last" style="background-color: slategrey;">son4</div>
</div>
登录后复制
但是使用 display:inline-block会出现一些情况,比如
相似回答