问题一:如何解决父元素的第一个子元素的margin-top越界问题?
<!DOCTYPE html>
<html>
<head>
<title> ... </title>
<meta charset="utf-8"/>
<meta name="HSW" content="">
<meta name="Keywords" content="">
<style>
.parent1{
width:300px;
height:100px;
background-color:#8ff;
}
.parent2 {
width:300px;
height:100px;
background-color:#f8f;
}
.child2 {
width:200px;
height:50px;
background-color:#ff8;
/*margin-top:10px;*/
}
</style>
</head>
<body>
<div class="parent1">parend1</div>
<div class="parent2">
<div class="child2">child2</div>
parend2
</div>
</body>
</html>
此时的样子:
给子元素child2加 margin-top:10px;发现父元素parend2也一起下来,那么怎么解决呢?
- 为父元素加border-top: 1px;——有副作用
- 为父元素指定padding-top: 1px;——有副作用
- 为父元素指定overflow:hidden;——有副作用
- 为父元素添加前置内容生成——推荐使用
.parent:before {
content: ' ';
display: table;
}
问题二:如何解决所有子元素浮动后父元素高度变为0,且影响后续元素?
<!DOCTYPE html>
<html>
<head>
<title> ... </title>
<meta charset="utf-8"/>
<meta name="HSW" content="">
<meta name="Keywords" content="">
<style>
.parent {
width:400px;
background-color:#8ff;
}
.child1 {
width:200px;
height:50px;
background-color:#ff8;
margin-top:10px;
/*float:left;*/
}
.child2 {
width:200px;
height:50px;
background-color:#f8f;
margin-top:10px;
/*float:left;*/
}
</style>
</head>
<body>
<div class="parent">
<div class="child1">child1</div>
<div class="child2">child2</div>
</div>
<hr>
</body>
</html>
此时的样子:
给所有子元素添加float:left后,父元素的高度变为0了,且影响后续元素,怎么办?
1)为父元素指定overflow:hidden;——有副作用
2)为父元素指定高度:height: xxx;——有局限性
3)为父元素添加后置内容生成——推荐使用
.parent:after {
content: ' ';
display: table;
clear: both;
}