一、简介
margin我们一般叫他外边距,分别是设置四个方向的外边距,实际上我们通常设置的margin是物理级别的参数,而margin还有start,end,before等逻辑级别的设置,参考margin
二、margin负值
为margin设置负值效果总结起来就是:
上和左方的 margin 负值使该元素向上和左方向移动。
下和右方的 margin 负值使该元素下方、右方相邻的元素向上或者向左移动。
例子:
.main{
width:300px;
height: 300px;
border: 1px solid red;
margin: 100px auto;
}
.child {
height: 100px;
width: 100px;
text-align: center;
line-height: 100px;
}
.child1{
display: inline-block;
background-color:lightcoral;
}
.child2{
display: inline-block;
background-color:yellowgreen;
}
.child3{
background-color:purple;
}
<div class="main">
<div class="child child1">1</div><div class="child child2">2</div>
<div class="child child3">3</div>
</div>
在对①使用margin-top:-50px和margin-left:-50px的时候,①分别向上方和左方移动了50个像素。(margin-top和margin-bottom的时候只对块级元素起作用)![margin上左.png]
而使用 margin-bottom: -50px 和 margin-right: -50px 的例子,位于下方和右方的②向①方向移动了50个像素,覆盖了①的一部分
三、margin负值的应用
3.1水平垂直居中
<div class="box">
<div class="out">
<div class="content">水平垂直居中</div>
</div>
</div>
.box {
position: relative;
width: 300px;
height: 300px;
background: #ddd;
}
.out {
position: absolute;
top: 50%;
left: 50%;
}
.content {
width: 100px;
height: 100px;
margin: -50px 0 0 -50px;
background: lightblue;
}
3.2列表项两端对齐
.box1 {
float: left;
width: 400px;
height: 400px;
background: #ffeecc;
}
.list {
overflow: hidden;
margin-right: -20px;
}
.item {
float: left;
width: 120px;
height: 400px;
margin-right: 20px;
background: #acacab;
}
<div class="box1">
<div class="list">
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
</div>
</div>
3.3等高布局
通过给所有item栏目设置超高padding撑开,再用相同的margin值消除的原理,实现等高布局。等高布局
3.4三栏自适应布局
通过对三栏全部设置左浮动,使他们处于同一个文档流,再用margin负值调整位置。三栏自适应布局
四、参考
http://www.hicss.net/i-know-you-do-not-know-the-negative-margin/
代码地址