Search code examples
javascriptscrollmenunavbarfixed

I want to turn my menu fixed on top


My menu is hidden/show, but I want to keep it on the top of the page when I scroll.

The HTML:

<div class="menu">
    <ul>
        <a href="#home"><li>Home</li></a>
        <a href="#about"><li>About</li></a>
        <a href="#servicces"><li>Services</li></a>
        <a href="#projects"><li>Work</li></a>
        <a href="#contact"><li>Contact</li></a>
    </ul>
</div>
<div class="menu-toggle">
    <a href="#"><i class="fa fa-angle-double-down"></i></a>
</div>

The CSS:

.menu {
  display:none;
    width:100%;
  background:#fcfcfc;
}
.menu ul {
    font-family: 'Raleway', serif;
  font-weight:300;
  height:110%;
    list-style:none;
    margin:0;
    padding:10px;
    text-align:center;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  justify-content: space-around;
}
.menu ul li {
    color:#333;
    font-size:12px;
    letter-spacing:2px;
    padding:15px 0;
  padding-left:5px;
  padding-right:5px;
    text-transform:uppercase;
  transition:all .3s ease-in-out;
}
.menu ul li:hover {
  text-align:center;
    background:rgba(90,221,184,.6);
  color:#fff;
  font-weight:bold;
  transition:all .3s ease-in-out;
}
.menu a {
  text-decoration:none;
    color: #333;
}
.menu-toggle {
    background:none;
  color: #333;
    width:100%;
    text-align:center;
    padding:10px 0;
    font-size:25px;
}
.menu-toggle a {
    text-decoration:none;
    color: #333;
}
.fa-angle-double-down{
  color:#fcfcfc;
  transition:all .3s ease-in-out;
}
.fa-angle-double-down:hover{
  color:#5ADDB8;
  transition:all .2s ease-in-out;
  -ms-transform: rotate(180deg); /* IE 9 */
    -webkit-transform: rotate(180deg); /* Chrome, Safari, Opera */
    transform: rotate(180deg);
}

And the JS:

$(document).ready(function(){
    $(".menu-toggle a").click(function(){ 
        $(".menu").slideToggle(700);
    });
});

I'd like to get the arrow on top, and when it is clicked, it moves down and gets the menu on the top, after closing the menu, the arrow back to its initial place.

Visit the menu codepen: HERE

Visit my page trying: HERE


Solution

  • Add the following in the menu css:

        position:fixed;
        top:0;
    

    And add the following in your arrow css:

        position:relative;
    

    That should do what you are thinking to do.

    Edit:

    .menu-container{
      position: fixed;
      top:0;
    }
    .menu{
       display: block;
       position: relative;
    }
    .menu-toggle{
       margin:0 auto;
       position:relative;
    }