使柔性元件居中

时间:2017-12-15 09:53:15

标签: html css css3 flexbox

我有这样的布局



.navbar {
  width: 100%;
  height: 64px;
  background: #0d1717;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.navbar .navbar-nav {
  width: 360px;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.navbar .title {
  color: #fff;
  font-size: 32px;
  font-family: Fairview;
  color: #fcfcfc;
}

<header class="navbar">
  <div class="navbar-nav">
    <!-- content -->      
  </div>
  <span class="title">Summary</span>
</header>
&#13;
&#13;
&#13;

如何将.title放在带有flexbox的块.navbar的中心?但与此同时,只剩下.navbar-nav。

1 个答案:

答案 0 :(得分:2)

您可以使用justify-content:center对齐内容用于align items horizontally,而align-items用于垂直对齐。

&#13;
&#13;
.navbar {
  width: 100%;
  height: 64px;
  background: #0d1717;
  display: flex;
  align-items: center;
  justify-content: center;
}

.navbar .title {
  color: #fff;
  font-size: 32px;
  font-family: Fairview;
  color: #fcfcfc;
}
&#13;
<header class="navbar">
  <div class="navbar-nav">
  </div>
  <span class="title">Summary</span>
</header>
&#13;
&#13;
&#13;

在子元素上使用margin:auto进行水平对齐:

&#13;
&#13;
.navbar {
  width: 100%;
  height: 64px;
  background: #0d1717;
  display: flex;
  align-items: center;
}

.navbar .title {
  color: #fff;
  font-size: 32px;
  font-family: Fairview;
  color: #fcfcfc;
  margin:0 auto;
}
&#13;
<header class="navbar">
  <div class="navbar-nav">
  </div>
  <span class="title">Summary</span>
</header>
&#13;
&#13;
&#13;

When another content is present as well in the navbar.您可以使用绝对和相对位置并转换标题的位置

&#13;
&#13;
.navbar {
  width: 100%;
  height: 64px;
  background: #0d1717;
  display: flex;
  align-items: center;
  position:relative;
  color:white;
}

.navbar .navbar-nav {
  width: 360px;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.navbar .title {
  position:absolute;
  color: #fff;
  font-size: 32px;
  font-family: Fairview;
  color: #fcfcfc;
  left:50%;
  transform:translateX(-50%);
}
&#13;
<header class="navbar">
  <div class="navbar-nav">
  </div>
  <span class="title">Summary</span>
</header>
&#13;
&#13;
&#13;