How to keep sticky navbar within defined body width?

问题: My sticky navbar goes from body width (max 1450px) to 100% screen width when scrolling. https://biogenity.com/RC19/index.html I've defined the body width using CSS: b...

问题:

My sticky navbar goes from body width (max 1450px) to 100% screen width when scrolling. https://biogenity.com/RC19/index.html I've defined the body width using CSS:

    body {
      max-width: 1450px;
    }

For the sticky navbar I currently use 100% width, but it doesn't apply within the width of body. I'm not quite sure what to use instead.

    .sticky.is-sticky {
        position: fixed;
        left: 0;
        right: 0;
        top: 0;
        z-index: 1000;
        width: 100%;
    }

Could this maybe be fixed through the .js?

            $(document).ready(function () {
            // Custom function which toggles between sticky class (is-sticky)
            var stickyToggle = function (sticky, stickyWrapper, scrollElement) {
                var stickyHeight = sticky.outerHeight();
                var stickyTop = stickyWrapper.offset().top;
                if (scrollElement.scrollTop() >= stickyTop) {
                    stickyWrapper.height(stickyHeight);
                    sticky.addClass("is-sticky");
                }
                else {
                    sticky.removeClass("is-sticky");
                    stickyWrapper.height('auto');
                }
            };

            // Find all data-toggle="sticky-onscroll" elements
            $('[data-toggle="sticky-onscroll"]').each(function () {
                var sticky = $(this);
                var stickyWrapper = $('<div>').addClass('sticky-wrapper'); // insert hidden element to maintain actual top offset on page
                sticky.before(stickyWrapper);
                sticky.addClass('sticky');

                // Scroll & resize events
                $(window).on('scroll.sticky-onscroll resize.sticky-onscroll', function () {
                    stickyToggle(sticky, stickyWrapper, $(this));
                });

                // On page load
                stickyToggle(sticky, stickyWrapper, $(window));
            });
        });

Thanks in advance.


回答1:

By using position:fixed you remove the element from the normal document flow so I don't believe the body styles apply.

From position - CSS: Cascading Style Sheets | MDN

The element is removed from the normal document flow, and no space is created for the element in the page layout.

So you should set the max-width for it and allow it to be centered by setting left and right to auto:

.sticky.is-sticky {
    position: fixed;
    max-width: 1450px;
    left: auto;
    right: auto;
    top: 0;
    z-index: 1000;
    width: 100%;
}
  • 发表于 2019-03-09 03:48
  • 阅读 ( 209 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除