典型的三行二列居中高度自适应布局
|
源代码网整理以下 首先先按这里看实际运行效果,这个页面在mozilla、opera和IE浏览器中均可以实现居中和高度自适应。我们来分析代码: 源代码网整理以下 完整代码 源代码网整理以下 <html> 源代码网整理以下 <head> 源代码网整理以下 <style type="text/css"> 源代码网整理以下 body{ 源代码网整理以下 background:#999; 源代码网整理以下 text-align:center; 源代码网整理以下 color: #333; 源代码网整理以下 font-family:arial,verdana,sans-serif; 源代码网整理以下 } 源代码网整理以下 #header{ 源代码网整理以下 width:776px; 源代码网整理以下 margin-right: auto; 源代码网整理以下 padding: 0px; 源代码网整理以下 background: #EEE; 源代码网整理以下 height:60px; 源代码网整理以下 text-align:left; 源代码网整理以下 } #contain{ 源代码网整理以下 margin-right: auto; 源代码网整理以下 margin-left: auto; 源代码网整理以下 width: 776px; 源代码网整理以下 } #mainbg{ 源代码网整理以下 width:776px; 源代码网整理以下 padding: 0px; 源代码网整理以下 background: #60A179; 源代码网整理以下 float: left; 源代码网整理以下 } 源代码网整理以下 #right{ 源代码网整理以下 float: right; 源代码网整理以下 padding:0px; 源代码网整理以下 width: 574px; 源代码网整理以下 background: #ccd2de; 源代码网整理以下 text-align:left; 源代码网整理以下 } 源代码网整理以下 #left{ 源代码网整理以下 float: left; 源代码网整理以下 margin: 2px 2px 0px 0px; 源代码网整理以下 padding: 0px; 源代码网整理以下 background: #F2F3F7; 源代码网整理以下 width: 200px; 源代码网整理以下 text-align:left; 源代码网整理以下 } 源代码网整理以下 #footer{ 源代码网整理以下 clear:both; 源代码网整理以下 width:776px; 源代码网整理以下 margin-right: auto; 源代码网整理以下 margin-left: auto; 源代码网整理以下 padding: 0px; 源代码网整理以下 background: #EEE; 源代码网整理以下 height:60px;} 源代码网整理以下 .text{margin:0px;padding:20px;} 源代码网整理以下 </style> 源代码网整理以下 </head> 源代码网整理以下 <body> 源代码网整理以下 <div id="header">header</div> 源代码网整理以下 <div id="contain"> 源代码网整理以下 <div id="mainbg"> 源代码网整理以下 <div id="right"> 源代码网整理以下 <div 源代码网整理以下 </div> 源代码网整理以下 <div id="left"> 源代码网整理以下 <div class="text">left</div> 源代码网整理以下 </div> 源代码网整理以下 </div> 源代码网整理以下 </div> 源代码网整理以下 <div id="footer">footer</div> 源代码网整理以下 </body> 源代码网整理以下 </html> 代码分析
首先我们定义body和顶部第一行#header,这里面的关键是body中的text-align:center;和header中的margin-right: auto;margin-left: auto;,通过这两句使得header居中。注:其实定义text-align:center;就已经在IE中实现居中,但
在mozilla中无效,需要设置margin:auto;才可以实现mozilla中的居中。 源代码网整理以下 接下来定义中间的两列#right和#left。为了使中间两列也居中,我们在它们外面嵌套一个层#contain,并对contain设 源代码网整理以下 注意中间两列定义的顺序,我们首先定义#right,通过float: right;让它浮在#contain层的最右边。然后再定义#left,通过float: left;让它浮动在#right层的左面。这和我们以前表格从左到右定义的顺序正好相反(更正:先左后右、还是先右后左都可以实现,根据自己需要设计)。 源代码网整理以下 我们看到代码中在#contain和两列之间还嵌套了一个层#mainbg,这个层是做什么用的呢?这个层就是用来定义#contain的背景的。你肯定会问,为什么不直接在#contain中定义背景,而要多套一层呢?那是因为在#contain中直接定义的背景,在mozilla中将显示不出来,必须定义高度值才可以。如果定义了高度值,#right层就无法实现根据内容的自动伸缩。为了解决背景和高度问题,就必须增加这么一个#mainbg层。窍门在于#mainbh这个层定义float: left;,因为float使层自动有宽和高的属性。(暂且这么理解:) 源代码网整理以下 最后是定义底部的#footer层。这个定义的关键是:clear:both;,这一句话的作用是取消#footer层的浮动继承。否则的话,你会看到#footer紧贴着#header显示,而不是在#right的下面。 源代码网整理以下 主要的层定义完毕,这个布局就ok了。补充一点:你看到我还定义了一个.text{margin:0px;padding:20px;},这个class的作用是使内容的外围有20px的空白。为什么不直接在#right里定义margin或者padding呢,因为mozilla和IE对css盒模型的解释不一致,直接定义margin/padding会造成mozilla里布局变形。我一般采用内部再套一层的做法来解决。 源代码网供稿. |

