css位置相对于绝对值

问题描述 投票:0回答:1

我使用相对位置遇到了麻烦。以下代码在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到右边和底部。怎么解决这个问题呢?

css position absolute relative
1个回答
3
投票

position:absolute意味着它是基于祖先的左上角定位的,该祖先是具有位置规范的父级,或者如果没有,则是<body>元素本身。然而,position:relative意味着它的位置是基于它没有被重新定位时通常会采取的位置(即正常位置+偏移)。如果你的代码是这样的:

<div id="background"><div id="p1">...</div></div>

那意味着background应该位于左上角(加上偏移量),但是p1应该是100像素,并且在它的父角background的右边。

编辑:修正了有关这两个职位的定义。

© www.soinside.com 2019 - 2024. All rights reserved.