应该为“容器”元素和“动画”元素分配什么位置属性?HTML CSS JavaScript.

what position property should be assigned to "container" element and "animation" element? html css javascript

本文关键字:元素 属性 位置 HTML JavaScript CSS 什么 动画 容器 分配      更新时间:2023-09-26

我从 w3schools.com 看到了这个例子。该网站说

容器元素应使用 style = "position: relative " 创建。动画元素应使用 style = "position: absolute " 创建。

我不明白为什么会这样。有人可以向我解释一下吗?

<!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>

通过在元素上设置position: absolute,它将从文档的正常呈现流程中删除,并准确地呈现在您告诉它的位置。您在此元素上设置的任何定位规则(leftrighttopbottom(都将使用最接近的祖先作为参考,如果设置了position:relativebody元素

如果你需要快速拓宽对CSS定位的理解,我推荐本教程。

position: absolute的全部

意义在于根据父元素定位它。

实现此目的的唯一方法是在父元素上使用position: relative

由于默认位置值是position: static因此绝对定位的元素不能基于该值。

如果没有带有position: relative的父元素,则position: absolute元素将根据 html 定位自身。

这里有一篇关于CSS技巧上不同位置值的好文章:

https://css-tricks.com/absolute-relative-fixed-positioining-how-do-they-differ/

引用 css-tricks 帖子 在 position: relative 上:

请记住,这些值将相对于具有相对(或绝对(定位的下一个父元素。如果没有这样的父元素,它将默认一直返回到

元素本身,这意味着它将相对于页面本身放置。