布局时可能遇到浮动布局会导致页面布局错乱的问题,这里收集一些解决的办法:
No.1使用after伪类和zoom清除(推荐)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
.parent {
background-color: #673AB7;
/****解决问题部分****/
zoom: 1;
}
/****解决问题部分****/
.parent:after {
display:block;
clear:both;
content:"";
visibility:hidden;
height:0;
}
.child1 {
width: 50%;
height: 100px;
background-color: #f00;
float: left;
}
.child2 {
width: 50%;
height: 90px;
background-color: #ff0;
float: left;
}
</style>
</head>
<body>
<div class="parent">
<div class="child1"></div>
<div class="child2"></div>
</div>
<script type="text/javascript"></script>
</body>
</html>
No.2父级元素定义overflow: auto
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
.parent {
background-color: #673AB7;
/****解决问题部分****/
overflow: auto;
}
.child1 {
width: 50%;
height: 100px;
background-color: #f00;
float: left;
}
.child2 {
width: 50%;
height: 90px;
background-color: #ff0;
float: left;
}
</style>
</head>
<body>
<div class="parent">
<div class="child1"></div>
<div class="child2"></div>
</div>
<script type="text/javascript"></script>
</body>
</html>
No.3添加额外标签clear:both
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
.parent {
background-color: #673AB7;
}
.child1 {
width: 50%;
height: 100px;
background-color: #f00;
float: left;
}
.child2 {
width: 50%;
height: 90px;
background-color: #ff0;
float: left;
}
/****解决问题部分****/
.clear {clear: both;}
</style>
</head>
<body>
<div class="parent">
<div class="child1"></div>
<div class="child2"></div>
/****解决问题部分****/
<div class="clear"></div>
</div>
<script type="text/javascript"></script>
</body>
</html>
No.4不使用浮动布局,使用display:table布局
缺点:子元素会以最大高度同样撑开
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
.parent {
background-color: #673AB7;
display: table;
width: 100%;
}
.child1 {
display: table-cell;
width: 40%;
height: 100px;
background-color: #f00;
}
.child2 {
display: table-cell;
width: 60%;
height: 90px;
background-color: #ff0;
}
</style>
</head>
<body>
<div class="parent">
<div class="child1"></div>
<div class="child2"></div>
</div>
<script type="text/javascript"></script>
</body>
</html>