2016-07-15 38 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