CSS margin负值的实际表现与应用

前端开发一些布局需求时常使用 margin 负值来达到效果,margin 负值在不同布局上会展现出不一样的效果。

① 针对两个上下布局的块元素(普通文档流):

HTML:

<div class="box1"></div>

<div class="box2"></div>

CSS:

.box1 {
  width: 200px;
  height: 200px;
  margin-bottom: -10px;
  background-color: #000;
}
.box2 {
  width: 200px;
  height: 200px;
  background-color: #F00;
}

实际效果:上方块元素设置 margin-bottom 负值,会将下方块元素往上拉,并且重叠部分被下方块元素所覆盖。

② 针对两个左右布局的左浮动块元素(流式布局):

HTML:

<div class="box1"></div>

<div class="box2"></div>

CSS:

.box1 {
  width: 200px;
  height: 200px;
  float: left;
  margin-right: -10px;
  background-color: #000;
}
.box2 {
  width: 200px;
  height: 200px;
  float: left;
  background-color: #F00;
}

实际效果:左方块元素设置 margin-right 负值,会将右方块元素往左拉,并且重叠部分被右方块元素所覆盖。

③ 针对未设宽度的块元素:

HTML:

<div class="wrap">
  <div class="box"></div>
</div>

CSS:

.wrap {
  width: 400px;
  height: 400px;
  background-color: #f00;
}
.box {
  height: 200px;
  margin-right: 10px;
  background-color: #000;
}

实际效果:处于内部的块元素未设置宽度,当设置 margin-right 负值时,该元素会向右侧延伸宽度;当设置 margin-left 负值时,该元素会向左侧延伸宽度。

此条目发表在CSS分类目录,贴了, , 标签。将固定链接加入收藏夹。