2015-12-06 49 views
0

我從w3schools.com看到這個例子。該網站說,什麼位置屬性應該分配給「容器」元素和「動畫」元素? html css javascript

容器元素應該創建與style =「位置:相對」。 應該使用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> 

回答

1

position: absolute整點是根據父元素定位它。

可以實現的唯一方法是在父元素上使用position: relative

由於默認位置值爲position: static絕對定位的元素不能基於此。

如果沒有父元素position: relativeposition: absolute元素將根據html定位自​​己。

這裏有關於CSS-技巧的不同位置值的偉大的職位:從CSS-技巧

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

報價張貼在position: relative

請記住,這些值將是相對的到相對(或絕對)定位的下一個父元素。如果不存在這樣的父項,它將默認一直返回到HTML元素本身,這意味着它將相對於頁面本身放置。

1

通過在元素上設置position: absolute,它將從文檔的正常渲染流程中移除,並且它完全呈現在您告訴它的位置。你這個元件上設置的任何定位規則(leftrighttopbottom)將使用如參考position:relative最接近祖先如果任何被設定body元件來計算。

如果您需要擴大您對CSS定位的快速瞭解,我推薦this tutorial