css中如何清除浮動: clear:both和BFC
阿新 • • 發佈:2022-03-30
clear:both
這種方式有兩種做法
做法1
<!DOCTYPE html> <html> <head> <title>one</title> <style> .to-float { width: 100px; height: 100px; float: left; /* 不重要的部分 */ background-color: aqua; } .to-clear { width: 50px; height: 50px; clear: both; /* 不重要的部分 */ background-color:blue } .other{ width: 100px; height: 100px; /* 不重要的部分 */ background-color:red } </style> </head> <body> <div class="to-float"> </div> <div class="to-clear"> </div> <div class="other"> </div> <script> </script> </body> </html>
效果圖
做法2
做法1 添加了多餘的元素'.to-clear' , 為了儘量不使用多餘元素, 做法2使用偽元素元素
<!DOCTYPE html> <html> <head> <title>one</title> <style> .to-float { width: 100px; height: 100px; float: left; /* 不重要的部分 */ background-color: aqua; } .parent::after{ /* 這裡必須是塊級, 同時content必須有 */ display: block; content: ''; clear: both; } .other{ width: 100px; height: 100px; /* 不重要的部分 */ background-color:red } </style> </head> <body> <div class="parent"> <div class="to-float"> </div> </div> <div class="other"> </div> <script> </script> </body> </html>
效果圖
BFC
給 parent 新增 overflow:hidden 形成BFC 這樣 不會影響parent下面的元素
<!DOCTYPE html> <html> <head> <title>one</title> <style> .to-float { width: 100px; height: 100px; float: left; /* 不重要的部分 */ background-color: aqua; } .parent{ overflow: hidden; } .other{ width: 100px; height: 100px; /* 不重要的部分 */ background-color:red } </style> </head> <body> <div class="parent"> <div class="to-float"> </div> </div> <div class="other"> </div> <script> </script> </body> </html>