Float浮动:浮动元素脱离文档流,原先位置不保留,飘在文档流上方
一、兄弟元素之间的浮动
<body>
<div class="one"></div>
<div class="two"></div>
</body>
1)、未浮动时
<style>
.one {
width: 100px;
height: 100px;
background-color: plum;
padding-left: 50px;
}
.two {
width: 100px;
height: 200px;
background-color: palevioletred;
}
</style>
如图显示:
2)、one向左浮动后:如下图,two所在的元素跑到了one的下方
.one {
width: 100px;
height: 100px;
background-color: plum;
float: left;
}
3)、清除one的浮动对two的影响
给one的兄弟元素two的样式设置clear:both
.two {
clear: both;
width: 100px;
height: 200px;
background-color: palevioletred;
}
二、父子元素之间子元素浮动
<body>
<div class="parent">
<div class="child">child</div>
</div>
</body>
1)、未浮动时
<style>
.parent {
width: 200px;
border: 1px solid blue;
}
.child {
width: 100px;
height: 100px;
background-color: palevioletred;
}
</style>
2)、child向左浮动后
<style>
.parent {
width: 200px;
border: 1px solid blue;
}
.child {
width: 100px;
height: 100px;
background-color: palevioletred;
float: left;
}
</style>
child向左浮动后,因为父元素没有设置高度,所以父元素会发生高度塌陷,如下图
3)、清除子元素浮动对父级元素产生的影响
给父元素的样式设置overflow:hidden;即可
<style>
.parent {
width: 200px;
border: 1px solid blue;
overflow: hidden;
}
.child {
width: 100px;
height: 100px;
background-color: palevioletred;
float: left;
}
</style>