http://www.codebit.cn/css/negative-margin.html
负边距(negative margin)在页面制作过程中,有许多妙用,用的好了能让原本复杂的问题变的简单,本文是针对负边距相关问题的整理,欢迎各位补充。
负边距的使用非常简单:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
<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>
|
1
2
|
<
p
class
=
"one"
></
p
>
<
p
class
=
"two"
></
p
>
|
这时,我们会看到蓝色的框伸到了红色框的里面,下面总结一些问题:
如何改变覆盖顺序
在本例中,就是如何让红色框覆盖蓝色框,很简单,在需要覆盖到上面的元素样式中添加 : position:relative; 在本例中,就是要在红色的样式 .one 中添加。
负边距可以用在哪些地方:
导航高亮效果的实现:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
<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>
|
1
2
3
4
5
6
7
|
<
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 像素,这个时候,我们就可以用负边距来解决(并非唯一的办法):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
<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>
|
这里只是列举了部分和负边距相关的问题,欢迎各位修正、完善。