Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I'm trying to create this top header using flexbox.

header

Basically I would like to center the <div class="header-title"> (Institution institution 1) on the line with the 3 other elements you see. (Institutioner, Ledere and Log ud) like you see on the image.

.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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
389 views
Welcome To Ask or Share your Answers For Others

1 Answer

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...