我使用相对位置遇到了麻烦。以下代码在css中:
#background
{
background-color: gray;
position: absolute;
left: 100px;
top: 100px;
width: 500px;
height: 500px;
}
#p1
{
position: relative;
left: 100px;
top: 100px;
width: 10px;
height: 10px;
background-color: green;
}
在我看来,背景和p1的左上角应该是均匀的。但它根本就没有。我会说它被推到大约+ 50px到右边和底部。怎么解决这个问题呢?
position:absolute
意味着它是基于祖先的左上角定位的,该祖先是具有位置规范的父级,或者如果没有,则是<body>
元素本身。然而,position:relative
意味着它的位置是基于它没有被重新定位时通常会采取的位置(即正常位置+偏移)。如果你的代码是这样的:
<div id="background"><div id="p1">...</div></div>
那意味着background
应该位于左上角(加上偏移量),但是p1
应该是100像素,并且在它的父角background
的右边。
编辑:修正了有关这两个职位的定义。