2017-02-12 21 views
1

如何將#box div垂直居中對齊頁面?我試過vertical-align:middle;但它不起作用。您可以檢查站點住here如何在頁面上垂直居中div?

這是CSS:

iframe { 
position:fixed; 
width:100vw; 
height:100vh; 
border:none; 
margin:0; 
padding:0; 
overflow:hidden; 
z-index:999999; 
} 

body { 
background-color: #000; 
} 

#box { 
text-align: center; 
vertical-align: middle; 
} 

#link { 
color: #FFF; 
} 

#download { 
color: #FFF; 
} 
+0

http://stackoverflow.com/questions/13903556/centering-a-div-vertically-horizo​​ntally-using-jquery 類似的問題 – Krishna9960

+0

這是使用jQuery和我使用純CSS。我只想要css – TravelWhere

+0

分享HTML代碼以及 – Krishna9960

回答

5

方法1(位置,變換翻譯):

* { 
 
    padding: 0; 
 
    margin: 0; 
 
} 
 
.parrent { 
 
    position: relative; 
 
    left: 0; 
 
    top: 0; 
 
    width: 100vw; 
 
    height: 100vh; 
 
    background-color: gray; 
 
} 
 
.child { 
 
    position: absolute; 
 
    left: 50%; 
 
    top: 50%; 
 
    transform: translate(-50%, -50%); 
 
    width: 10em; 
 
    height: 5em; 
 
    background-color: white; 
 
    box-shadow: 1px 1px 10px rgba(0,0,0,.4); 
 
}
<div class="parrent"> 
 
    <div class="child"></div> 
 
</div>

方法2(Flexbox的):

* { 
 
    padding: 0; 
 
    margin: 0; 
 
} 
 

 
.parrent { 
 
    position: fixed; 
 
    left: 0; 
 
    top: 0; 
 
    width: 100vw; 
 
    height: 100vh; 
 
    background-color: gray; 
 
    display: flex; 
 
} 
 

 
.child { 
 
    margin: auto; 
 
    width: 10em; 
 
    height: 5em; 
 
    background-color: white; 
 
    box-shadow: 1px 1px 10px rgba(0, 0, 0, .4); 
 
}
<div class="parrent"> 
 
    <div class="child"></div> 
 
</div>

1

你可以做到這一點與flexboxes:

html,body { 
 
    height: 100%; 
 
    min-height: 100%; 
 
} 
 
.Aligner { 
 
    display: flex; 
 
    align-items: center; 
 
    justify-content: center; 
 
    height: 100%; 
 
    min-height: 100%; 
 
} 
 

 
.Aligner-item { 
 
    max-width: 50%; 
 
    background-color: red; 
 
}
<div class="Aligner"> 
 
    <div class="Aligner-item">…</div> 
 
</div>

0

添加一個包裝DIV;盒包裝的方式儘可能詳細的解釋

#box-wrapper { 
    position: relative; 
} 
#box { 
    position: absolute; 
    top: 50%; 
    left: 50%; 
    transform: translate(-50%, -50%); 
} 

可以css-tricks.com/centering-css-complete-guide

0
.parent { 
    text-align: center; 
    white-space: nowrap; 
}  
.parent:before { 
    content: ''; 
    display: inline-block; 
    height: 100%; 
    vertical-align: middle; 
    margin-right: -0.25em; 
} 
.child { 
    display: inline-block; 
    vertical-align: middle; 
    width: 300px; 
} 
0

HTML

<div class="container"><div class="your-div"></div></div> 

找到CSS

body, html{ 
    display:table; 
    height:100%; 
    width:100%; 
} 
.container{ 
    display:table-cell; 
    vertical-align:middle; 
} 
.container .your-div{ 
    width:150px; 
    height:150px; 
    background:green; 
    margin:0 auto; 
}