CSS中关于margin的理解误区

思考一

在之前,我对于margin的理解是这样的,此处用margin-top举例:指的是离相邻元素之间的距离。css

可是实际是:相对于自身原来的位置偏移。html

举个例子:编码

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <!-- 规定字符集的编码为utf-8 -->
    <meta charset="utf-8">

    <style type="text/css"> body { position: relative; padding: 0px; height: 500px;
        } #Red { width: 200px; height: 80px; border: 1px solid red; position: relative;
        } #Green { width: 200px; height: 80px; border: 1px solid yellowgreen; margin-top: 10px;
        }
    </style>
</head>

<body>

<div id="Red">Red</div>
<div id="Green">Green</div>

</body>
</html>

其表现为:spa

可是若是我把Red这个div设置下margin-top:10pxcode

此时Red会往下移动10px,若是按照最开始的理解:离相邻元素之间的距离。那么Green这个div也应该往下移动,可是实际上却不是如此,见下图htm

Green是没有移动的!blog

能够得出:margin是相对于自身原来的位置偏移。utf-8

思考二

下面是我在查看笔记的时忽然顿悟的:文档

结论:margin这种定位方式是会影响到后续的兄弟元素的,而relative这种定位方法是不会影响后续兄弟节点的。it

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <!-- 规定字符集的编码为utf-8 -->
    <meta charset="utf-8">

    <style type="text/css"> body { position: relative; padding: 0px; height: 500px;
        } #Green { width: 200px; height: 80px; border: 1px solid yellowgreen; float: left;
        } #Red { width: 200px; height: 80px; border: 1px solid red; float: left;

            /*状况1*/ margin-left: 20px;

            /*状况2*/
            /*position: relative;*/
            /*left: 20px;*/
        }
    </style>
</head>

<body>

<div id="Red">Red</div>
<div id="Green">Green</div>

</body>
</html>

注意查看Red这个div的CSS的2种状况。

第一种状况:margin-left

 

第二种状况:position+left

 

margin和position均未脱离文档流,可是他们致使的结果仍是不一样的,我我的更偏向于使用margin定位,由于好理解。

相关文章
相关标签/搜索