2017-01-02 38 views
-2

使用CSS屬性'position',如何在另一個div內創建div始終是父div的100%高度,在頂部和底部的40px的?它需要進行調整,以便如果父div的高度爲700px,則子div將爲620px(距邊距700px-80px)。這裏是我的意思的一個例子:CSS如何在div中定位div使它始終爲100%

Here父div(綠色)很高,所以孩子(橙色)必須伸展以適應空間。

here父母(綠色)被壓扁,所以孩子(橙色)必須通過壓扁自己以適應補償。

預先感謝您。

編輯:

下面是HTML林一起工作:

<div id="center-page"> 
    <p id="center-page-title">Blog</h1> 
    <div id="content"> 

    </div> 
</div> 
+0

有很多可能性。請與我們分享您正在使用的代碼。 –

+0

儘管稍有不足,您可以嘗試'高度:calc(100%-80px);'。 – Yemachu

+0

@Yemachu這不會工作,因爲當孩子div的高度設置爲100%,它需要從整個頁面100%,而不是像我想要的父div。 –

回答

0

試試這個:

#center-page { 
 
    position: relative; 
 
    background: green; 
 
    height: 700px; 
 
} 
 

 
#content { 
 
    position: absolute; 
 
    background: orange; 
 
    top: 40px; 
 
    bottom: 40px; 
 
    left: 0; 
 
    right: 0; 
 
}
<div id="center-page"> 
 
    <p id="center-page-title">Blog</h1> 
 
    <div id="content"> 
 

 
    </div> 
 
</div>

+0

正是我需要的。非常感謝你。 –

+0

不客氣,那麼請把它標記爲答案:) –

0

你可以嘗試用topbottom值絕對定位。事情是這樣的:

#child{ 
    position: absolute; 
    top: 40px; 
    bottom: 40px; 
    left: 0; 
    right: 0; 
    background: blue; 
} 

下面是一個例子: https://jsfiddle.net/Lys72mgy/