margin负值问题
Jonnzer Lv4

也许在工作中 hack 样式时,有用过 margin 负值,但是没正式归纳过。让我们好好梳理下~

第一种情况:元素没有设置浮动没有设置定位或者 position 为 static
1
2
<div class="container"></div>
<div class="center"></div>
1
2
3
4
5
6
7
8
9
10
11
.container {
width: 200px;
height: 100px;
background-color: #000;
margin-bottom: -50px;
}
.center {
width: 100px;
height: 100px;
background-color: greenyellow;
}

效果图如下:
情景1

分析:
(1)设置 margin-top 和 margin-left 时,都是自身移动 :top 就是往上位移,left 就是往左位移
(2)设置 margin-bottom 和 margin-right 时,自身不移动元素后面的元素(以下简称后面元素)往反方向位移:
margin-right 时就是,后面元素往左位移。 margin-bottom 时就是,后面元素往上位移。
并且,后面元素会覆盖在前面元素上面。

第二种情况:元素没有设置浮动position 为 relative
1
2
<div class="container"></div>
<div class="center"></div>
1
2
3
4
5
6
7
8
9
10
11
12
.container {
width: 200px;
height: 100px;
background-color: #000;
margin-bottom: -50px;
position: relative;
}
.center {
width: 100px;
height: 100px;
background-color: greenyellow;
}

情景2

分析:
(1)设置 margin-top 和 margin-left 时,都是自身移动 :top 就是往上位移,left 就是往左位移(同第一种)
(2)当设置 margin-bottom/right 的时候,元素本身也不会移动,元素后面的其他元素也会往该元素的方向移动相应的距离,但是,该元素会覆盖在后面的元素上面 (当然,此处说的情况肯定是后面的元素没有设置定位以及 z-index的情况)。

第三种情况:元素没有设置浮动position 为 absolute

分析:
(1)设置 margin-top 和 margin-left 时,都是自身移动 :top 就是往上位移,left 就是往左位移(同第一种)
(2)当设置 margin-bottom/right 的时候,不会对后面元素造成影响。因为该元素已经脱离了标准文档流。

第四种情况:元素有设置浮动 (涉及比较多✨ 需要重点看)

分析:
(1)当元素,设置的 margin 的方向与浮动的方向 相同,那么,该元素会往对应的方向移动对应的距离。
比如 float : left 和 margin-left:负值,该元素就会向左边位移。

应用场景:
双飞翼布局,中检侧float:left,width:100% 。
而右侧,可以设置width:100px ,margin-left:-100px,float:left。这样右侧会自动往左侧位移100px,就贴合在右边了。
而左侧,可以设置width:200px,**margin-left:-100%**,float:left。这样左侧会向左侧位移父盒子100%的宽度,就贴合在左边了。
撒花🎉

(2)当元素,设置的 margin 的方向与浮动的方向 相反,那么,该元素本身不动,元素前后的元素会往该元素的方向移动对应的距离。
比如 float : right 和 margin-left:负值,该元素就会向左边位移。


参考链接:
理解并运用 CSS 的负 margin 值 segmentFault

  • 本文标题:margin负值问题
  • 本文作者:Jonnzer
  • 创建时间:2020-04-08 18:21:35
  • 本文链接:https://jonnzer.github.io/2020/04/08/CSS/margin负值/
  • 版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
 评论