在 flexbox 中左、中、右对齐元素

新手上路,请多包涵

我正在尝试使用 flexbox 创建这个顶部标题。

标头

基本上,我想将 <div class="header-title"> (Institution institution 1)与您看到的其他 3 个元素放在一起。 (Institutioner、Ledere 和 Log ud)就像您在图片上看到的那样。

 .nav {
    background: #e1e1e1;
}
ol, ul {
    list-style: none;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-start;
}
.header-title {
  justify-content: center;
    align-self: center;
    display: flex;
}
.nav ul li.logout {
      margin-left: auto;
}
.nav ul li a {
    text-decoration: none;
    padding: 0px 20px;
    font-weight: 600;
}
 <div class="nav mobilenav">
  <div class="header-title">
    Institution institution 1
  </div>
  <ul>
    <li><a href="/institutions/">Institutioner</a></li>
    <li>
      <a href="/leaders/">Ledere</a>
    </li>
    <li class="logout">
      <a class="button-dark" href="/user/logout">Log ud</a>
    </li>
  </ul>
</div>

演示 - JSFiddle

原文由 Dave Mikes 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 249
2 个回答

使用嵌套的弹性容器和 flex-grow: 1

这允许您在导航栏上创建三个等宽的部分。

然后每个部分成为一个(嵌套的)弹性容器,它允许您使用弹性属性垂直和水平对齐链接。

现在左右项目被固定到容器的边缘,中间项目完全居中(即使左右项目的宽度不同)。

 .nav {
  display: flex;
  height: 50px;      /* optional; just for demo */
  background: white;
}

.links {
  flex: 1;          /* shorthand for: flex-grow: 1, flex-shrink: 1, flex-basis: 0 */
  display: flex;
  justify-content: flex-start;
  align-items: center;
  border: 1px dashed red;
}

.header-title {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px dashed red;
}

.logout {
  flex: 1;
  display: flex;
  justify-content: flex-end;
  align-items: center;
  border: 1px dashed red;
}

.links a {
  margin: 0 5px;
  text-decoration: none;
}
 <div class="nav mobilenav">

  <div class="links">
    <a href="/institutions/">Institutioner</a>
    <a href="/leaders/">Ledere</a>
  </div>

  <div class="header-title">Institution institution 1</div>

  <div class="logout"><a class="button-dark" href="/user/logout">Log ud</a></div>

</div>

jsFiddle

原文由 Michael Benjamin 发布,翻译遵循 CC BY-SA 3.0 许可协议

使用 justify-content: space-between; 像这样:

 .container {
  display: flex;
  justify-content: space-between;
}
 <div class="container">
  <div>A</div>
  <div>B</div>
  <div>C</div>
</div>

原文由 Fellow Stranger 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题