2015-11-22 78 views
1

有一個動態內容的div。父母的身高是身體的100%,孩子是未知的。 translateY(-50%)技術只有在子內容高度小於父級時纔有效。但如果更多的子div(綠色)開始溢出父母(黃色)如下圖像。 enter image description here 什麼是設置父div的正確方法增加高度並添加一些填充。垂直居中的div,增加父母身高

.body { 
 
    height: 300px; 
 
    background: red; 
 
} 
 
.parent { 
 
    height: 100%; 
 
    position: relative; 
 
    background: rgb(105, 199, 115); 
 
    
 
} 
 
.child { 
 
    position: absolute; 
 
    top: 50%; 
 
    left: 50%; 
 
    transform: translate(-50%, -50%); 
 
    background: green; 
 
    width: 200px; 
 
}
<div class="body"> 
 
    <div class="parent"> 
 
    <div class="child"> 
 
     Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, 
 
    </div> 
 
    </div> 
 
</div>

+2

你能表現出一定的來源? –

+0

我已經更新了這個問題。還更新了我的父div有100%的窗口大小,而不是100vh。 –

+0

你需要'min-height'而不是'height'。儘管如此,這對絕對定位的孩子來說不起作用。嗯。必須考慮。 –

回答

2

爲什麼位置?
您可以居中div使用該:
我用這個中心,動力高度在它的父一個div:

<style> 
    .body { 
     height: 300px; 
     background: red; 
     display:table; 
     width: 100%; 
    } 
    .parent { 
     display:table-cell; 
     vertical-align: middle; 
     background: rgb(105, 199, 115); 

    } 
    .child { 

     background: green; 
     width: 200px; 
     margin: auto; 
    } 
</style> 
<div class="body"> 
    <div class="parent"> 
     <div class="child"> 
      Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, Sample content, 
     </div> 
    </div> 
</div>