父亲有一个宽高,儿子若不设定宽高会继承,继承宽的100%,高度靠自己内容撑开。

2、padding对儿子宽的影响

  看代码:

<style>
    .father{
        width:200px;
        height:200px;
        background:red;
    }
    .son{
        background:purple;
    }
</style>
<body>
    <div class="father">
        <div class="son">123</div>
    </div>
</body>    

这个时候,儿子完全继承父亲的宽,高度有自己的内容高度撑开。运行结果:

Padding和父子继承宽高之间的关系

这个时候,修改代码,在.son中加上padding-left:50px;会发现盒子宽度并没与改变。

<style>
    .father{
        width:200px;
        height:200px;
        background:red;
    }
    .son{
        background:purple;
        padding-left:50px;//新添加的
    }
</style>
<body>
    <div class="father">
        <div class="son">123</div>
    </div>
</body>    

运行结果如图所示:

Padding和父子继承宽高之间的关系

可是如果你非要再给儿子加上一个width,无论是width:100%还是width:200px;这个时候,padding就会起作用。

<style>
    .father{
        width:200px;
        height:200px;
        background:red;
    }
    .son{
        background:purple;
        width:100%;//新添加的
        padding-left:50px;
    }
</style>
<body>
    <div class="father">
        <div class="son">123</div>
    </div>
</body>    

运行结果:

Padding和父子继承宽高之间的关系

 

总之,宽度最好能不写就不写。CSS细枝末节太多了吧!

 

相关文章:

  • 2022-02-12
  • 2021-12-10
  • 2021-10-15
  • 2022-01-04
  • 2022-03-05
  • 2021-05-29
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-01-10
  • 2021-12-24
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-24
  • 2021-11-11
相关资源
相似解决方案