负边距式布局
所谓的负边距就是margin取负值的情况,如margin:-100px,margin:-100%。当一个元素与另一个元素margin取负值时将拉近距离。
在网页的布局当中,负边距起到了很大的作用。
利用负边距形成的三栏布局
三栏布局即两边宽度一定,中间宽度自适应的布局模式。
元素的最终边界是由margin决定的,margin为负的时候就相当于元素的边界线向里收,文档流认的只是这个边界,不会管你实际的尺寸。
<div class="parent">
<div class="left">left</div>
<div class="center">
<div class="innertext">这是中间栏的内容</div>
</div>
<div class="right">right</div>
</div>
//style
.left{
width: 200px;
float: left;
height: 200px;
background-color: #b5c4b1;
}
.center{
width:100%;
height:200px;
float:left;
margin-right: -400px;
background-color: #ead0d1;
}
.right{
width: 200px;
float: left;
height: 200px;
background-color: #f8ebd8;
}
.innertext{
margin-right: 400px;
}
我们只需要不断的调整中间栏的负边距以及中间栏内容部分的边距就可以实现这样的三栏布局,是三栏布局中较为简单的一种,但在实际应用中并没有什么优势。
利用负边距去除块级元素中间的间隙
我们在实现如上样式时总会多出来一个margin让列表无法按照我的的想法排列变成下图这样
这种情况我们只需要给ul加一个负边距,抵消掉多出来的margin就ok
<div class="box">
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
</ul>
</div>
.box{
width:320px;
height:210px;
background:#ead0d1;
}
ul{
margin-right:-10px;
}
li{
width:100px;
height:100px;
background:#f8ebd8;
margin-right:10px;
margin-bottom:10px;
float:left;
}
去除列表最后一个li元素的border-bottom
列表中我们经常会添加border-bottom值,最后一个li的border-bottom往往会与外边框重合,视觉上不雅观,往往要移除。方法有多种,加class去除,这种方法需要破坏html结构;不过,我们可以为li元素设置margin-bottom:-1px;来实现,不过不要为ul/ol设置高度,需要高度请在外层嵌套一个div设置高度。
ul{
margin:20px;
width:390px;
background:#F4F8FC;
-moz-border-radius:3px 3px 3px 3px;
-webkit-border-radius:3px 3px 3px 3px;
border-radius:3px 3px 3px 3px;
border:2px solid #D7E2EC;
}
li{
height:25px;
line-height:25px;
padding:5px;
border-bottom:1px dotted #D5D5D5;
margin-bottom:-1px;
}
水平垂直居中
使用绝对定位将box的定点定位到body的中心,然后使用负margin(content宽高的一半),将box的中心拉回到body的中心,已到达水平垂直居中的效果。
.box{
width:400px;
height:400px;
position:absolute;
top:50%;
left:50%;
margin-left:-200px;
margin-top:-200px;
border:1px dashed #ead0d1;
background:#f8ebd8;
}