Aligning elements left, center and right in flexbox

*爱你&永不变心* 提交于 2019-11-28 05:55:07

Use nested flex containers and flex-grow: 1.

This allows you to create three equal-width sections on the nav bar.

Then each section becomes a (nested) flex container which allows you to vertically and horizontally align the links using flex properties.

Now the left and right items are pinned to the edges of the container and the middle item is perfectly centered (even though the left and right items are different widths).

.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

Use justify-content: space-between; like this:

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

If you are open to changing your html, you need to put all the items in your header on the same level in the DOM.

Here's a working example

.nav {
  background: #e1e1e1;
  list-style: none;
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 60px;
}

.nav > div {
  min-width: 0;
  white-space: nowrap;
}

.header-title {
  flex-basis: 80%;
  text-align: center;
}

.nav div a {
  text-decoration: none;
  padding: 0px 20px;
  font-weight: 600;
}
<div class="nav mobilenav">

  <div><a href="/institutions/">Institutioner</a></div>

  <div><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>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!