Why isn't “position:fixed;” keeping my page he

2019-08-26 17:11发布

问题:

This question already has an answer here:

  • css position fixed not working at all 5 answers

I'm trying to expand a menu when someone clicks on the menu icon but right now when I do that its pushing over the page title -- JSFiddle. I would like the page title to stay in the same place during the menu opening/closing interaction. The HTML5 I'm using to construct the page title and the menu are

#pageTitle {
  display: flex;
  padding: 10px;
  position: fixed;
}

ul.horizontal {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
}

li.menuItem {
  float: left;
}

li.menuItem a {
  display: block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}
<div id="pageTitle">
  <h2>Page Title</h2>

  <details class="mobile-nav">
    <summary class="menu-btn" id="menu-btn">
      <div></div>
      <span></span>
      <span></span>
      <span></span>
    </summary>

    <div class="responsive-menu">
      <ul id="menu">
        <li>Vote</li>
        <li>Search</li>
        <li>About</li>
      </ul>
    </div>
  </details>
</div>

I thought using position: fixed; would keep the page title where it was but it keeps getting pushed over.
How can I keep it from getting pushed over while allowing the menu opening/closing to happen?

回答1:

You need to use position:fixed in addition to left:0, right:0 and top:0. See below:

header {
  width: 100%;
  background-color: orange; 
  text-align: center;
  position:fixed;
  left:0;
  right:0;
  top:0;
}

Basically left:0, right:0 make the header take up the full viewport width, and top:0 positions it at the top of the page.

Here is a fiddle