没有Flexbox的CSS元素的中央对齐

5xu*_*xum 4 html css

我遇到了使文本显示在网页中间(高度方向)的问题。该网站的HTML是:

<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>
Run Code Online (Sandbox Code Playgroud)

我想做的是让home-container元素一直延伸到页面底部,并在页面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;
}
Run Code Online (Sandbox Code Playgroud)

我知道,如果我做home-container这样的话,我想做的事情是可能的:

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

但这不适用于所有浏览器。我在做错什么vertical-align物业?在我的示例中,Id并没有真正做任何事情...

Pra*_*jal 7

尝试这个:

 <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>
Run Code Online (Sandbox Code Playgroud)

HTML

<div class="home-container">
    <div class="some-other-class">
        <p>text that should be in the middle</p>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)


Moh*_*man 7

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;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)


Mih*_*i T 5

在使用vertical-align:middle添加display:table-cell.home-rowdisplay:table.home-container

看到这里jsfiddle

代码:

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

}

.home-row{
vertical-align: middle;
display:table-cell;
}
Run Code Online (Sandbox Code Playgroud)

垂直对齐 CSS属性指定内嵌或表格盒的垂直对准。

在此处了解更多信息垂直对齐