div中内嵌并排div的显示问题
在页面布局中,最常使用的就是div标签,经常会出现div中内嵌div的情形,这时,子div的排列就相当重要。下面推荐两种方式。**1. 当需要两个div并排显示,并拥有同一个父div时:**<div style="width: 500px; height: 300px; background-color: red;"><div style="width: 250px; heigh
·
在页面布局中,最常使用的就是div标签,经常会出现div中内嵌div的情形,这时,子div的排列就相当重要。下面推荐两种方式。
**
1. 当需要两个div并排显示,并拥有同一个父div时:
**
<div style="width: 500px; height: 300px; background-color: red;">
<div style="width: 250px; height: 150px; display: inline-block; background-color: green;">
</div>
<div style="width: 250px; height: 150px; background-color: grey; display: inline-block; margin-left: 0;">
</div>
</div>
此时页面显示为:
div之间默认有个间隔。需要把子div的总长度减少才能在一排显示。
**
2. 使用float属性时:
**
<div style="width: 500px; height: 300px; background-color: red;">
<div style="width: 250px; height: 150px; display: inline-block; background-color: green; float: left;">
</div>
<div style="width: 250px; height: 150px; background-color: grey; display: inline-block; margin-left: 0; float: left;">
</div>
</div>
此时页面显示为:
div之间没有间隔并且并排显示,但是此时脱离了文档流,即灰色div也必须要用float: left属性,不然就会覆盖绿色div。
**
3. 使用position属性:
**
<div style="width: 500px; height: 300px; background-color: red; position: relative;">
<div style="width: 250px; height: 150px; display: inline-block; background-color: green;">
</div>
<div style="width: 250px; height: 150px; background-color: grey; display: inline-block; position: absolute;">
</div>
</div>
这时能达到和图2同样的效果,原理也一样,position: absolute能使div脱离文档流。
**
4. 当我们在并排div中加标签时,若使用方式1:
**
<div style="width: 500px; height: 300px; background-color: red;">
<div style="width: 250px; height: 150px; display: inline-block; background-color: green;">
<div style="width: 100%; height: 75px; background-color: blue;">
<span>div1</span>
</div>
<div style="width: 100%; height: 75px; background-color: pink;">
<span>div2</span>
</div>
</div>
<div style="width: 240px; height: 150px; background-color: grey; display: inline-block;">
<span>div3</span>
</div>
</div>
如图3所示:
此时就会破坏div布局。
因此,在布局子div中,要使用方式2和方式3,即float或者position属性。
更多推荐
已为社区贡献1条内容
所有评论(0)