Css+div 垂直居中對齊方式集錦
來源:程序員人生 發布時間:2013-12-04 15:15:30 閱讀次數:3118次
1. 重置瀏覽器的默認設置
首先將以下代碼加到你的全局css文件中:
/*1.Reset browser defaults then reset the browser font size*/
body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,form,fieldset,input,textarea,p,
blockquote,th,td {margin:0; padding:0; }
table { border-collapse:collapse; border-spacing:0; }
fieldset,img { border:0; }
address,caption,cite,code,dfn,em,strong,th,var { font-style:normal; font-weight:normal; }
ol,ul { list-style:none; }
caption,th { text-align:left; }
h1,h2,h3,h4,h5,h6 { font-size:100%; font-weight:normal; }
q:before,q:after { content:“; }
abbr,acronym { border:0; }
html {font-size: 62.5%;}
然后,我們把字體大小font-size設為10px如:
html {font-size: 62.5%;}
這樣我們就比較容易的通過em單位來設置頁面字體的大小了,e.g
p {font-size: 1.2em;}/* the same as 12px*/
h1 {font-size: 2em;}/* the same as 20px */
2.水平居中(僅限固定寬度)
這個我想大家都會知道的,如:
div#container {margin: 0 auto;}
3.充分利用position中的absolute和relatively
4.居中,還是居中(縱橫通殺)
div.popup { height:400px; width:500px; position: absolute; top: 50%; left: 50%;}
div.popup { margin-top: -200px; margin-left: -250px;}
Memo:
·必須指定width和height的固定值;
·position值為absolute;
·分別指定top與left為50%;
·設置margin-top和margin-left分別height和width的負值的一半,也可以簡寫為:margin:-200px 0 0 -250px;
5.CSS也能復用
建立你的global css rules,充分在任何可以用到的頁面用它吧,e.g
.left {float: left;}
.right {float: right;}
img .left { border:2px solid #aaaaaa; margin: 0 10px 0 0;}
img .right { border:2px solid #aaaaaa; margin: 0 0 0 10px; padding: 1px;}
6.IE6的margin bug
當你設置div元素的float屬性并指定了margin-left屬性,在IE6或以下版本瀏覽的時候你可以會太跌眼鏡,IE6怎么給你愉愉地加了margin的值呢?
解決方法:把div設為內聯的就行了 e.g
div {float:left;margin:40px;display:inline;}
7.簡單的導航菜單
xhtml:
<div id="navbar">
<ul>
<li><a href=http://www.jyygyx.com>LieHuo Design</a></li>
<li><a href=http://www.google.com>Google</a></li>
<li><a href="http://bbs.liehuo.net/">LieHuo BBS</a></li>
</ul>
</div>
CSS:
#navbar ul li {display:inline;margin:0 10px 0 0;}
#navbar ul li a {color: #333;display:block;float:left;padding:5px;}
#navbar ul li a:hover {background:#eee;color:black;}
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈