父子元素的宽度

父子元素的宽度

1.正常情况

<style>
    .parent{
      width: 200px;
      height: 300px;
      background-color: aquamarine;
    }
    .child{
      width: 100%;
      background-color: red;
    }
</style>
 
<div class="parent">
    <div class="child">
      hello world
    </div>
</div>

在这里插入图片描述

此时,子元素宽度等于父元素宽度,正是我们要的效果。

2.有定位的情况

<style>
    .parent{
      width: 200px;
      height: 300px;
      background-color: aquamarine;
      position:relative;
    }
    .child{
      width: 100%;
      background-color: red;
      position:absolute;
    }
</style>
 
<div class="parent">
    <div class="child">
      hello world
    </div>
</div>

此时,子元素宽度也是正常的,等于父元素宽度。

3.父元素无定位,子元素是绝对定位

<style>
    .parent{
      width: 200px;
      height: 300px;
      background-color: aquamarine;
    }
    .child{
      width: 100%;
      background-color: red;
      position:absolute;
    }
</style>
 
<div class="parent">
    <div class="child">
      hello world
    </div>
</div>

此时,子元素的宽度发生了变化,宽度等于body的宽度了。这是因为子元素设置了绝对定位,它脱离了父元素文档流,所以宽度直接和body一样了。
在这里插入图片描述

解决方法:

1.给父元素加上相对定位;

2.将子元素的width:100%;改成width:inherit;,表示继承父元素的宽度。注意:IE8不支持inherit属性

<style>
    .parent{
      width: 200px;
      height: 300px;
      background-color: aquamarine;
    }
    .child{
      width: inherit;
      background-color: red;
      position:absolute;
    }
</style>
 
<div class="parent">
    <div class="child">
      hello world
    </div>
</div>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值