2015-05-08 22 views
0

我有我的頁面上的元素div包含p元素。獲取元素的高度,並用它在CSS

<div class="parent-div"> 

    <p>Here's some text</p> 

</div> 

我試圖讓p元素的外部高度,然後使用該號碼的保證金適用於父元素。

例如,如果p元素的高度是346px,那麼我想將346px的margin-top應用於父div

我可以使用jQuery的outerHeight()高度,但我不知道怎麼用這個數字的保證金適用於父元素。

任何意見是非常感謝。

回答

2
$('p').each(function(){//for each paragraph 
    $(this).parent().css("margin-top", $(this).outerHeight() +"px"); 
    //change its parent margin-top with the current p's outerHeight 
}) 
1
var height = $("#yourelement").outerHeight(); 
$("#parent").css('margin-top', height); 

您可以使用'css'方法將元素應用於樣式。