zoukankan      html  css  js  c++  java
  • css 子元素margin-top影响了父元素

    源码

    <!DOCTYPE HTML>
    <html manifest="">
    <head>
      <style>
        .box1 {
          background-color: deepskyblue;
          height: 200px;
          width: 200px;
        }
        .box2 {
          background-color: coral;
          margin-top: 50px;
          height: 50px;
          width: 200px;
        }
      </style>
    </head>
      <body>
      <div class="box1">
        <div class="box2">
        </div>
      </div>
      </body>
    </html>
    

    效果

    可以看到box1虽然没有margin-top:50px,但是上方也留出了50px
    在这里插入图片描述

    原因

    css盒模型规定:

    In this specification, the expression collapsing margins means that adjoining margins (no non-empty content, padding or border areas or clearance separate them) of two or more boxes (which may be next to one another or nested) combine to form a single margin.
    所有毗邻的两个或更多盒元素的margin将会合并为一个margin共享之。毗邻的定义为:同级或者嵌套的盒元素,并且它们之间没有非空内容、Padding或Border分隔。

    解决方案

    1. 父级或子元素使用浮动或者绝对定位absolute
      浮动或绝对定位不参与margin的折叠
    2. 父级overflow:hidden;
    3. 父级设置padding
    4. 父级设置border
  • 相关阅读:
    TI达芬奇平台测试
    V4L2 常用控制命令
    Linux 线程编程
    HMM
    PCA & ICA
    SVD分解(转载)
    Factor analysis
    Mixtures of Gaussians and the EM algorithm
    Arduino 单个按键控制led灯闪烁、常亮、关闭
    django计算当前日期最近一周日期范围
  • 原文地址:https://www.cnblogs.com/luguojun/p/14294662.html
Copyright © 2011-2022 走看看