均匀分配孩子,但使父母与flex右对齐

时间:2019-02-19 10:24:30

标签: html css css3 flexbox alignment

我有以下代码来设置菜单。想法是使菜单项在水平方向上均匀分布,但在有多余空间时不要将它们间隔太远。如果有多余的空间,则菜单现在会向左对齐(绿色朝向黄色的左侧)。

目标是使菜单与右侧对齐。如何实现?

.wrapper {
  display: flex;
  height: 5em;
}
.left {
  flex: 1;
  display: flex;
}
.middle {
  flex: 4;
  background: #ffc;
  display: flex!important; /* this comes from the library i'm using */
}
ul {
  display: flex;
  max-width: 200px;
}
li {
  list-style: none;
  flex: 1;
  background: #cfc;
  text-align: center;
}
.right {
  flex: 1;
}
<div class="wrapper">
  <div class="left">
    <div class="tagline">Left</div>
  </div>
  <div class="middle">
    <ul>
      <li>menu item</li>
      <li>menu item</li>
      <li>menu item</li>
      <li>menu item</li>
    </ul>
  </div>
  <div class="right">
    right
  </div>
</div>

2 个答案:

答案 0 :(得分:1)

对齐右侧的菜单项,我们可以在margin-left: auto上放置ul。也许您也想将padding默认 ul设置为零。

请参见下面的演示

.wrapper {
  display: flex;
  height: 5em;
}
.left {
  flex: 1;
  display: flex;
}
.middle {
  flex: 4;
  background: #ffc;
  display: flex!important; /* this comes from the library i'm using */
}
ul {
  display: flex;
  max-width: 200px;
  margin-left: auto; /* ADDED */
  padding: 0; /* ADDED */
}
li {
  list-style: none;
  flex: 1;
  background: #cfc;
  text-align: center;
}
.right {
  flex: 1;
}
<div class="wrapper">
  <div class="left">
    <div class="tagline">Left</div>
  </div>
  <div class="middle">
    <ul>
      <li>menu item</li>
      <li>menu item</li>
      <li>menu item</li>
      <li>menu item</li>
    </ul>
  </div>
  <div class="right">
    right
  </div>
</div>

答案 1 :(得分:0)

这是你想要的吗?

.wrapper {
  display: flex;
  height: 5em;
}
.left {
  flex: 1;
  display: flex;
}
.middle {
  flex: 4;
  background: #ffc;
  display: flex!important; /* this comes from the library i'm using */
}
ul {
     display: flex;
    width: 100%;
    padding: 0;
    justify-content: flex-start;
}
li {
  list-style: none;
  flex: 1;
  background: #cfc;
  text-align: center;
}
.right {
  flex: 1;
}
<div class="wrapper">
  <div class="left">
    <div class="tagline">Left</div>
  </div>
  <div class="middle">
    <ul>
      <li>menu item</li>
      <li>menu item</li>
      <li>menu item</li>
      <li>menu item</li>
    </ul>
  </div>
  <div class="right">
    right
  </div>
</div>