步骤二:
现在我们开始用一些基本的 CSS 来给页面添加样式。把以下代码放入在我们的 html 页面顶部被引入的 style.css。
html, body { margin:0; padding:0; height:100%; }
body { background:url('page_bg.jpg') 50% 50% no-repeat #FC3; font-family:Georgia, Times, serifs; }
#floater { position:relative; float:left; height:50%; margin-bottom:-200px; width:1px; }
#centered { position:relative; clear:left; height:400px; width:80%; max-width:800px; min-width:400px; margin:0 auto; background:#fff; border:4px solid #666; }
#bottom { position:absolute; bottom:0; right:0; }
#nav { position:absolute; left:0; top:0; bottom:0; right:70%; padding:20px; margin:10px; }
#content { position:absolute; left:30%; right:0; top:0; bottom:0; overflow:auto; height:340px; padding:20px; margin:10px; }
在我们能够把 content 垂直居中之前, body 和 html 应该被拉伸到 100% 的高度。由于 height在 padding 和 margin 之内,所以我们要把它们设成 0 以防止因为很小的 margin 出现滚动条。
floater 的 margin-bottom 是 content 高度(400px)的一半,-200px。
现在可以看到一下效果:

#centred 的宽度为 80%。这可以市网页随着显示器的大小而变化。一般称作流体布局。设置 min-width 和max-width 以避免网页过大或者过小。 但是 IE 不支持 min/max-width。显然可以用固定宽度来代替。
因为 #centred 是相对定位的,在它里面我们可以用绝对定位来定位元素。设置 #content 的 overflow:auto;以避免滚动条的出现。IE 不怎么喜欢 overflow:auto; 除非我们指定高度(不是 top 和 bottom 的定位,也不是 %)因此我们给它指定高度。
出处:前端观察
责任编辑:bluehearts
上一页 CSS实现垂直居中的5种方法 [3] 下一页 CSS实现垂直居中的5种方法 [5]
◎进入论坛网页制作、WEB标准化版块参加讨论,我还想发表评论。
|