在 flex 项目中,将内容垂直和水平居中

3

我希望能够在flex项目内水平垂直居中文本。我已经到处寻找并尝试了很多方法,但目前为止似乎没有任何有效的解决方案...

我是否可以在现有的flex容器内再嵌套一个flex容器?

html, body {
  height: 100%;
  margin: 0;
}
.flex-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.page1 {
  flex-grow: 1;
  min-height: 100%;
  background: lightblue;
}
#text1 {
  font-size: 160%;
  color: white;
  font-family: roboto, sans-serif;
}
.page2 {
  flex-grow: 1;
  min-height: 100%;
  background: cyan;
}
.page3 {
  flex-grow: 1;
  min-height: 100%;
  background: lightgreen;
}
.page3 {
  flex-grow: 1;
  min-height: 100%;
  background: lightgreen;
}
<div class="flex-container">
  <div class="page1">
    <p id="text1">blabla bla blablabla.</p>
  </div>
  <div class="page2"></div>
  <div class="page3"></div>
</div>


1
是的,您可以嵌套Flex容器。https://dev59.com/bGMk5IYBdhLWcg3wtgMR#33049198 - Michael Benjamin
1个回答

3

把 flex-items 也变成 flex-containers,像下面这样。我还给 #text1 添加了 margin: auto 居中。

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

.flex-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.page1 {
  display: flex;
  flex-direction: column;
  flex-grow: 1;
  min-height: 100%;
  background: lightblue;
}

#text1 {
  margin: auto;
  font-size: 160%;
  color: white;
  font-family: roboto, sans-serif;
}

.page2 {
  flex-grow: 1;
  min-height: 100%;
  background: cyan;
}

.page3 {
  flex-grow: 1;
  min-height: 100%;
  background: lightgreen;
}

.page3 {
  flex-grow: 1;
  min-height: 100%;
  background: lightgreen;
}
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title> Portfolio </title>
    <link rel="stylesheet" type="text/css" href="style.css">
  </head>

  <body>

    <div class="flex-container">

      <div class="page1">
        <p id="text1"> blabla bla blablabla. </p>
      </div>


      <div class="page2">

      </div>

      <div class="page3">

      </div>

    </div>



  </body>
</html>


谢谢你的帮助,伙计。解决方案非常简单,但我就是想不出来...#我需要休息 - Unknown User

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接