代碼:ide
<div style="margin-right:-100px; width:200px;">1</div>佈局
代碼:ui
<div style="margin-right:-100px; height:100px; width:200px; float:left;"></div>
<div style="width:150px; float:left; height:100px;">spa
<div style=" height:100px; width:200px; float:left;"></div>
<div style="width:150px; float:left; height:100px;">3d
此例適用於左右欄寬度固定,中間欄寬度自適應的佈局。因爲網頁的主體部分通常在中間,不少網頁都須要中間列優先加載,而這種佈局恰好知足此需求。code
HTML:blog
<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; }
效果:get
項目中常常會使用浮動列表展現信息,爲了美觀一般爲每一個列表之間設置必定的間距(margin-right),當父元素的寬度固定式,每一行的最右端的li元素的右邊距就多餘了,去除的方法一般是爲最右端的li添加class,設置margin-right:0; 這種方法須要動態判斷爲哪些li元素添加class,麻煩!!!利用負margin就能夠實現下面這種效果:it
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; }
效果:
列表中咱們常常會添加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"></p> </div> <div id="center"> <p style="height:100px"></p> </div> <div id="right"> <p 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}
效果: