先说结论吧,你遇到的情况这里应该都会包含:
-
块级元素设置 margin-top margin-bottom 都会发生位移,只不过设置 margin-bottom,会发生位移的是其后边的元素;
-
行内元素 设置margin-top margin-bottom 都不会发生位移,添加绝对定位(让其脱离文档流,比如浮动固定定位),设置margin-top会发生位移; 改变vertical-align的设置(middle top),行内块元素设置 margin-top margin-bottom 可以发生位移;
-
设置 margin-left 块级元素和行内元素都会发生位移,不同的是块级元素后边的内容不会发生位移,行内元素后的内容会发生位移(因为行内元素后的内容是跟它在同一行呀);
-
块级元素 设置 margin-right,自身宽度增加;行内元素 设置 margin-right,元素后边的行内元素会根据数值位移
注:影响margin显示效果的因素:display 定位机制 verticle-align
应用
1.两栏布局
左栏定宽,右栏自适应;让左栏占据左侧border的位置
.box {
border-left: 150px solid transparent;
}
.one {
width: 150px;
height: 50px;
background-color: red;
float: left;
margin-left: -150px;
}
.two {
height: 50px;
background-color: green;
}
复制代码
<div class="box">
<div class="one"></div>
<div class="two"></div>
</div>
复制代码
2.水平垂直居中
元素绝对定位的top和left值设置为50%会多一半自身的长度;用margin偏移自身的一半位置回来
.box {
position: relative;
height: 300px;
}
.one {
position: absolute;
left: 50%;
top: 50%;
width: 100px;
height: 100px;
margin: -50px 0 0 -50px;
background: red;
}
复制代码
<div class="box">
<div class="one"></div>
</div>
复制代码
3. 列表一边间隙
当列表中最后一个li的margin值超出了盒子的大小,让其父元素给margin设置为负值是超出那部分的大小,注意需要嵌套一层盒子,因为其盒子的大小已经定好,设置负的margin值不影响其长度大小
.container {
width: 80px;
height: 100px;
background-color: turquoise;
}
.box {
padding: 0;
margin: 0;
height: 100%;
overflow: hidden;
margin-right: -10px;
}
.one {
margin-right: 10px;
height: 100%;
width: 20px;
background-color: tomato;
list-style: none;
float: left;
}
复制代码
<div class="container">
<ul class="box">
<li class="one"></li>
<li class="one"></li>
<li class="one"></li>
</ul>
</div>
复制代码
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END