The menu is fixed when scrolling and stretches. How can I lock a layer so it stays in one place when scrolling the page? How to make a bottom fixed menu

When creating a website, there is often a need to keep in view the horizontal menu, which contains the main navigation of the site. The method of “fixing” the horizontal menu is convenient from the point of view of the visitor, who “has navigation always at hand”, no matter how much you turn the wheel down or up.

Fixing the horizontal menu with CSS: position:fixed

On the one hand, everything is simple and easy to solve using CSS in no time. Example of HTML layout of a fixed horizontal menu:

  • home
  • News
  • Contacts
  • Search
[page content] [site footer]

CSS layout of a fixed horizontal menu:

# menu-top-almost-fixed( position: fixed; top: 10px; left: 0; height: 30px; width: 100%; margin: 0; )

Now let’s set the indentation for the page content equal to the height of the menu:

#content ( margin-top: 30px; )

And now we have “almost” succeeded. The menu is always visible to the visitor. But what should we do if we have a site header in our design, followed by the menu itself, and in the header we have a logo, site motto, and banners.

Well, we can fix the site header by making the content indentation equal in height to the header and menu, along with the indentation between them. But a problem arises. We significantly limit the viewing space for our visitors to view page content. The option to abandon the cap does not suit us at all.

Fixing a horizontal menu using javascript

So, let's consider the option when the menu “goes” behind the site header, but if the visitor actively scrolls down, the menu is “fixed” at the top and remains in place. The site header is not visible. If the visitor returns to the page header, the menu “becomes” in its place “behind the site header”. To begin with, here is the complete HTML layout of an example page layout:

Website logo Website slogan Banner

  • home
  • News
  • Contacts
  • Search
[page content] [site footer]

Our website template consists of several typical areas:

  • site headers – #header, height 150px
  • horizontal menu – #menu-top-almost-fixed– height 30px,
  • main information area of ​​the page – #content,
  • site footer - #footer.

Here's the CSS layout:

#menu-top-almost-fixed( position: fixed; margin: 0; left: 0; top: 150px; height: 30px; ) #header( display: block; height: 150px; overflow: hidden; position: relative; margin -bottom: 55px; ) #menu-top-almost-fixed ul, #menu-top-almost-fixed li( list-style: none; margin: 0; padding: 0; ) #menu-top-almost-fixed ul ( display: block; text-align: center; width: 100%; float: left; ) #menu-top-almost-fixed ul li( display: inline; line-height: 30px; width: 120px; padding: 0 5px ; text-align: center ;

First, let's set an indent from the header to the content equal to the height of our menu + a small indent with a margin for aesthetic beauty. #header ( margin-bottom: 55px; ) . Let's fix our menu right behind the header: #menu-top-almost-fixed( position: fixed; margin: 0; left: 0; top: 150px; height: 30px; ) .

Now let’s make sure that when scrolling, the menu “fixes” exactly at the top of the page. Let's put the following javascript between and :

Javascript:

var m1 = 150; /* header height in pixels */ var m2 = 2; /* indentation when the header is no longer visible during scrolling */ var menuID = "menu-top-almost-fixed"; /* id of the horizontal menu to pin */ var menuOpacityOnChange = "0.7"; /* menu transparency when scrolling: 1 - opaque, 0.5 - translucent 0.0 - completely transparent */ var menuOpacityOnChangeIE = menuOpacityOnChange * 100; /* function for cross-browser determination of the indent from the top of the document to the current position of the scroll scroller */ function getScrollTop() ( var scrOfY = 0; if(typeof(window.pageYOffset) == "number") ( //Netscape compliant scrOfY = window.pageYOffset ; ) else if(document.body && (document.body.scrollLeft || document.body.scrollTop)) ( //DOM compliant scrOfY = document.body.scrollTop; ) else if(document.documentElement && (document.documentElement. scrollLeft || document.documentElement.scrollTop)) ( //IE6 Strict scrOfY = document.documentElement.scrollTop; ) return scrOfY ) /* function that sets the top padding for a "floating" fixed horizontal menu depending on the scroller position and visibility headers */ function marginMenuTop() ( var top = getScrollTop(); var s = document.getElementById(menuID); if(typeof s != "undefined" && s)( if (top+m2< m1) { s.style.top = (m1-top) + "px"; s.style.filter = s.style.filter.replace("progid:DXImageTransform.Microsoft.Alpha(opacity="+menuOpacityOnChangeIE+")",""); s.style.opacity = "1"; } else { s.style.top = m2 + "px"; s.style.opacity = menuOpacityOnChange; s.style.filter = s.style.filter.replace("progid:DXImageTransform.Microsoft.Alpha(opacity="+menuOpacityOnChangeIE+")",""); s.style.filter += "progid:DXImageTransform.Microsoft.Alpha(opacity="+menuOpacityOnChangeIE+")"; } } } /** функция регистрирует вычисление позиции «плавающего» меню при прокрутке страницы **/ function setMenuPosition(){ if(typeof window.addEventListener != "undefined"){ window.addEventListener("scroll", marginMenuTop, false); } else if(typeof window.attachEvent != "undefined"){ window. attachEvent("onscroll", marginMenuTop); } marginMenuTop(); } /** регистрируем вызов необходимых функций после загрузки страницы **/ if(typeof window.addEventListener != "undefined"){ window.addEventListener("load", setMenuPosition, false); } else if(typeof window.attachEvent != "undefined"){ window. attachEvent("onload", setMenuPosition); }

You can see an example of the implementation by following this link and using the scroll wheel. So, everything is simple here. In the settings we pass the following parameters to the script:

  • var m1 = 150;
  • var m2 = 2;
  • - indentation when the header is no longer visible while scrolling,
  • var menuID = “menu-top-almost-fixed”;
    • - id of the horizontal menu to pin,
    • var menuOpacityOnChange = “0.7”; - menu transparency when scrolling:
    • 1 - opaque

0.5 – translucent

0.0 - completely transparent

In this version, we have “tuned” our menu a little, and when scrolling we add translucency to it. A more classic option immediately suggests itself, when we do not change the transparency of the menu, but simply make a background for the menu in the form of a background with the menu color and a lower translucent border (in which the gradient smoothly “transitions” from an opaque color to a transparent one):

Let's change a little CSS layout for our horizontal fixed menu:

Javascript:

#menu-top-almost-fixed( position: fixed; margin: 0; left: 0; top: 150px; height: 30px; background: url(./images/white-gradient-l.png) bottom left repeat-x ; )< m1) { s.style.top = (m1-top) + "px"; } else { s.style.top = m2 + "px"; } } } /** функция регистрирует вычисление позиции «плавающего» меню при прокрутке страницы **/ function setMenuPosition(){ if(typeof window.addEventListener != "undefined"){ window.addEventListener("scroll", marginMenuTop, false); } else if(typeof window.attachEvent != "undefined"){ window. attachEvent("onscroll", marginMenuTop); } } /** регистрируем вызов необходимых функций после загрузки страницы **/ if(typeof window.addEventListener != "undefined"){ window.addEventListener("load", setMenuPosition, false); } else if(typeof window.attachEvent != "undefined"){ window. attachEvent("onload", setMenuPosition); }

Now let’s give the modified javascript code, which we will place between and :

  • var m1 = 150;
  • var m1 = 150; /* header height in pixels */ var m2 = 0; /* indentation when the header is no longer visible during scrolling */ var menuID = "menu-top-almost-fixed"; /* function for cross-browser determination of the indent from the top of the document to the current position of the scroll scroller */ function getScrollTop() ( var scrOfY = 0; if(typeof(window.pageYOffset) == "number") ( //Netscape compliant scrOfY = window.pageYOffset ; ) else if(document.body && (document.body.scrollLeft || document.body.scrollTop)) ( //DOM compliant scrOfY = document.body.scrollTop; ) else if(document.documentElement && (document.documentElement. scrollLeft || document.documentElement.scrollTop)) ( //IE6 Strict scrOfY = document.documentElement.scrollTop; ) return scrOfY ) /* function that sets the top padding for a "floating" fixed horizontal menu depending on the scroller position and visibility headers */ function marginMenuTop() ( var top = getScrollTop(); var s = document.getElementById(menuID); if(typeof s != "undefined" && s)( if (top+m2
So, everything is simple here. In the settings we pass the following parameters to the script:

var m2 = 0;

Function setMenuPosition())( if(typeof window.addEventListener != "undefined")( window.addEventListener("scroll", marginMenuTop, false); ) else if(typeof window.attachEvent != "undefined")( window. attachEvent( "onscroll", marginMenuTop);

To the following code:

Function setMenuPosition())( if(typeof window.addEventListener != "undefined")( window.addEventListener("scroll", marginMenuTop, false); ) else if(typeof window.attachEvent != "undefined")( window. attachEvent( "onscroll", marginMenuTop); marginMenuTop());

After the page loads, we immediately call our marginMenuTop function, which will check the position of the menu on the page and apply the desired style

Implementing a partially fixed menu using the Afixx jQuery plugin from Twitter Bootstrap

In continuation of this topic, an article was written for you on implementing an almost fixed menu using the jQuery Affix plugin from the Twitter Bootstrap framework.

The first thing we will do is paste our HTML code in the place on your site where you want to see the menu.

  • home
  • WordPress
  • HTML5&CSS3
  • PHP

The menu is assigned the default class, thanks to which our jquery can then determine that this particular block then needs to be pinned to the top.

2. jQuery code

In the header, before the closing head, insert the code. As I wrote above, it defines a block with class default and after scrolling assigns it class fixed . You can change the class names if you need it. But just be careful and don’t miss anything, otherwise everything will simply stop working. You need to change in jQuery, HTML and CSS.

$(document).ready(function())( var $menu = $("#menu"); $(window).scroll(function())( if ($(this).scrollTop() > 100 && $menu. hasClass("default"))( $menu.fadeOut("fast",function())( $(this).removeClass("default") .addClass("fixed transbg") .fadeIn("fast"); )) ; ) else if($(this).scrollTop()

Please note that if there are single quotes in the code enclosed in echo "" , they will need to be escaped, i.e. put in front of each of them a backslash (\") without parentheses, of course.

In general, it turned out as it turned out. You will have to decide for yourself how to specifically attach this to your topic - when you have time, it’s even fun to “rack your brain.” Thank you.

Good luck to you! See you soon on the pages of the blog site

You might be interested

WebPoint PRO is a responsive WordPress theme with wide functionality and competent technical search engine optimization
Share42 - a script for adding social networking buttons and bookmarks to the site (there is a floating panel option)

Which are found more and more often on the pages of blogs and other resources. The use of such navigation bars is quite justified. One of the main reasons for the active use of these jQuery plugins is that the menu is always at the visitor's fingertips, even if it is at the bottom of the page. In addition, a fixed menu takes up little space and does not distract attention from the main content. Generally speaking, a fixed menu improves the usability of the site.
I have put together a collection of the best, in my opinion, free jQuery plugins for implementing a fixed menu. I tried to ensure that each of the plugins was unique in some way, so that any plugin from the selection could be used specifically in your project. In the collection you can find both simple and more complex plugins with animation, etc.
If you need a very simple fixed menu, something like how we implemented a sticky panel with social buttons, you can do without jQuery plugins, because loading the page with scripts is not very good, but we will talk about this in the following articles . Subscribe to our channel or pages so as not to miss interesting materials.
So. Here are 6 jQuery plugins for creating a fixed menu.

Auto-Hide Sticky HeaderjQuery fixed navigation plugin, which works on a similar principle as the script above, but less smooth, although, at first glance, a little easier. Unfortunately, I can’t say that the navigation is fully adaptive, since on small screens the menu items become just numbers, which is very strange.

On Scroll Header EffectsPowerful jQuery plugin for fixed navigation bar. You can set certain segments on the page when scrolling, upon reaching which the panel transforms and can completely change its appearance. There can be any number of such segments on a page.

On-Scroll Animated Header A good plugin to implement a sticky navigation bar. It works like this: at the very beginning of the page, we see a tall header containing the logo and menu. When scrolling, the header area with all elements, including the logo and navigation, smoothly decreases using properties and becomes a narrow strip stuck to the top of the screen.

Today we fix the menu when scrolling the page, let's look at the best implementation option.

How do we fix the menu?

There are 2 ways to fix the menu:

  • Fix the menu only if the page has scrolled down enough
  • Fix the menu permanently
Fixing the menu when scrolling the page

This method requires JS and CSS. First, we need to determine how far the page has scrolled down, and then, if this value is greater than a certain value (for example, greater than the screen size), we will fix the menu. Let's look at an example:

$(window).scroll(function())( var docscroll=$(document).scrollTop(); if(docscroll>$(window).height())( $("nav").css(("height" : $("nav").height(),"width": $("nav").width())).addClass("fixed" )else( $("nav").removeClass("fixed" "); ) ));

That is, when scrolling the page, we check “whether the amount of scrolling the page is greater than the height of the window”, and if it is greater, we add the fixed class to our menu (and specify the height and width, because when using position: fixed the block dimensions are lost), in otherwise, delete this class.

Fixed( position: fixed; top:0; left: 0; )

That is, if such a class is present, the object will become fixed.

Ready. The menu will only stick when the user scrolls the page more than the screen size. Of course, you can fix the menu after the user scrolls the page by the amount of the menu itself, or by some predetermined value.

We always fix the menu (second fixing option)

For this method we just need CSS. We will permanently fix the menu, and if desired, we will make a top indent at the body so that when scrolling to zero, the menu does not overlap with the rest of the content.