2015-06-22 106 views
0

如何使用CSS在div內水平居中div?我正在嘗試,我得到它從左側和右側居中,但我不能從頂部和底部居中。CSS居中DIV包含其他DIV

 html { 
     height:100%; 
    } 
    body { 
     padding:0px; 
     margin: 0px; 
     height:100%; 
    } 
    #openFrame { 
     position:fixed; 
     top:0px; 
     width:100%; 
     left:0%; 
     height:100%; 
    } 
    .main { 
     position: absolute; 
     width: 80%; 
     max-height: 100%; 
     top: 0; 
     left: 0; 
     right: 0; 
     bottom: 0; 
     margin: auto; 
    } 
    #vid { 
     width:100%; 
     max-height:100%; 
     vertical-align: middle; 
    } 
    #bottom { 
     width:100%; 
     height:69px; 
     background-color: green; 
     background-repeat: no-repeat; 
     background-position: top center; 
     background-size: contain; 
    } 
+3

可能重複[如何垂直居中一個div所有的瀏覽器?(http://stackoverflow.com/questions/396145/how-to-vertically-center-a-div -for-all-browsers) –

+0

https://jsfiddle.net/ozgul/epm4y8jy/請參閱預覽 – Blair

回答

0

垂直居中DIV是有點麻煩。基本上你必須將其設置爲positionabsolute和容器的positionrelative。然後,將topleft值設置爲50%,並通過應用負邊距減去要居中的元素的寬度/高度的一半。

Codepen example

<!DOCTYPE html> 
    <head> 
     <meta charset="utf-8"> 
     <meta http-equiv="X-UA-Compatible" content="IE=edge"> 
     <title></title> 
     <meta name="description" content=""> 
     <meta name="viewport" content="width=device-width, initial-scale=1"> 

     <style type="text/css"> 
     body, html, #container { 
      height: 100%; 
      width: 100%; 
     } 
     #container { 
      position: relative; 
     } 
     #content { 
      width: 300px; 
      height: 300px; 
      position: absolute; 
      top: 50%; 
      left: 50%; 
      margin-top: -150px; 
      margin-left: -150px; 
      background-color: red; 
     } 
     </style> 
    </head> 
    <body> 
     <div id="container"> 
      <div id="content"></div> 
     </div> 
    </body> 
</html> 
+0

謝謝你,但仍然沒有得到任何地方 – Blair

+0

也許說爲什麼?這樣,沒有人能夠幫助你。我檢查了你的jsfiddle,並且存在很多問題。另外,它看起來不像你嘗試的解決方案。請嘗試解決方案,並創建一個jsfiddle然後張貼它,這樣我可以檢查什麼是錯的。另一件事:當你做絕對定位時,將0px分配給頂部和底部是沒有意義的。這意味着它從頂部是0px,從底部是0px,這是不可能的。在這裏看到更多:http://www.w3schools.com/css/css_positioning.asp –

+0

你必須做一些工作。這是一個回答問題的網站,而不是其他人爲你寫代碼的地方。 –