【问题标题】:How to position: fixed the navbar when using flexbox如何定位:修复了使用 flexbox 时的导航栏
【发布时间】:2017-04-07 22:58:17
【问题描述】:

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

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

当我将 position:fixed 添加到导航栏时,它会向下折叠并且不会填充包装器的宽度。有谁知道如何解决这一问题? 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;
  }

【问题讨论】:

  • display:flex 和 position 不匹配...您想要修复导航栏吗?
  • 对你有帮助吗?......

标签: css flexbox


【解决方案1】:

Display:flex 和 position:fixed 不能很好地结合在一起。

你可以做些小改动,让它看起来像这样

检查以下sn-p

/* 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>

希望对你有帮助

【讨论】:

【解决方案2】:

简单地使用

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

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      【解决方案4】:

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

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

      【讨论】:

        猜你喜欢
        • 2017-03-30
        • 2013-12-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多