我在w3schools.com上看到了这个例子。该网站说
应使用style =“position:relative”创建容器元素。 应使用style =“position:absolute”创建animation元素。
我不明白为什么会这样。有人可以请你解释一下。
<!Doctype html>
<html>
<style>
#container {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#animate {
width: 50px;
height: 50px;
position: absolute;
background: red;
}
</style>
<body>
<h1>My First JavaScript Animation</h1>
<div id="container">
<div id="animate"></div>
</div>
</body>
</html>
答案 0 :(得分:1)
position: absolute
的重点是根据父元素定位它。
实现这一目标的唯一方法是在父元素上使用position: relative
。
由于默认位置值为position: static
,绝对定位的元素不能基于此。
如果没有position: relative
的父元素,position: absolute
元素将根据html定位自己。
这是关于CSS-Tricks上不同位置值的好文章:
https://css-tricks.com/absolute-relative-fixed-positioining-how-do-they-differ/
引用position: relative
上的css-tricks帖子:
请记住,这些值将相对于具有相对(或绝对)定位的下一个父元素。如果没有这样的父母,它将一直默认为&lt; html&gt;元素本身意味着它将相对于页面本身放置。
答案 1 :(得分:1)
通过在元素上设置position: absolute
,它将从文档的正常渲染流中移除,并且它会准确呈现在您告诉它的位置。您在此元素(left
,right
,top
,bottom
)上设置的任何定位规则都将使用最近的祖先{{1}来计算} 如果设置了或position:relative
元素。
如果您需要快速扩展对CSS定位的理解,我建议this tutorial。