負邊距(negative margin)在頁面制作過程中,有許多妙用,用的好了能讓原本復雜的問題變的簡單,本文是針對負邊距相關問題的整理,歡迎各位補充。
負邊距的使用非常簡單:
CSS: -
-
<style type="text/css">
-
/*
-
說明:負邊距(negative margin)的相關問題整理
-
整理:CodeBit.cn ( http://www.codebit.cn )
-
*/
-
.one {
-
height:100px;
-
width:300px;
-
border:2px solid red;
-
margin-bottom:-10px;
-
}
-
.two {
-
height:100px;
-
width:300px;
-
border:2px solid blue;
-
}
-
</style>
-
HTML: -
-
<p class="one"></p>
-
<p class="two"></p>
-
這時,我們會看到藍色的框伸到了紅色框的里面,下面總結一些問題:
如何改變覆蓋順序
在本例中,就是如何讓紅色框覆蓋藍色框,很簡單,在需要覆蓋到上面的元素樣式中添加 : position:relative; 在本例中,就是要在紅色的樣式 .one 中添加。
負邊距可以用在哪些地方:
導航高亮效果的實現:CSS: -
-
<style type="text/css">
-
/*
-
說明:負邊距(negative margin)的相關問題整理
-
整理:CodeBit.cn ( http://www.codebit.cn )
-
*/
-
.nav, .nav li {
-
list-style:none;
-
}
-
.nav li {
-
border:2px solid #000;
-
float:left;
-
margin-left:10px;
-
background:#333;
-
padding:3px 20px;
-
margin-bottom:-2px; /* 遮蓋下面內容的邊框部分 */
-
position:relative; /* IE 下要添加此行 */
-
}
-
.nav a {
-
color:#fff;
-
text-decoration:none;
-
}
-
.nav li.current {
-
border-bottom:2px solid #eee; /* 當前的把下邊框的顏色換成和下邊內容相同的 */
-
background:#eee; /* 背景的顏色也換成相同的 */
-
}
-
.nav li.current a {color:#000;}
-
.content {
-
border:2px solid #000;
-
background:#eee;
-
height:100px;
-
width:300px;
-
clear:both;
-
}
-
</style>
-
HTML: -
-
<ul class="nav">
-
<li class="current"><a href="">當前</a></li>
-
<li><a href="">導航</a></li>
-
<li><a href="">導航</a></li>
-
</ul>
-
<div class="content">
-
</div>
-
結果:
注意:firefox 下面 .nav li 不用加 position:relative; 也能覆蓋到下面的 div ,但是 ie 下面要加上。
修正 IE 的 bug相信大家都很了解 IE 的 3 像素 bug,當浮動元素和非浮動元素相鄰時,會增加額外的 3 像素,這個時候,我們就可以用負邊距來解決(并非唯一的辦法):
CSS: -
-
<style type="text/css">
-
/*
-
說明:負邊距(negative margin)的相關問題整理
-
整理:CodeBit.cn ( http://www.codebit.cn )
-
*/
-
#floatContent {
-
float: left;
-
width: 300px;
-
}
-
#otherContent {
-
margin-left: 300px;
-
}
-
/* 對 MacIE 隱藏 \*/
-
* html #floatContent {
-
margin-right: -3px;
-
}
-
* html #otherContent {
-
height: 1%; /* 如果你沒有設置 #otherContent 的高度或者寬度 */
-
margin-left: 0;
-
}
-
/* 隱藏結束 */
-
</style>
-