前端笔试中关于padding/margin问题的一些基础总结

初学css,笔试题遇到了还是有点懵,这里小小总结一下,欢迎指正。

padding撑大盒子的情况

如果盒子已经有了宽度和高度,当我们给盒子指定了padding值,就会影响盒子的实际大小。

<body>
    <div class="father">
        我是父亲
        <!-- <div class="son"></div> -->
    </div>

</body>

<style>
    * {
        margin: 0;
        padding: 0;

    }

    .father {
        width: 300px;
        height: 300px;
        background-color: blue;
        padding-top: 100px;
    }
</style>

可见原本300*300变成了300*400,盒子被撑大了。

 

margin外边距合并问题

(1)父子嵌套的div,同时都指定了上边距,此时父元素会塌陷较大的外边距值。

<body>
    <div class="father">
        <div class="son">
        </div>
    </div>
</body>
<style>
    * {
        margin: 0;
        padding: 0;

    }

    .father {
        width: 300px;
        height: 300px;
        background-color: blue;
        margin-top: 50px;
    }

    .son {
        width: 200px;
        height: 100px;
        background-color: pink;
        margin-top: 100px;
    }
</style>

此时father的上外边距也变为100px。

 (2)上下相邻的div,同时指定了margin-top和margin-bottom,此时两div之间的上下外边距为margin-top和margin-bottom中的较大值。

<body>
    <div class="father">
    </div>
    <div class="neighbor">
    </div>
</body>
<style>
    * {
        margin: 0;
        padding: 0;

    }

    .father {
        width: 300px;
        height: 300px;
        background-color: blue;
        margin-bottom: 50px;
    }

    .neighbor {
        width: 200px;
        height: 100px;
        background-color: pink;
        margin-top: 100px;
    }
</style>

此时出现了外边距合并,外边距取两者最大值而不是加和。

 最后

来一个我前端笔试遇到的题目,大致代码如下,请问son距离顶部的距离是多少?

<body>
    <div class="father">
        <div class="son">
        </div>
    </div>
</body>
<style>
    * {
        margin: 0;
        padding: 0;

    }

    .father {
        width: 300px;
        height: 400px;
        background-color: blue;
        margin-top: 100px;
        padding-bottom: 100px;
    }

    .son {
        width: 200px;
        height: 200px;
        background-color: pink;
        margin-top: 200px;
        padding-top: 100px;
    }
</style>

分析:首先margin,父子嵌套关系,外边距会塌陷,所以上边距同一为200px;其次padding-bottom会撑大father-div为300*500,son-div的 padding-top为100px,同样撑大了son为200*300,最终答案为200px。


 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值