20200821 丁浪

hc中一些很很反直觉的现象

上外边距溢出


上外边距溢出现象

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        /* 
        外边距溢出:
                条件:
                    子元素上边距与父元素上边距紧紧贴合
                    子元素拥有上外边距            
         */
        .wrap{
            width: 500px;
            height: 500px;
            background-color: #f9f9f9;
        }
        .wrap>div{
            width: 250px;
            height: 250px;
            margin-top: 100px;
            background-color: #f00;
        }
    </style>
</head>
<body> 
    <div class="wrap">
        <div>

        </div>
    </div>
    
</body>
</html>

造成原因

如线图,浅黄色的盒子与粉色的盒子在特定的条件下会发生上外边距溢出现象,条件:当且仅当父元素无边框和上内边距,父子元素之间没有其他有height或者padding值的元素,包括伪元素。

解决方案

  1. 不为子元素设置上外边距
  2. 为父元素设置一个内边距
  3. 为父元素设置一个边框
  4. (最优)在父元素和子元素间添加一个空格div设置其display为table或直接添加一个空的table标签
  5. (最最优)选中父元素的before伪元素,设置content为"",并设置其display为table
  6. 选中父元素的before伪元素,设置其content为"",并设置其高度为非0值,或者设置其padding为非0值。

上下外边距重合

如果两个上下相邻的盒子既有上边距,又有下边距,那么两个盒子之间的边距以这二者中的大值为准,这不会发生在左右边距之上。

上下外边距重合现象

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .wrap{
             background-color: #d8bdbd;
            height: 150px;
        }
        .wrap01{
            margin-bottom: 50px;
            width: 50px;
            height: 50px;
            background-color: #f00;
        }
        .wrap02{
            margin-top: 40px;
            width: 50px;
            height: 50px;
            background-color: #00f;
        }


    </style>
</head>
<body> 
    <div class="wrap">
        <div class="wrap01">
        
        </div>
        <div class="wrap02">
    
        </div>
    </div>
</body>
</html>

margin-top相对高度的基准为父元素的width

按着直觉去看,该段代码应当能将子元素设置为垂直方向的居中对齐,但是结果去不是如此,原因是margin相对高度基准为父元素的width,所以小红方块出现的位置很靠下

<!DOCTYPE HTML>
<html>

<head>
  <meta charset="utf-8">
  <title>42度空间-多行内联元素垂直居中-伪元素</title>
  <style>
    .wrap {
      height: 400px;
      position: relative;
      /* width: 500px; */
      background-color: #00f;
    }

    .wrap>div {
      width: 50px;
      height: 50px;
      background-color: #f00;

      position: absolute;
      margin-top: 50%;
    }
  </style>
</head>

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

</html>

评论