给子元素添加margin-top不生效,父元素受到影响的解决办法

今天写css的时候遇到一个问题,当给子元素添加margin-top的时候,子元素不生效,反而父元素被添加上了,严重影响页面布局。

例子代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>给子元素添加margin-top,父元素也受到影响</title>
    <style type="text/css">
        *{
     
            margin:0;
            padding: 0;
        }
        .father{
     
            width:500px;
            height: 500px;
            background: #f00;
            /*注意这里代码*/
            /* padding-top:1px; */
            /* border:1px solid #fcc; */
            /* overflow: hidden; */

        }
        .son{
     
            width:200px;
            height: 200px;
            margin-top:200px;
            background: #0f0;
        }
    </style>
</head>
<body>
    <div class="father">
        <div class="son"></div>
    </div>
</body>
</html>

如图所示
给子元素添加margin-top不生效,父元素受到影响的解决办法_第1张图片
解决方法:
给父元素添加上注释里的属性,任意一个都可以解决
给子元素添加margin-top不生效,父元素受到影响的解决办法_第2张图片

具体原因请移步:
https://blog.csdn.net/u012011360/article/details/41823125,这位博主有详细解答

你可能感兴趣的:(html,css,css,html,css3,html5)