Skip to content

06 margin 负值问题

查看代码
html
<p>用于测试 margin top bottom 的负数情况</p>
<div class="container">
  <div class="item item1 border-blue">this is item 1</div>
  <div class="item item2 border-red">this is item 2</div>
</div>

<p>用于测试 margin left right 的负数情况</p>
<div class="container clearfix">
  <div class="item item3 border-blue float-left">this is item 3</div>
  <div class="item item4 border-red float-left">this is item 4</div>
</div>
css
body {
  margin: 20px;
}

.float-left {
  float: left;
}
.clearfix:after {
  content: '';
  display: table;
  clear: both;
}

.container {
  border: 1px solid #ccc;
  padding: 10px;
}
.container .item {
  width: 100px;
  height: 100px;
}
.container .border-blue {
  border: 1px solid blue;
}
.container .border-red {
  border: 1px solid red;
}

.item1 {
  /*   margin-top: -20px; */
  /*   margin-bottom: -20px; */
}

.item2 {
  /*   margin-top: -20px; */
  /*   margin-bottom: -20px; */
}

.item3 {
  /*   margin-left: -20px; */
  /*   margin-right: -20px; */
}

.item4 {
  /*   margin-left: -20px; */
  /*   margin-right: -20px; */
}

  • margin-topmargin-left 负值,元素向上、左移动
  • margin-right 负值,右侧元素向左移动,自身不受影响
  • margin-bottom 负值,下方元素向上移动,自身不受影响