在flexbox标题中使用空元素

时间:2018-04-20 18:40:50

标签: html css css3 flexbox

编辑因为不清楚而编辑 - 我试图让nav元素增长,但不要太多,并且使导航项空间均匀。

当我创建一个标题时,我经常使用一个空div,以便在调整大小时帮助水平对齐,方法是为其赋予弹性增长权重。

我确信这不是它应该做的方式,而且可能只是缺乏flexbox知识,所以我希望有人可以看看我的标题并推荐正确的方法。

以下是我想要实现的调整大小: https://codepen.io/anon/pen/LmVrvm

由于

<div class="container">
  <div class="item logo">LOGO</div>
  <div class="item empty-item"></div>
  <div class="item nav">
    <div class="item item1">MENU ITEM 1</div>
    <div class=" item item2">MENU ITEM 2</div>
    <div class="item item3">MENU ITEM 3</div>
  </div>
</div>

-

.container{
  display: flex;
  width: 100%;
  height: 70px;
  background: #5e5e5e;

  align-items: center;
}

.logo{
  width: 200px;
  text-align: center;
}

.empty-item{
  flex-grow: 2;
}

.nav{
  flex-grow: 1;

  display: flex;
  justify-content: space-between;
}

.item{
  margin: 5px;
  padding: 5px;
  border: 1px solid #fff;
}

2 个答案:

答案 0 :(得分:1)

您不需要那个空div来使nav响应。

您可以使用的方法之一是flex-basis: num%并将justify-content: space-between添加到父容器。

检查我的代码:

.container {
  display: flex;
  width: 100%;
  height: 70px;
  background: #5e5e5e;
  justify-content: space-between;
  align-items: center;
}

.logo {
  width: 200px;
  text-align: center;
}

.empty-item {}

.nav {
  display: flex;
  justify-content: space-between;
  flex-basis: 45%;
}

.item {
  margin: 5px;
  padding: 5px;
  border: 1px solid #fff;
}
<div class="container">
  <div class="item logo">LOGO</div>
  <div class="item nav">
    <div class="item item1">MENU ITEM 1</div>
    <div class=" item item2">MENU ITEM 2</div>
    <div class="item item3">MENU ITEM 3</div>
  </div>
</div>

答案 1 :(得分:0)

我在这里更新了您的codepen: https://codepen.io/platypusjones/pen/xjGJoe

我删除了无关的元素,但重要的是删除flex-grow并添加margin-left并显示inline-block,这将允许它自然浮动。

.nav{
  display: flex;
  justify-content: space-between;
  margin-left:auto;
  display: inline-block;
}