父元素没有给固定高度,子元素设有固定的高度,但是父云素也没有被子元素的高度撑开。子元素浮动了,而浮动属性会使元素脱离文档流,即子元素设置float属性后,当前的html文档会当作元素不存在一样,所以可以看作父元素内根本没有内容,高度当然也就撑不开。
解决办法:
1.设置父元素float属性;这样,父元素也是脱离当前文档流,子元素和父元素一起脱离,并且子元素仍在父元素内,父元素内容不空了,所以高度会适应子元素高度。
2.不要浮动,子元素使用display:inline-block;
3.在最后一个设置浮动的子元素后加一个空div,清除浮动;
4.父元素设置overflow:hidden属性;
5 .使用after伪对象清除浮动 ;
推荐后面3种方法。
针对方案4还可以这样:
如果在父元素内要左右排列且不让父元素坍塌,可以这样改,将左边的子类设置为float,右边的子类设置为overflow:hidden属性。如下代码所示:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<style>
.left{
float:left;
width:200px;
margin-right: 20px;
background-color: #aaaaaa;
}
.parent{
overflow: hidden;
background-color: antiquewhite;
}
@media screen and (max-width: 500px) {
.left{
float: none;
width: auto;
margin-right: 0;
margin-bottom: 20px;
background-color: #aaaaaa;
}
}
</style>
</head>
<body>
<div class="parent">
<div class="left"><p>DEMO</p></div>
<div class="right"><p>DEMO</p></div>
</div>
<p>DEMODEMODEMODEMO</p>
</body>
</html>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 顶
- 0
- 踩
父元素没有给固定高度,子元素设有固定的高度,但是父云素也没有被子元素的高度撑开。子元素浮动了,而浮动属性会使元素脱离文档流,即子元素设置float属性后,当前的html文档会当作元素不存在一样,所以可以看作父元素内根本没有内容,高度当然也就撑不开。
解决办法:
1.设置父元素float属性;这样,父元素也是脱离当前文档流,子元素和父元素一起脱离,并且子元素仍在父元素内,父元素内容不空了,所以高度会适应子元素高度。
2.不要浮动,子元素使用display:inline-block;
3.在最后一个设置浮动的子元素后加一个空div,清除浮动;
4.父元素设置overflow:hidden属性;
5 .使用after伪对象清除浮动 ;
推荐后面3种方法。
针对方案4还可以这样:
如果在父元素内要左右排列且不让父元素坍塌,可以这样改,将左边的子类设置为float,右边的子类设置为overflow:hidden属性。如下代码所示:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<style>
.left{
float:left;
width:200px;
margin-right: 20px;
background-color: #aaaaaa;
}
.parent{
overflow: hidden;
background-color: antiquewhite;
}
@media screen and (max-width: 500px) {
.left{
float: none;
width: auto;
margin-right: 0;
margin-bottom: 20px;
background-color: #aaaaaa;
}
}
</style>
</head>
<body>
<div class="parent">
<div class="left"><p>DEMO</p></div>
<div class="right"><p>DEMO</p></div>
</div>
<p>DEMODEMODEMODEMO</p>
</body>
</html>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34