简体   繁体   中英

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

I saw this example from w3schools.com. The website says that

The container element should be created with style = "position: relative". The animation element should be created with style = "position: absolute".

I don't understand why this is the case. Could someone please kindly explain it to me.

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

The whole point of position: absolute is to position it BASED on the parent element.

The only way this can be achieved is through the use of position: relative on the parent element.

Since the default position-value is position: static the absolutely positioned element can not be based on that.

If there is no parent element with a position: relative the position: absolute element will position itself according to the html.

Here's a great post about the different position values on CSS-Tricks:

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

Quote from the css-tricks post on position: relative :

Remember that these values will be relative to the next parent element with relative (or absolute) positioning. If there is no such parent, it will default all the way back up to the <html> element itself meaning it will be placed relatively to the page itself.

By setting position: absolute on an element it is removed from the documents' normal rendering flow and it is rendered exactly where you tell it. Any positioning rule you set on this element ( left , right , top , bottom ) will be calculated using as reference the closest ancestor with position:relative if any is set or the body element .

If you need to broaden your understanding of CSS positioning fast, I recommend this tutorial .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM