2014-07-19 410 views
2

我希望元素的margin-top爲父元素高度的百分比。將margin-top設置爲父元素高度的百分比

例如,如果我有高度爲100px的div,我希望在其內部創建一個包含margin-top:25px的p元素,除了通過設置p元素的邊距以便可以處理它的父級更改高度。

編輯:對於那些認爲這是顯而易見的 - 你不能使用margin-top:25%。 %除了高度以外使用父元素的寬度。因此,如果您使用margin-top:25%,則將其設置爲父div的寬度的25%。

+0

uhm ... margin-top:25%; ? –

+2

這不是那麼簡單 –

+1

Nah @brett,這不是保證金最高的25%。 margin-top%使用元素的寬度進行大小調整。 –

回答

2

這是我所看到的是解決方案之一:

<div style="height:100px; background-color:red; color:white; position:relative;"> 
    <div style="top: 25%;position: absolute;"> 
     <p> I want an elements margin-top to be a % of t</p> 
    </div> 
</div> 
0

嘗試定位元素,而不是給它一個餘量,像這樣:

p { 
    position: relative; 
    top: 50%; 
} 

Demo for reference

0

你可以使用JS來測量父元素在渲染後的高度(offsetHeight),然後將其除以4並將結果分配給childs top或marginTop屬性。

var parent = document.getElementById("parent"); 
var child = document.getElementById("child"); 
var marginVal = (parent.offsetHeight)/4; 
child.style.top = marginVal+"px"; 

小提琴:http://jsfiddle.net/Nillervision/AwqJK/

如果您纏繞JS的功能,您可以把它當頁面加載(在window.onload),並在瀏覽器中得到調整,如果改變的父元素的大小( window.onresize)

+0

Thanke Nillervision,但目前不接受JS答案 –

相關問題