本文轉載自:http://www.topcss.org/?p=94,有修改。
負數給人總是一種消極、否定、拒絕之感,不過有時利用負margin可以達到奇妙的效果,今天就表一表負值在頁面佈局中的應用。這裏說的負值主要指的是負margin。
關於負margin的原理建議大家看看這篇文章:http://www.cnblogs.com/2050/archive/2012/08/13/2636467.html#2457812
本文不講原理,主要展示幾個應用。
一、左右列固定,中間列自適應佈局
此例適用於左右欄寬度固定,中間欄寬度自適應的佈局。由於網頁的主體部分一般在中間,很多網頁都需要中間列優先加載,而這種佈局剛好滿足此需求。
HTML:
<div class="main"> <div class="main_body">Main</div> </div> <div class="left">Left</div> <div class="right">Right</div>
CSS:
body{ margin:0; padding:0; min-width:600px; } .main{ float:left; width:100%; } .main_body{ margin:0 210px; background:#888; height:200px; } .left,.right{ float:left; width:200px; height:200px; background:#F60; } .left{ margin-left:-100%; } .right{ margin-left:-200px; }
效果:
二、去除列表右邊框
項目中經常會使用浮動列表展示信息,爲了美觀通常爲每個列表之間設置一定的間距(margin-right),當父元素的寬度固定式,每一行的最右端的li元素的右邊距就多餘了,去除的方法通常是爲最右端的li添加class,設置margin-right:0; 這種方法需要動態判斷爲哪些li元素添加class,麻煩!!!利用負margin就可以實現下面這種效果:
HTML:
<div id="test"> <ul> <li>子元素1</li> <li>子元素2</li> <li>子元素3</li> <li>子元素4</li> <li>子元素5</li> <li>子元素6</li> </ul> </div>
CSS:
body,ul,li{ padding:0; margin:0;} ul,li{ list-style:none;} #test{ width:320px; height:210px; background:#CCC; } #test ul{ margin-right:-10px; zoom:1; } #test ul li{ width:100px; height:100px; background:#F60; margin-right:10px; margin-bottom:10px; float:left; }
效果:
三、負邊距+定位:水平垂直居中
使用絕對定位將div定位到body的中心,然後使用負margin(content寬高的一半),將div的中心拉回到body的中心,已到達水平垂直居中的效果。
HTML:
<div id="test"></div>
CSS:
body{margin:0;padding:0;} #test{ width:200px; height:200px; background:#F60; position:absolute; left:50%; top:50%; margin-left:-100px; margin-top:-100px; }
效果:
四、去除列表最後一個li元素的border-bottom
列表中我們經常會添加border-bottom值,最後一個li的border-bottom往往會與外邊框重合,視覺上不雅觀,往往要移除。
HTML:
<ul id="test"> <li>Test</li> <li>Test</li> <li>Test</li> <li>Test</li> <li>Test</li> </ul>
CSS:
body,ul,li{margin:0;padding:0;} ul,li{list-style:none;} #test{ margin:20px; width:390px; background:#F4F8FC; border-radius:3px; border:2px solid #D7E2EC; } #test li{ height:25px; line-height:25px; padding:5px; border-bottom:1px dotted #D5D5D5; margin-bottom:-1px; }
效果:
五、多列等高
此例關鍵是給每個框設置大的底部內邊距,然後用數值相似的負外邊距消除這個高度。這會導致每一列溢出容器元素,如果把外包容器的overflow屬性設爲hidden,列就在最高點被裁切。
HTML:
<div id="wrap"> <div id="left"> <p style="height:50px">style="height:50px"</p> </div> <div id="center"> <p style="height:100px">style="height:100px"</p> </div> <div id="right"> <p style="height:200px">style="height:200px"</p> </div> </div>
CSS:
body,p{ margin:0; padding:0; } #wrap{ overflow:hidden; width:580px; margin:0 auto; } #left,#center,#right{ margin-bottom:-200px; padding-bottom:200px; } #left { float:left; width:140px; background:#777; } #center { float:left; width:300px; background:#888; } #right { float:right; width:140px; background:#999; } p {color:#FFF;text-align:center}
效果:
原文地址:http://www.cnblogs.com/jscode/archive/2012/08/28/2660078.html