初学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。