div中内嵌并排div的显示问题

 在页面布局中,最常使用的就是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>

此时页面显示为:
图1
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>

此时页面显示为:
图2
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所示:
图3
此时就会破坏div布局。

因此,在布局子div中,要使用方式2和方式3,即float或者position属性。

  • 15
    点赞
  • 66
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值