1、两栏布局——
绝对定位法:若左栏高度超过右栏,则包裹层container无法撑开
<!doctype html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>左栏固定宽度,右栏自适应之绝对定位法</title> <style type="text/css"> body{ margin: 0; } #nav{ top: 0; left: 0; 230px; height: 600px; background: #ccc; position: absolute; } #main{ height: 600px; margin-left: 230px; background: #0099ff; } </style> </head> <body> <div id="container"> <div id="nav"> 左栏 </div> <div id="main"> 右栏 </div> </div> </body> </html>
float浮动方法:外包裹层不会因为左栏height > 右栏height而不能 撑开外包裹层。此方法不会影响底部布局
<!doctype html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>左栏固定宽度,右栏自适应之负margin法</title> <style type="text/css"> body{ margin: 0; } #container{ /* margin-left: 230px; 也可以配合#nav的注释部分这样写 */ } #nav{ float: left;/*采用浮动float方法*/ 230px; height: 600px; background: #ccc; /* margin-left: -230px;*/ } #main{ height: 600px; background: #0099ff; margin-left: 230px;/*没有这步右栏则在左栏下,和左栏位置相同*/ } </style> </head> <body> <div id="container"> <div id="nav"> 左栏 </div> <div id="main"> 右栏 </div> </div> </body> </html>
2、元素垂直居中
<!doctype html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> body{ margin: 0; } #container{ 200px;height: 200px; border: 1px solid black; } </style> </head> <body> <div id="container"></div> </body> <script> window.onload=function(){ var winH=document.documentElement.clientHeight;/有兼容问题/ var elemH=document.getElementById('container').offsetHeight; document.getElementById('container').style.marginTop=(winH-elemH)/2+'px' } </script> </html>