2015-07-20 79 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 
    }); 
});