2016-07-15 37 views
0

我有一個問題,讓文本出現在屏幕中間(高度)在網頁上。該網站的HTML是:中央對齊的元素CSS沒有flexbox

<html lang="en"> 
    <head> 
     <title>example</title> 
     <link href="example.css" rel="stylesheet"> 
    </head> 

    <body>   
     <div class="home-container"> 
      <div class="home-row"> 
       <div class="some-other-class"> 
        <p>text that should be in the middle</p> 
       </div> 
      </div> 
     </div> 
    </body> 
</html> 

我想要做的是有家庭容器元一路延伸到頁面的底部,並有text that should be in the middle在它的中間。我css樣子:

html, body{ 
    height:100%; 
} 


.home-container{ 
    width: 100%; 
    height: 100%; 
    background-color: rgba(139,0,0,0.4); 
} 

.home-row{ 
    vertical-align: middle; 
} 

我明白,我想要做的是可能的,如果我反而讓home-container像這樣:

.home-container{ 
    width: 100%; 
    height: 100%; 
    background-color: rgba(139,0,0,0.4); 
    align-items: center; 
    display: flex; 
} 

但這並不對所有的瀏覽器。我在做什麼錯了vertical-align屬性?標識是不是真的做任何事情在我的例子...

+1

,以便能夠使用'垂直對齊'你需要在大容器(.home-container)上使用'display:table'和'.home-row'上的display:table-cell' –

+1

使用CSS表和定位屬性:http://stackoverflow.com/a/31977476/3597276 –

回答

2

使用vertical-align:middle.home-rowdisplay:table.home-container

看到這裏jsfiddle

代碼添加display:table-cell

.home-container{ 
width: 100%; 
height: 100%; 
background-color: rgba(139,0,0,0.4); 
display:table; 

} 

.home-row{ 
vertical-align: middle; 
display:table-cell; 
} 

垂直對齊 CSS屬性指定內聯或表格單元格的垂直對齊方式。

在這裏閱讀更多vertical align

+0

但我需要家容器來覆蓋所有的頁面... – 5xum

+0

是的,這個工程。謝謝!奇怪的是,因爲我沒有在任何地方看到垂直對齊只適用於表... – 5xum

+0

它也適用於內聯元素。欲瞭解更多信息,請閱讀https://developer.mozilla.org/en/docs/Web/CSS/vertical-align –

1

試試這個:

<style> 
    .home-container { 
     width: 100%; 
     height: 800px; 
     background-color: rgba(139, 0, 0, 0.4); 
     text-align: center; 
    } 

    .some-other-class { 
     position: relative; 
     top: 50%; 
     transform: translateY(-50%); 
    } 
</style> 

HTML

<div class="home-container"> 
    <div class="some-other-class"> 
     <p>text that should be in the middle</p> 
    </div> 
</div> 
1

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

 
.home-container{ 
 
    width: 100%; 
 
    height: 100%; 
 
    display: table; 
 
    text-align: center; 
 
    background-color: rgba(139,0,0,0.4); 
 
} 
 

 
.home-row{ 
 
    display: table-cell; 
 
    vertical-align: middle; 
 
}
<html lang="en"> 
 
    <head> 
 
    <title>example</title> 
 
    <link href="example.css" rel="stylesheet"> 
 
    </head> 
 
    <body>   
 
    <div class="home-container"> 
 
     <div class="home-row"> 
 
     <div class="some-other-class"> 
 
      <p>text that should be in the middle</p> 
 
     </div> 
 
     </div> 
 
    </div> 
 
    </body> 
 
</html>

+0

嗯,是的,這是有效的。非常感謝。 – 5xum

+0

@ 5xum歡迎您) –

+0

您的回答非常好,和Mihai T的一樣有用,但他的速度更快4分鐘,所以我會接受這個答案。希望你明白:) – 5xum