如何使用 flexbox 将文本居中放置在 2 个 div 中

How to center text into 2 divs with flexbox

您好,我有两个由 flexbox 管理的,但我不明白如何将文本垂直对齐。

你可以在这里看到结果:https://www.w3schools.com/code/tryit.asp?filename=GKEFJJF780BU

您还可以在此处查看代码片段:

.barralanding {
  display: flex;
  flex-direction: row;
    
    /*width:100%;
    display:table;*/
}

.landing-foto {
  background-color: dodgerblue;
  flex: 50%;

    /*width:50%;
    display:table-cell;
    vertical-align:middle;
    background:   url("images/foto-land-dovedormire.jpg") no-repeat center;
    background-size: cover;*/
    height:420px;
}

.landing-testo {
  background-color: #369;
  flex: 50%;

    /*width:50%;
    display:table-cell;
    vertical-align:middle;
    background-color:#f0ca9c;*/
    background-color:#06C;
    
    padding:20px 30px 20px 30px;
    box-sizing:border-box;

}

.landing-testo h4{
    font: normal normal 1.9em 'Poppins', sans-serif;
    font-weight:800;
    color:white;
    text-align:left;
    background:   url("images/rigasottowth-h1.gif") no-repeat bottom left;
    padding-bottom:15px;
    margin:0px;
}
.landing-testo p{
    font: normal normal 1.0em 'Poppins', sans-serif;
    color:white;
    width:80%;
}
.landing-testo p.big{
    font: italic normal 1.2em 'Poppins', sans-serif;
    text-align:center;
}





/* Responsive layout - makes a one column-layout instead of two-column layout */
@media (max-width: 800px) {
  .barralanding {
    flex-direction: column;
  }
  
  .landing-foto {
    order: 1;
  }
  
}
<div class="barralanding">
  <div class="landing-foto">1 lkjh khs alkdjsh alkdh la laksjjhh alskjhv 2</div>
  <div class="landing-testo">2 dskf aksdhh alk alsdkhhadslkjfh slkjfh sslkfjjh dlfkjjhh adslkjh alksjkh alkjjh aadkljjhf ajk1</div>
  
</div>

您知道如何垂直对齐文本 - 至少 - 在一个 div 中吗?

非常感谢。

使用 flex,您可以创建一个 .center class 来居中您的内容:

.center {
  display: flex;
  align-items: center;
  justify-content: center;
}

不过如果能用grid就更简单了:

.center {
  display: grid;
  place-items: center;
}

要解决您的问题,您可以选择上述任一居中方法并将 HTML 更改为:

<div class="barralanding">
  <div class="landing-foto center">
    1 lkjh khs alkdjsh alkdh la laksjjhh alskjhv 2
  </div>
  <div class="landing-testo center">
    2 dskf aksdhh alk alsdkhhadslkjfh slkjfh sslkfjjh dlfkjjhh adslkjh
    alksjkh alkjjh aadkljjhf ajk1
  </div>
</div>

.center {
  display: grid;
  place-items: center;
}

.barralanding {
  display: flex;
  flex-direction: row;
}

.landing-foto {
  background-color: dodgerblue;
  flex: 50%;
  height: 420px;
}

.landing-testo {
  background-color: #369;
  flex: 50%;
  background-color: #06c;
  padding: 20px 30px 20px 30px;
  box-sizing: border-box;
}
<div class="barralanding">
  <div class="landing-foto center">
    1 lkjh khs alkdjsh alkdh la laksjjhh alskjhv 2
  </div>
  <div class="landing-testo center">
    2 dskf aksdhh alk alsdkhhadslkjfh slkjfh sslkfjjh dlfkjjhh adslkjh alksjkh alkjjh aadkljjhf ajk1
  </div>
</div>