2015-07-20 74 views
0

我正在嘗試使用一點點柔性盒子,並且我一直在嘗試瞭解如何做基本的事情,但我無法將div直接對準body,但我能夠以例如p爲中心元素在div內。爲什麼我不能將div直接放在體內?

這是HTML代碼:

<!DOCTYPE html> 

<html> 
    <head> 
     <link href="center.css" type="text/css" rel="stylesheet"> 
    </head> 

    <body> 
     <div class="parent"> 
      <p class="intro">This is a HTML template file.</p>   
     </div> 
    </body> 

</html> 

這是CSS文件:

body{ 
    display: flex; 
    display: -webkit-flex; 

    flex-direction: row; 
    -webkit-flex-direction: row; 

    justify-content: center; 
    -webkit-justify-content: center; 

    align-items: center; 
    -webkit-align-items: center; 

} 

.parent{ 
    margin: auto; 

    width: 300px; 
    height: 300px; 
    background-color: cornflowerblue; 

    display: flex; 
    display: -webkit-flex; 

    flex-direction: row; 
    -webkit-flex-direction: row; 

    justify-content: center; 
    -webkit-justify-content: center; 

    align-items: center; 
    -webkit-align-items: center; 

} 

.intro{ 
    margin: auto; 
    color: darkblue; 
} 

基本上我採用同樣的技術作爲p元素定心div元素中.. 。

這不適用於Safari或Chrome。

+1

您需要的寬度和高度設置爲100%爲HTML,然後身體才能看到它的工作全頁。添加body {border:solid;),看看它站在哪裏:) –

+0

@GCyrillus謝謝,工作!但爲什麼我們需要弄亂html標籤?我認爲身體代表了真正的內容... – nbro

+1

flex在其內容上縮小了元素。寬度和高度的百分比值需要設置值的父級,否則爲空值的百分比。 HTML將視口尺寸作爲參考:)所以視口尺寸值通過html組合成實體 –

回答

4

您需要設置widthheight100%htmlbody,才能看到它完整的網頁上正常運行。

添加到您的代碼:

body{ 
    border:solid; 
} 

,看看它的立場!

html, body { 
 
    height: 100%; 
 
    width: 100%; 
 
    margin: 0; 
 
} 
 

 
body { 
 
    display: flex; 
 
    display: -webkit-flex; 
 
    flex-direction: row; 
 
    -webkit-flex-direction: row; 
 
    justify-content: center; 
 
    -webkit-justify-content: center; 
 
    align-items: center; 
 
    -webkit-align-items: center; 
 
} 
 

 
.parent { 
 
    margin: auto; 
 
    width: 300px; 
 
    height: 300px; 
 
    background-color: cornflowerblue; 
 
    display: flex; 
 
    display: -webkit-flex; 
 
    flex-direction: row; 
 
    -webkit-flex-direction: row; 
 
    justify-content: center; 
 
    -webkit-justify-content: center; 
 
    align-items: center; 
 
    -webkit-align-items: center; 
 
}
<div class="parent"> 
 
    <p class="intro">This is a HTML template file.</p> 
 
</div>

0

CSS:

body { 
    background: #900; 
} 

div { 
    position: absolute; 
    left: 50%; 
    top: 50%; 
    transform: translate(-50%, -50%); 

    /* 
    This doesn't work 
    margin-left: -25%; 
    margin-top: -25%; 
    */ 

    width: 40%; 
    height: 50%; 

    padding: 20px; 
    background: red; 
    color: white; 
    text-align: center; 
    box-shadow: 0 0 30px rgba(0, 0, 0, 0.2); 
} 

DEMO

的jQuery:

$(function() { 
    $('.className').css({ 
     'position' : 'absolute', 
     'left' : '50%', 
     'top' : '50%', 
     'margin-left' : -$('.className').outerWidth()/2, 
     'margin-top' : -$('.className').outerHeight()/2 
    }); 
});