如何定位:使用flexbox时固定导航栏

时间:2016-11-23 19:38:07

标签: css flexbox

从这个布局开始: http://codepen.io/RebelOne/pen/wodbpR

.navbar {
  display: flex;
  justify-content: space-between;

当我添加位置:固定到导航栏时,它会向下折叠并且不会填充包装器的宽度。有谁知道如何解决这一问题? http://codepen.io/RebelOne/pen/bBWyLZ?editors=1100

.navbar {
  display: flex;
  justify-content: space-between;
  background-color: yellow;
  position: fixed;
  top: 0;
  z-index: 99;
  }

4 个答案:

答案 0 :(得分:6)

显示:弹性和位置:固定不合适。

你可以做一些改变,看起来像这样

检查以下代码段



/* Clear formatting*/

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
/* Remove formatting from links*/

a {
  color: inherit;
  text-decoration: none;
}
/* Set a max width to the content*/

.wrapper {
  max-width: 960px;
  margin: 0 auto;
  background-color: pink;
  display: flex;
  flex-direction: column;
  /*height: 100vh;  */
}
.parent {
  position: fixed;
  top: 0;
  left: 0;
  margin: auto;
  width: 100%;
}
.navbar {
  display: flex;
  justify-content: space-between;
  background-color: yellow;
  /*   */
}
.logo {
  padding: 20px;
}
.menu {
  display: flex;
  align-items: center;
}
.menu ul {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  list-style: none;
  background-color: grey;
}
.menu li {
  padding: 20px;
  margin-left: 20px;
  background-color: orange;
  color: rgba(255, 0, 0, 0.9);
  font-size: 16px;
  font-weight: bold;
}

<div class="parent">
  <div class="navbar">
    <div class="logo">
      <picture>
        <img src="http://fillmurray.com/50/50" alt="logo">
      </picture>
    </div>
    <div class="menu">
      <ul>
        <li><a href="#home">Home</a>
        </li>
        <li><a href="#about">About</a>
        </li>
        <li><a href="#contact">Contact</a>
        </li>
      </ul>
    </div>
  </div>
</div>

<div class="wrapper">
  <div style="height: 2000px"></div>
</div>
&#13;
&#13;
&#13;

希望有所帮助

答案 1 :(得分:1)

在导航栏类中添加以下css属性

    .navbar {
  display: flex;
  justify-content: space-between;
  background-color: yellow;
  position: sticky;
  top: 0;
  z-index: 100;
  }

答案 2 :(得分:0)

只需使用

.navbar {<br/>
display: flex;<br/>
    position: fixed;
    top: 0;<br/>
    left: 0;<br/>
    right: 0;<br/>
    justify-content: space-between;<br/>
    z-index: 200;<br/>
    background-color: white;<br/>
}

答案 3 :(得分:0)

在使用 flex 时,重要的是将父包装器 div 放在标题中,然后将其写入包装器中,如果您希望标题保持固定

.wrapper{
    position: fixed;
    width: 100%;
    top: 0;
    z-index: 1;
}