CSS给元素清除浮动影响的方法,--最全四种方法
代码实例:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>清除浮动方法一</title> <style> *{ margin: 0; padding: 0; } .father{ width: 500px; background-color: pink; } .son1, .son2{ height: 200px; width: 200px; float: left; } .son1{ background-color: blue; } .son2{ background-color: skyblue; } .box{ width: 600px; height: 200px; background-color: #000; } .clearfix{ clear: both; } </style> </head> <body> <div class="father"> <div class="son1"></div> <div class="son2"></div> <!-- 在浮动元素的末尾添加一个空的标签 --> <div class="clearfix"></div> </div> <div class="box"></div> </body> </html>
代码实例:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>清除浮动方法二</title> <style> *{ margin: 0; padding: 0; } .father{ width: 500px; background-color: pink; overflow: hidden; /* 给父元素添加 overflow:hidden/auto/scroll */ } .son1, .son2{ height: 200px; width: 200px; float: left; } .son1{ background-color: blue; } .son2{ background-color: skyblue; } .box{ width: 600px; height: 200px; background-color: #000; } </style> </head> <body> <div class="father"> <div class="son1"></div> <div class="son2"></div> </div> <div class="box"></div> </body> </html>
代码实例:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>清除浮动方法三</title> <style> *{ margin: 0; padding: 0; } .father{ width: 500px; background-color: pink; overflow: hidden; /* 给父元素添加 overflow:hidden/auto/scroll */ } .son1, .son2{ height: 200px; width: 200px; float: left; } .son1{ background-color: blue; } .son2{ background-color: skyblue; } .box{ width: 600px; height: 200px; background-color: #000; } /*给父元素添加类clearfix*/ .clearfix:after{ content: "."; /* 这里尽量写点内容,否则在IE6-7会出现间隙 */ dispaly: black; /* 转换为块级元素 */ height: 0; /* 高度为0 */ clear: both; /* 清除浮动 */ visibility: hidden; /* 隐藏盒子 */ } .clearfix{ *zoom: 1; /* 这是专门给IE6-7做的清除浮动 */ } </style> </head> <body> <div class="father clearfix"> <div class="son1"></div> <div class="son2"></div> </div> <div class="box"></div> </body> </html>
代码实例:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>清除浮动方法四</title> <style> *{ margin: 0; padding: 0; } .father{ width: 500px; background-color: pink; overflow: hidden; /* 给父元素添加 overflow:hidden/auto/scroll */ } .son1, .son2{ height: 200px; width: 200px; float: left; } .son1{ background-color: blue; } .son2{ background-color: skyblue; } .box{ width: 600px; height: 200px; background-color: #000; } /*给父元素添加类clearfix*/ .clearfix:before, .clearfix:after{ content:""; display:table; /*这句话可以触发BFC,BFC可以清除浮动*/ } .clearfix:after{ clear:both; } .clearfix{ *zoom:1; } </style> </head> <body> <div class="father clearfix"> <div class="son1"></div> <div class="son2"></div> </div> <div class="box"></div> </body> </html>