没有 flexbox 的元素 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>

我想要做的是让 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;
}

我明白,如果我改为制作 home-container ,我想做的事情是可能的:

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

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

原文由 5xum 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 283
2 个回答

to use vertical-align:middle add display:table-cell on .home-row and display:table on .home-container

看这里 jsfiddle 或片段

 html,
body {
  height: 100%;
}

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

.home-container {
  width: 100%;
  height: 100%;

  background-color: rgba(139, 0, 0, 0.4);
  display: table;

}
 <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>

vertical-align CSS 属性指定行内或表格单元框的垂直对齐方式。

在这里阅读更多 垂直对齐

编辑 2020 有一种更好的方法可以使用 flexbox

检查下面的片段

玩玩 flexbox 。您可以将它添加到其他项目而不仅仅是容器

 .home-container {
  background: red;
  display:flex;
  flex-direction: column;
  justify-content: center;
  height:100vh;
 }
 <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>

原文由 Mihai T 发布,翻译遵循 CC BY-SA 4.0 许可协议

试试这个:

  <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>

原文由 Pranjal 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏