在Flexbox中将元素左,中和右对齐 [英] Aligning elements left, center and right in flexbox

查看:80
本文介绍了在Flexbox中将元素左,中和右对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用flexbox创建此顶部标头.

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

基本上,我想将<div class="header-title">(机构机构1)与您看到的其他3个元素居中对齐. (Institutioner,Ledere and Log ud),就像您在图片上看到的一样.

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>

演示-JSFiddle

推荐答案

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

Use nested flex containers and flex-grow: 1.

这使您可以在导航栏上创建三个等宽部分.

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

然后每个部分都变成一个(嵌套的)flex容器,使您可以使用flex属性在垂直和水平方向上对齐链接.

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>

这篇关于在Flexbox中将元素左,中和右对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆