Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
393 views
in Technique[技术] by (71.8m points)

html - Aligning elements left, center and right in flexbox

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

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

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...