使寬度自適應使用百分比css
使一個div元素居中,要給其設置寬度,並設置margin:0 auto;便可。html
代碼:瀏覽器
<!doctype html> <html> <head> <meta charset="utf-8"> <title>一列居中佈局</title> <style type="text/css"> * { padding:0; margin:0;} .main { height:300px; width:800px; background-color:#900; margin:0 auto; } </style> </head> <body> <div class="main"></div> </body> </html>
效果:佈局
固定寬度的兩列布局:在上面的main div元素中添加兩個div,能夠使用百分比,也能夠使用像素固定其寬度。spa
代碼:
code
<!doctype html> <html> <head> <meta charset="utf-8"> <title>一列居中佈局</title> <style type="text/css"> * { padding:0; margin:0;} .main { width:800px; height:400px; background-color:#900; margin:0 auto; } .left { width:250px; height:inherit; background-color:#CCC; float:left; } .right { width:550px; height:inherit; background-color:#666; float:left; } </style> </head> <body> <div class="main"> <div class="left"></div> <div class="right"></div> </div> </body> </html>
效果:htm
實現方法:utf-8
設置三列的寬度都爲33.33%,並設置三列div元素左浮動。it
代碼:io
<!doctype html> <html> <head> <meta charset="utf-8"> <title>三列寬度相等佈局</title> <style type="text/css"> #div1 { width:33.33%; height:500px; float:left; background-color:#f00;} #div2 { width:33.33%; height:500px; float:left; background-color:#0f0;} #div3 { width:33.33%; height:500px; float:left; background-color:#00f;} </style> </head> <body> <div id="div1"></div> <div id="div2"></div> <div id="div3"></div> </body> </html>
效果:
實現方法:
左右div塊元素設置固定寬度,中間div不設置;
左右div設置position爲absolute,而且分別設置位於瀏覽器左上角和右上角;
設置中間div的左右margin值分別爲左右div元素的寬度。
代碼:
<!doctype html> <html> <head> <meta charset="utf-8"> <title>三列布局——中間自適應寬度</title> <style type="text/css"> * { padding:0; margin:0; } #div1 { width:200px; height:500px; position:absolute; left:0; top:0; background-color:#f00;} #div2 { height:500px; margin:0 300px 0 200px; background-color:#0f0;} #div3 { width:300px; height:500px; position:absolute; right:0; top:0; background-color:#00f;} </style> </head> <body> <div id="div1"></div> <div id="div2"></div> <div id="div3"></div> </body> </html>
效果:
實現:
利用基礎的一列、兩列、三列布局知識進行組合,利用浮動和定位對網頁進行佈局。
代碼:
<!doctype html> <html> <head> <meta charset="utf-8"> <title>混合佈局</title> <style type="text/css"> * { padding:0; margin:0; } .top { height:50px; background-color:#f00;} .top-center { width:800px; height:inherit; margin:0 auto; background-color:#009;} .main { width:800px; height:400px; margin:0 auto; background-color:#0f0;} .main-left { width:200px; height:inherit; float:left; background-color:#FF0; } .main-right {width:600px; height:inherit; float:right; background-color:#0FF; } .sub-left { width:400px; height:inherit; float:left; background-color:#C60;} .sub-right { width:200px; height:inherit; float:left; background-color:#F0C;} .foot { width:800px; height:50px; margin:0 auto; background-color:#00f;} </style> </head> <body> <div class="top"> <div class="top-center"></div> </div> <div class="main"> <div class="main-left"></div> <div class="main-right"> <div class="sub-left"></div> <div class="sub-right"></div> </div> </div> <div class="foot"></div> </body> </html>
效果: