区别display: inline \ display: inline-block \ display: block :
display: block 与 display: inline 相比,主要区别在于 display: inline-block 允许在元素上设置宽度和高度。
如果设置了 display: inline-block,将保留上下外边距/内边距,而 display: inline 则不会。
与 display: block 相比,主要区别在于 display:inline-block 在元素之后不添加换行符,因此该元素可以位于其他元素旁边。
html部分:
<div id="r_box_bottom">
<h2 id="h_box_bottom">旅游百宝箱</h2>
<div class="box">
<a href="###" class="trea1">天气预报</a>
<a href="###" class="trea2">火车票查询</a>
<a href="###" class="trea3">航空查询</a>
<a href="###" class="trea4">地铁线路查询</a>
</div>
</div>
在还没有设置css使,盒子模型如上,a标签还是个袋子,它没有固定的宽高,里面的内容都堆叠在一起,也就是图片和文字重叠,它的宽度随标签里的内容的尺寸而定。如图下删除display效果图示意;
在设置css后,
css部分:
#r_box_bottom{
width: 400px;
height: 160px;
margin-left: 10px;
border: 1px solid #DCDCDC;
padding-top: 0px;
}
#r_box_bottom .box a {
display: inline-block; <!--注意区别 -->
width: 180px;
height: 40px;
line-height: 40px;
margin: 2px 0;
text-align: left;
text-indent: 35px;
color: #999;
}
#r_box_bottom .box a.trea1 {
background: #eee url(images/trea1.png) no-repeat 10px center;
margin-left: 20px;
}
#r_box_bottom .box a.trea2 {
background: #eee url(images/trea2.png) no-repeat 10px center;
}
#r_box_bottom .box a.trea3 {
background: #eee url(images/trea3.png) no-repeat 10px center;
margin-left: 20px;
}
#r_box_bottom .box a.trea4 {
background: #eee url(images/trea4.png) no-repeat 10px center;
}
01、无display效果
#r_box_bottom .box a {
<!--删除display: inline-block;的效果 ,发现宽180在a标签里并没有起作用, -->
width: 180px;
height: 40px;
line-height: 40px;
margin: 2px 0;
text-align: left;
text-indent: 35px;
color: #999;
}
02、有display效果,之display: inline;
#r_box_bottom .box a {
display: inline; <!-- 和删除display效果一样,因为a标签本身是内联元素 -->
width: 180px;
height: 40px;<!-- -->
line-height: 40px;
margin: 2px 0;
text-align: left;
text-indent: 35px;
color: #999;
}
03、有display效果,之display: inline; 之增加多个a标签
所以inline不是在一行显示,超过行宽还是要自动换行的
04、有display效果,之display: block;
#r_box_bottom .box a {
display: block; <!-- 和删除display效果一样,因为a标签本身是内联元素 -->
width: 180px;
height: 40px;<!-- -->
line-height: 40px;
margin: 2px 0;
text-align: left;
text-indent: 35px;
color: #999;
}
通过display: block; 把a标签内联元素转换为块级元素,现在可以设宽高,调整 float 、margin来达到效果,还要多加一个盒子。 增加了代码量以及时间成本。
总之:
使用 display: inline-block,将保留上下外边距/内边距,类似于在软袋子里装盒子。接受它是一个内联元素的同时,允许在此内联元素内添加硬盒子。
display: block; display: inline ;即为内联元素与块元素之的单纯转换。