浮动布局注意点
-
先有标准流的父盒子排列,再才在父盒子里面添加子盒子,子盒子在父盒子里面浮动;
-
父盒子里面的子盒子一旦有一个浮动,所有子盒子都应该浮动
-
浮动的盒子只会覆盖后面的标准流,对前面的标准流没影响
最常见的是以下布局
注意事项
-
top(首行)和footer(末尾行)都是与浏览器同宽的,因此不需要写宽度;
-
开始要 清空内外边距,防止出现有些盒子自带边距,比如<ul><li>
-
注意合理设置子类,增加代码复用
具体代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> * { /* 不加这句用li就会出错!!! */ margin: 0; padding: 0; } .top { /* 和浏览器一样宽,不用指定宽度 */ height: 42px; margin: 12px auto; background-color: gray; } .banner { width: 580px; height: 109px; margin: 0 auto; margin-bottom: 12px; background-color: gray; } .four_small_box { width: 580px; height: 86px; margin: 0 auto; margin-bottom: 12px; background-color: skyblue; } li { list-style: none; float: left; width: 139px; height: 86px; margin-left: 0px; margin-right: 8px; background-color: yellow; } .four_small_box .last { margin-right: 0px; /* 除了和li冲突的,其余的不会覆盖 */ } .four_big_box { width: 580px; height: 181px; margin: 0 auto; margin-bottom: 12px; background-color: skyblue; } .four_big_box .big { height: 181px; background-color: pink; } .four_big_box .last { height: 181px; background-color: pink; margin-right: 0px; /* 除了和li冲突的,其余的不会覆盖 */ } .footer { height: 145px; margin: 0 auto; margin-bottom: 12px; background-color: gray; } </style> </head> <body> <div class="top"></div> <div class="banner"></div> <div class="four_small_box"> <!-- 这里div的子类就不要用div,可以用ul的li --> <ul> <li>1</li> <li>2</li> <li>3</li> <li class="last">4</li> </ul> </div> <div class="four_big_box"> <ul> <li class="big">1</li> <li class="big">2</li> <li class="big">3</li> <li class="last">4</li> </ul> </div> <div class="footer"></div> </body> </html>