[常用布局]左栏固定宽度,右栏自适应的两种纯CSS方法
前端开发
其一,左栏固定宽度,右栏自适应之绝对定位法:
<!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; width: 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>
看起来很美好,但是。。
由于左栏使用绝对定位,脱离了文档流,因此有一个缺陷,即当左栏高度大于右栏时,无法将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;
width: 230px;
height: 600px;
background: #ccc;
position: absolute;
}
#main{
height: 400px;
margin-left: 230px;
background: #0099ff;
}
#footer{
text-align: center;
background: #009000;
}
</style>
</head>
<body>
<div id="container">
<div id="nav">
左栏
</div>
<div id="main">
右栏
</div>
</div>
<div id="footer">
底栏
</div>
</body>
</html>
我们再来看看第二种方法,左栏固定宽度,右栏自适应之负margin法:
<!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;
_zoom: 1;
/*兼容IE6下左栏消失问题*/
}
#nav{
float: left;
width: 230px;
height: 600px;
background: #ccc;
margin-left: -230px;
position: relative;
/*兼容IE6下左栏消失问题,IE6真不让人省心啊>_<*/
}
#main{
height: 600px;
background: #0099ff;
}
</style>
</head>
<body>
<div id="container">
<div id="nav">
左栏
</div>
<div id="main">
右栏
</div>
</div>
</body>
</html>
这样无论两栏的高度如何变化都不会有问题了:
<!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;
_zoom: 1;
/*兼容IE6下左栏消失问题*/
}
#nav{
float: left;
width: 230px;
height: 600px;
background: #ccc;
margin-left: -230px;
position: relative;
/*兼容IE6下左栏消失问题,IE6真不让人省心啊>_<*/
}
#main{
height: 400px;
background: #0099ff;
}
#footer{
clear: both;
text-align: center;
background: #009000;
}
</style>
</head>
<body>
<div id="container">
<div id="nav">
左栏
</div>
<div id="main">
右栏
</div>
</div>
<div id="footer">
底栏
</div>
</body>
</html>
如需转载请注明出处:杰拉斯的博客
新的项目,一般都开始用bootstrap做布局了。
@bsspirit
只可惜它不支持IE6。
博主已经完全成为了一个前端工程师了!
思想是相通的→_→
今天换主机了!经常报Bad Request (Invalid Hostname);唉,不知道哪的问题……
@王雪松的站点
刚试了一下,我这边可以上= =
好好用,好厉害!!
我就是不太明白为啥兼容IE6左栏消失所提供的设置,如container标签里的margin-left: 230px;_zoom: 1;和nav标签里的margin-left: -230px;position: relative;为何这么设置?
兼容左栏消失问题是这两个属性:
#container 的 _zoom: 1; 和 #nav 的 position: relative
_zoom: 1 是用来触发 IE 的hasLayout,position: relative 不太记得了。