2011-12-24 107 views
0

我期待以下內容將位於瀏覽器窗口座標系中位置50,50處的內部(紅色)方塊。但事實並非如此。爲什麼?爲什麼留下填充不起作用?

<body> 
<div style="position: fixed; left: 0px; right: 0px; top: 0px; bottom: 0px; background-color: yellow; padding: 50px;"> 
    <div style="position: absolute; left: 0px; right: 0px; width: 64px; height: 64px; background-color: red"> 
    </div> 
</div> 
</body> 

對不起我的錯

我希望讓「頂:0像素」的內部DIV但寫道「右:0像素」來代替。只是一個錯誤。

+0

這是一種相當......獨特的做事方式。你能告訴我們爲什麼你以這種方式使用'position:fixed'和'position:absolute'?對於你想要完成的任務,可能有更好的解決方案。 – 2011-12-24 17:10:57

+0

你想讓紅色方塊在滾動時停留在那個位置嗎?我不確定你的意思是「瀏覽器窗口座標系」。 – moey 2011-12-24 17:16:11

+0

如果你覺得你已經解決了這個問題,請發表並接受你自己的答案。 – Wex 2011-12-24 17:21:48

回答

3

position: absolute;將您的元素帶出正常流程。既然你把它指定爲0,那就是它的位置。

+0

那麼爲什麼它不會做頂部? – Dims 2011-12-24 17:15:49

2

你內心的div的位置是absolute。嘗試relative,或根本不設置該屬性。

0

嗯,那是因爲你position: absolute它有left: 0;你可能想要的東西,像這樣:

<body> 

    <div style="position: fixed; left: 0px; right: 0px; top: 0px; bottom: 0px; background-color: yellow; padding: 50px;"> 
     <div style="position: absolute; left: 50px; right: 0px; width: 64px; height: 64px; background-color: red"> 
     </div> 
    </div> 

</body> 
0

由於position: absolute;上的紅色方塊。

你可以拿出來拿this,或者設置left屬性,並得到this。另外,作爲一個附註,有些人建議(包括我自己)在值爲0時不要將度量單位附加到CSS屬性上。零的東西還是零,所以0px,0em等等,沒關係,它總是評估爲0.

0

左上角和下角的css表示'距離'。這並不意味着以您使用它的方式使用。

這裏有一個更好的例子:http://jsfiddle.net/xAuLJ/

<body> 
<div style="position: fixed; width:100%; height:100%; background-color: yellow;"> 
    <div style="position: absolute; left: 50%; top: 50%; width: 64px; height: 64px; margin-top:-32px; margin-left:-32px; background-color: red"> 
    </div> 
</div> 
</body> 
0

這是我自己的錯。我希望爲內部DIV製作「top:0px」,而不是寫成「right:0px」。當元素向下移動但不是正確時,我決定頂部填充與左側不同。

+0

可能最好把這個納入你的問題而不是創建一個新的答案。 – mc10 2011-12-24 18:16:07