Relative 定位与Absolute 定位实例

  一直没有弄懂相对定位与绝对定位之间的关系,今天特来学习一下。本实践都是在360浏览器下测试所得。

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">

<style type="text/css">
 .hv
{
position:relative;
left:100px;
top:150px;
}
 .hv2
{
position: absolute;
left:100px;
top:150px;
}

h2{ background-color:gray;}
p{background-color: red;}
</style>
<title>
last
</title>
</head>
<body>
<h2 class="hv2">This is a heading  an absolute position This is a heading  an absolute positionThis is a heading  an absolute positionThis is a heading  an absolute position</h2>

    
<p>With absolute positioning, an element can be placed anywhere 方法on a page. The heading below is placed 100px from the left of the page and 150px from the top of the page.</p>


</body>
</html>

获得html高度是68px=p元素高度+margin=36px+16px+16px=body高度+p的margin=36px+16px+16px

获得body高度是36px=p元素高度=36px

获得h2高度是54px margin 20px

获得p高度是36px margin 16px

修改一下把样式改成hv 即position:relative 则

获得html高度是146px=body高度+h2 顶部margin +p底部 margin=110px+20px+16px

获得body高度是 110px=h2高度+p元素高度+h2与p元素之间的margin=54px+36px+20px=110px

获得h2高度是54px margin 20px

获得p元素高度是36px margin 16px

不设置样式即默认

获得html高度是146px=body高度+h2 顶部margin +p底部 margin=110px+20px+16px

获得body高度 110px=h2高度+p元素高度+h2与p元素之间的margin=54px+36px+20px=110px

获得h2高度 54px margin 20px

获得p元素高度 36px margin 16px

得出结论:

position:relative 可以移动的相对定位元素的内容和相互重叠的元素,它原本所占的空间不会改变。

position:absolute 定位使元素的位置与文档流无关,因此不占据空间。

 相对定位占空间,绝对定位不占空间

 参考:http://www.runoob.com/css/css-positioning.html

相关博文:http://blog.csdn.net/dyllove98/article/details/8967114

原文地址:https://www.cnblogs.com/xiaohuasan/p/5196022.html