记不清自己有多少次写浮动的 li 时最后一个 li 标签被挤掉下一行。导致的原因很简单,就是父盒子给的宽度太小了,今天偷来空总结总结处理办法。
情景模拟:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <style> * { margin: 0; padding: 0; } .box1 { margin: 100px; width: 700px; height: 100px; background-color: #c8d4db; } .box1 ul { list-style: none; } .box1 li { float: left; width: 100px; height: 100px; margin-right: 1px; background-color: #48484c; } .box1 li:hover { background-color: orange; } </style> </head> <body> <div class="box1"> <ul> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> </ul> </div> </body> </html>
父盒子是700px的宽,每一个li是100px的宽+1px的margin-right,由于700px<(100+1)*7,所以最后一个 li 被挤了下来。
解决办法1:
直接给li的父亲ul加具体宽,而且ul的宽要大于所有li宽度(包括margin,padding)之和,width : 707px;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title> 不管父盒子是不是浮动的:【不想超过父盒子边,可以给父盒子加overflow:hidden】,扩大ul的宽度,这样最后一个li 就不会被挤下去,而且每个li直接又留出了空隙。 父盒子的宽度还是700px,每一个li都是100px宽。【加overflow:hidden后,最后一个li的宽度明显没有100px,整整减小了6px】 </title> <style> * { margin: 0; padding: 0; } .box1 { margin: 100px; width: 700px; height: 100px; /*overflow: hidden;*/ background-color: #a83c3a; } .box1 ul { width: 707px; list-style: none; } .box1 li { float: left; width: 100px; height: 100px; margin-right: 1px; background-color: #48484c; } .box1 li:hover { background-color: #c43c35; } </style> </head> <body> <div class="box1"> <ul> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> </ul> </div> </body> </html>
解决办法2:
给li的父亲ul加 width:500%;_width:400%;
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title> 不管父盒子是不是浮动的:将ul的宽度设置为500%,最后一个li 不会被挤下去,而且每个li都留出了空隙。 父盒子的宽度还是700px,每一个li都是100px宽。【加overflow:hidden后,最后一个li的宽度明显没有100px,整整减小了6px】 </title> <style> * { margin: 0; padding: 0; } .box1 { margin: 100px; width: 700px; height: 100px; /*overflow: hidden;*/ background-color: #a83c3a; } .box1 ul { width: 500%; _width: 400%; list-style: none; } .box1 li { float: left; width: 100px; height: 100px; margin-right: 1px; background-color: #48484c; } .box1 li:hover { background-color: #c43c35; } </style> </head> <body> <div class="box1"> <ul> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> </ul> </div> </body> </html>
测试浮动情形:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title> 不管父盒子是不是浮动的:可以看到不管是直接使用ul width:707px还是width:500%都是可行的 与父盒子浮动不浮动无关。 </title> <style> * { margin: 0; padding: 0; } .box1 { margin: 100px; width: 700px; height: 100px; } .box2 { float: left; width: 100px; height: 100px; background-color: orange; } .box3 { /* 首先父盒子要有宽子盒子才能用500% */ width: 600px; float: right; } .box3 ul { width: 607px; list-style: none; } .box3 li { float: left; width: 100px; height: 100px; margin-right: 1px; background-color: #48484c; } li:hover { background-color: #c43c35; } </style> </head> <body> <div class="box1"> <div class="box2"> </div> <div class="box3"> <ul> <li></li> <li></li> <li></li> <li></li> <li></li> <li></li> </ul> </div> </div> </body> </html>