2016-11-16 94 views
0

我希望div能够垂直和水平地坐在页面中间。我正在寻找一个CSS解决方案。我拿出了保证金和保证金,因为他们与我拥有的头文混为一谈。如何将此div垂直居中以及水平居中?

/* CSS */ 
 

 
.mainDiv { 
 
    background: #fff; 
 
    padding: 20px; 
 
    width: 450px; 
 
    margin: auto; 
 
    /*margin: 0px auto; 
 
    margin-top: 200px;*/ 
 
    box-shadow: 0 0 20px #333; 
 
}
<!-- HTML --> 
 

 
<div class="mainDiv" align="right"> 
 
    <h1 align="left">Firebase Web App</h1> 
 
    <textarea placeholder="Enter text here ..."></textarea> 
 
</div>

FIDDLE

https://jsfiddle.net/gy0Lr6rg/

+0

就一个词使用height: 100%;:flexboxes。 (我有机会回答这个问题给其他人) –

+0

这可以帮助你http://stackoverflow.com/questions/356809/best-way-to-center-a-div-on-a-page-vertically-和水平?rq = 1 – Alexis

+0

同样的问题 - > [如何垂直中心的所有浏览器](http://stackoverflow.com/questions/396145/how-to-vertically-中心-A-DIV参加的所有的浏览器) –

回答

2

试用flexboxes:

.flex-container { 
 
    display: flex; 
 
    justify-content: center; 
 
    align-items: center; 
 
    height: 100vh; 
 
} 
 

 
.mainDiv { 
 
    background: #fff; 
 
    padding: 20px; 
 
    width: 450px; 
 
    /*margin: auto; 
 
    /*margin: 0px auto; 
 
    margin-top: 200px;*/ 
 
    box-shadow: 0 0 20px #333; 
 
}
<div class="flex-container"> 
 
    <div class="mainDiv" align="right"> 
 
     <h1 align="left">Firebase Web App</h1> 
 
     <textarea placeholder="Enter text here ..."></textarea> 
 
    </div> 
 
</div>

0

尝试围绕div与另一个div并使用height: 100%;就可以了。它在某些情况下适用于我。但它不会在jsfiddle中工作,因为高度不够大。您也可以尝试在你的body标签

0

.mainDiv { 
 
    background: #fff; 
 
    padding: 20px; 
 
    width: 450px; 
 
    height:150px; 
 
    margin-left: -225px; 
 
    margin-top:-75px; 
 
    /*margin: 0px auto; 
 
    margin-top: 200px;*/ 
 
    box-shadow: 0 0 20px #333; 
 
    position:absolute; 
 
    top:50%; 
 
    left:50%; 
 
}
<div class="mainDiv" align="right"> 
 
    <h1 align="left">Firebase Web App</h1> 
 
    <textarea placeholder="Enter text here ..."></textarea> 
 
    </div>