当一个div1嵌套有一个div2,在未进行任何操作的时候你会发现,div2设计高度或宽度无法将父级div1盒子撑开。
如图所示:
具体代码实现:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Title</title>
<style>
.box{
width: 300px;
background-color: red;
color: white;
}
.box1{
width: 50px;
height: 100px;
background-color: green;
float: left;
color: white;
}
.box2{
width: 50px;
height: 100px;
background-color: blue;
float: right;
color: white;
}
</style>
</head>
<body>
<div class="box">
box
<div class="box1">box1</div>
<div class="box2">box2</div>
</div>
</body>
</html>
面对这种情况,我们应该怎么来解决这个问题(怎么把父级div盒子撑起呢?)?在这里我有两种方法解决(推荐大家使用第二种方法),原因是第一种方法在原有的HTML添加一个div盒子。
方法一:可以通过添加一个空div,设置clear:both,便可以让div1获取到高度了
代码实现:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Title</title>
<style>
.box{
width: 300px;
background-color: red;
color: white;
}
.box1{
width: 50px;
height: 100px;
background-color: green;
float: left;
color: white;
}
.box2{
width: 50px;
height: 100px;
background-color: blue;
float: right;
color: white;
}
</style>
</head>
<body>
<div class="box">
box
<div class="box1">box1</div>
<div class="box2">box2</div>
//解决方法
<div style="clear: both"></div>
</div>
</body>
</html>
运行结果:
方法二:通过给父亲元素添加“overflow:hidden”,便可以让div1获取到高度了
代码实现:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Title</title>
<style>
.box{
width: 300px;
background-color: red;
color: white;
//解决方法
overflow: hidden;
}
.box1{
width: 50px;
height: 100px;
background-color: green;
float: left;
}
.box2{
width: 50px;
height: 100px;
background-color: blue;
float: right;
}
</style>
</head>
<body>
<div class="box">
box
<div class="box1">box1</div>
<div class="box2">box2</div>
</div>
</body>
</html>