如何在嵌套div中对齐h2?

时间:2019-03-22 19:46:37

标签: html css vertical-alignment

我正在尝试在h2元素内对齐文本。我希望它在div中垂直居中。我正在.NET MVC中工作

我的html :(这是给我麻烦的唯一部分) 具体来说:

.banner-side-container {
  height: 240px;
  width: 180px;
  vertical-align: middle;
}

.banner-side-container h2 {
  margin: 0;
  padding: 0;
  text-align: center;
}

.view-teams-banner {
  margin-top: 10px;
  height: 110px;
  width: 180px;
  background-color: aqua;
  border-radius: 20px;
}

.view-matches-banner {
  margin-top: 10px;
  height: 110px;
  width: 180px;
  background-color: darkorchid;
  border-radius: 20px;
}
<td>
  <div class="banner-side-container">
    <div class="view-teams-banner">
      <h2>View Teams</h2>
    </div>
    <div class="view-matches-banner">
      <h2>View Matches</h2>
    </div>
  </div>
</td>

我尝试添加vertical-align:middle;到所有4个选择器都没有成功。 进一步的信息:text-align:center;工作完美。

1 个答案:

答案 0 :(得分:0)

您可以使用flex并将以下设置添加到包裹h2和它们的父元素的三个元素中,如下所示:

display: flex;
flex-direction: column;
justify-content: center;

.banner-side-container {
  height: 240px;
  width: 180px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.banner-side-container h2 {
  margin: 0;
  padding: 0;
  text-align: center;
}

.view-teams-banner {
  margin-top: 10px;
  height: 110px;
  width: 180px;
  background-color: aqua;
  border-radius: 20px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.view-matches-banner {
  margin-top: 10px;
  height: 110px;
  width: 180px;
  background-color: darkorchid;
  border-radius: 20px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}
<td>
  <div class="banner-side-container">
    <div class="view-teams-banner">
      <h2>View Teams</h2>
    </div>
    <div class="view-matches-banner">
      <h2>View Matches</h2>
    </div>
  </div>
</td>