初学html写页面时,总是遇到父元素的第一个子元素加marign-top
会把父元素一起撑开
问题如下:
这是一段简单的代码:
<style>
#box1 {
width: 100%;
height: 100%;
background-color: powderblue;
}
.box1-child {
width: 1000px;
height: 200px;
background-color: pink;
margin: 0 auto;
}
#box2 {
width: 100%;
height: 100%;
background-color: blueviolet;
}
.box2-child {
width: 1000px;
height: 300px;
background-color: tomato;
margin: 0 auto;
}
</style>
</head>
<body>
<div id="box1">
<div class="box1-child">我是box1-child</div>
</div>
<div id="box2">
<div class="box2-child">我是box2-child</div>
</div>
</body>
</html>
效果如下:
接着 我的需求是:想要box2-child 与box2有50px 的边距
我给第二个.box2-child加上一个marign-top:50px;
代码如下:
.box2-child {
width: 1000px;
height: 300px;
background-color: tomato;
margin: 0 auto;
margin-top: 50px;
}
效果如下
正常来说,我们只想让子元素有外边距的效果,而不是让父元素有外边距产生外边距
当我们给子元素加上marign-top时 却又发现产生外边距效果的是 父元素
解决方案
1.最简单的方法 就是子元素加上 padding-top
.box2-child {
width: 1000px;
height: 300px;
background-color: tomato;
margin: 0 auto;
padding-top: 50px;
}
2.给父元素加边框线
#box2 {
width: 100%;
height: 100%;
background-color: blueviolet;
border: 1px solid bisque;
}
.box2-child {
width: 1000px;
height: 300px;
background-color: tomato;
margin: 0 auto;
margin-top: 50px;
}
3.给父元素加上 overflow:hidden(溢出隐藏)
#box2 {
width: 100%;
height: 100%;
background-color: blueviolet;
overflow: hidden;
}
.box2-child {
width: 1000px;
height: 300px;
background-color: tomato;
margin: 0 auto;
margin-top: 50px;
}
4.给父元素加浮动或定位
#box2 {
width: 100%;
height: 100%;
background-color: blueviolet;
position: absolute;
}