解决盒子塌陷问题

99 阅读1分钟

盒子塌陷问题

互相嵌套的块级元素,给子元素设置margin-top会作用在父元素身上,导致父元素一起往下移动

image.png

    .father {
      overflow: hidden;
      width: 600px;
      height: 600px;
      background-color: red;
    }
.son {
      width: 300px;
      height: 300px;
      margin-top: 20px;
      background-color: skyblue;
    }


  <div class="father">
    <div class="son"></div>
  </div>

解决方法

1.给父元素设置border-top

image.png

.father {
      border-top: 1px solid transparent;
      width: 600px;
      height: 600px;
      background-color: red;
    }

2.给父元素设置padding-top

image.png

    .father {
      padding-top: 10px;
      width: 600px;
      height: 600px;
      background-color: red;
    }

3.给父元素设置overflow: hidden;

image.png

.father {
      overflow: hidden;
      width: 600px;
      height: 600px;
      background-color: red;
    }

4.转换为行内块元素

image.png

.son {
      display: inline-block;
      width: 300px;
      height: 300px;
      margin-top: 20px;
      background-color: skyblue;
    }

5.设置浮动

image.png

.son {
  float: right;
  width: 300px;
  height: 300px;
  margin-top: 20px;
  background-color: skyblue;
}