1.通过父元素overflow:hidden,缺点:超出部分隐藏,不推荐使用
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <title></title> <style type="text/css"> *{padding:0;margin:0;} .box{margin:50px;border:1px solid #ddd;overflow:hidden;} .left{float:left;} .right{float:right;} </style> </head> <body> <div class="box"> <div class="left">54</div> <div class="right">33</div> </div> </body> </html>
效果:
方式2:添加空标签并设置clear:both,缺点是额外添加空标签,不推荐使用
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <title></title> <style type="text/css"> *{padding:0;margin:0;} .box{margin:50px;border:1px solid #ddd;} .left{float:left;} .right{float:right;} .slot{clear:both;} </style> </head> <body> <div class="box"> <div class="left">54</div> <div class="right">33</div> <div class="slot"></div> </div> </body> </html>
方式3:通过伪类添加,既不会隐藏超出部分,又不多空标签,推荐使用
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <title></title> <style type="text/css"> *{padding:0;margin:0;} .box{margin:50px;border:1px solid #ddd;} .box:after{content:'';display:block;clear:both;} .left{float:left;} .right{float:right;} </style> </head> <body> <div class="box"> <div class="left">54</div> <div class="right">33</div> </div> </body> </html>