css 子元素使用float,而父元素没有高度,不能自适应的问题

先来看一下demo
html:

css:

.container {
    background:green;
    padding: 10px;
}
.float_left{
    width:300px;
    height:300px;
    background-color: red;
    float: left;
}
.float_right{
    width:300px;
    height:400px;
    background-color: yellow;
    float: right;
}

效果:


image.png

当对盒子内的子元素应用float后,导致对象父元素内有高度,不能被撑开自使用高度。
这是因为对子元素使用float之后,脱离了正常流,使得父元素没有高度导致的。

解决办法:

1.为父元素设置高度

适用于知道父级高度的情况
缺点是父级元素不能自适应

.container {
    background:green;
    padding: 10px;
    height:400px;
}
.float_left{
    width:300px;
    height:300px;
    background-color: red;
    float: left;
}
.float_right{
    width:300px;
    height:400px;
    background-color: yellow;
    float: right;
}

效果:


image.png

2.使用clear:both清除浮动

这里注意是在父元素的结束标签之前添加一个清除浮动的元素,不是在父级元素上添加清除浮动
缺点是引入了没有语义的元素。
html:

css:

.container {
    background:green;
    padding: 10px;
}
.float_left{
    width:300px;
    height:300px;
    background-color: red;
    float: left;
}
.float_right{
    width:300px;
    height:400px;
    background-color: yellow;
    float: right;
}
.clear{
    clear: both;
}

效果:


image.png

3.使用overflow:hidden

这个方法可以使父元素自适应

.container {
    background:green;
    padding: 10px;
    overflow: hidden;
}
.float_left{
    width:300px;
    height:300px;
    background-color: red;
    float: left;
}
.float_right{
    width:300px;
    height:400px;
    background-color: yellow;
    float: right;
}

效果:


image.png

4.使用伪类:after方法

注意:这里的:after是作用于父元素的
原理:利用:after在父元素内部插入元素块,达到清除浮动的效果。实现原理类似于clear:both方法。

.container {
    background:green;
    padding: 10px;
    overflow: hidden;
}
.container:after{
    clear: both;
    content:" ";
    display: block;
    width:0;
    height: 0;
    visibility: hidden;
}

利用伪类,就不需要在HTML中加入标签。
display:block 用于显示伪元素
clear:both 用于清除浮动
content:"" 为伪元素加入空内容,以便伪元素中不会有内容显示在页面中
height:0 高度设置为0,使伪元素不影响布局
visibility:hidden 作用是允许浏览器渲染它,但是不显示出来。

效果:


image.png

你可能感兴趣的:(css 子元素使用float,而父元素没有高度,不能自适应的问题)