元素外边距可以为零/正数/负数.我们可以设定外边距为负值,调整元素的位置.
特点
margin-left为负时向左移动,后面的元素也跟着移动
行内元素也一样
Alice was beginning to get very tired
of
sitting by her sister on the bank
用margin上移元素,其后的元素会跟随向上移动
relative可起到类似效果,但原本所占空间仍然被保留
margin-top | margin-left 为负时,元素向对应方向移动
margin-right | margin-bottom 为负时,对自身位置无影响,后面的元素覆盖其上
未声明元素宽度时,负边距可以增加元素宽度
子元素宽度100%
对浮动元素的影响
Alice was beginning to get very tired
of
sitting by her sister on the bank
对绝对定位元素的影响
绝对定位元素后脱离文本流,因此后面的元素被盖在了下边
尽管声明了left:0;top:0;但margin还是对元素位置产生了影响
应用
圣杯布局
优点
- 先渲染中间,后渲染两侧
- 中部自适应,两侧定宽
<style>
.box-10 {
width: 300px;
border: 1px solid;
overflow: auto;
padding-left: 100px;
padding-right: 100px;
}
.box-10 * {
height: 50px;
float:left;
}
.child-10-main {
width:100%;
background: red;
}
.child-10-left {
width: 100px;
margin-left:-100%;
position: relative;
left: -100px;
background: yellow;
}
.child-10-right {
width:100px;
margin-left:-100px;
position:relative;
right:-100px;
background: green;
}
</style>
<div class="box-10">
<div class="child-10-main"></div>
<div class="child-10-left"></div>
<div class="child-10-right"></div>
</div>
双飞翼布局
双飞翼布局其实就是去掉相对定位的圣杯布局
<style>
.box-11 {
width: 350px;
border: 1px solid;
overflow: auto;
}
.box-11 > * {
height: 50px;
float:left;
}
.child-11-main {
width:100%;
}
.child-11-mainContent {
height: 50px;
background: red;
margin: 0 100px;
}
.child-11-left {
width: 100px;
margin-left:-100%;
background: yellow;
}
.child-11-right {
width:100px;
margin-left:-100px;
background: green;
}
</style>
<div class="box-11">
<div class="child-11-main">
<div class="child-11-mainContent"></div>
</div>
<div class="child-11-left"></div>
<div class="child-11-right"></div>
</div>