【问题标题】:Centering the flex-element [duplicate]居中弹性元素[重复]
【发布时间】:2017-12-29 07:26:46
【问题描述】:

我有这样的布局

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

如何使用 flexbox 将 .title 放在块 .navbar 的中心?但同时,这样 .navbar-nav 就剩下了。

【问题讨论】:

  • 你试过text-align: center;margin: 0 auto;吗?
  • 调整内容:居中;
  • Ofc,但这些方法在这种情况下不起作用。
  • 要水平居中吗?
  • @DudinVadim 看看解决方案。

标签: html css flexbox


【解决方案1】:

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

.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;
}
<header class="navbar">
  <div class="navbar-nav">
  </div>
  <span class="title">Summary</span>
</header>

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

.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;
}
<header class="navbar">
  <div class="navbar-nav">
  </div>
  <span class="title">Summary</span>
</header>

When another content is present as well in the navbar.你可以利用绝对和相对位置变换标题的位置

.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%);
}
<header class="navbar">
  <div class="navbar-nav">
  </div>
  <span class="title">Summary</span>
</header>

【讨论】:

  • 但是在这种情况下 .navbar-nav 也是居中的,它必须保持在左侧。
  • @DudinVadim justify-content 不会影响导航栏,但会影响其中的子标签。或者您可以在子元素上使用 margin:0 auto 来居中。我更新了。
  • 对不起,忘记放 .navbar-nav 的代码 .navbar .navbar-nav { width: 360px;高度:100%;显示:弯曲;对齐项目:居中; justify-content: 之间的空格; }
  • @DudinVadim 然后更新它:)
  • 我更新了任务。 :)
猜你喜欢
  • 1970-01-01
  • 2023-04-02
  • 1970-01-01
  • 2012-07-01
  • 2019-04-24
  • 2015-02-15
  • 2016-07-21
  • 1970-01-01
  • 2019-02-11
相关资源
最近更新 更多