Is it possible to keep the width of the parent element when position: fixed is applied?

前端 未结 8 1849
没有蜡笔的小新
没有蜡笔的小新 2021-02-01 12:16

When we apply position:fixed to an element, it\'s taken out of the normal flow of the document, therefore it doesn\'t respect it\'s parent\'s element width. Are the

相关标签:
8条回答
  • 2021-02-01 13:13

    As someone already suggest, using plain javascript (without jquery):

    const parentElement = document.querySelector('.parent-element');
    const fixedElement = document.querySelector('.fixed-element');
    
    window.addEventListener('load', changeFixedElementWidth);
    window.addEventListener('resize', changeFixedElementWidth);
    
    function changeFixedElementWidth() {
      const parentElementWidth = parentElement.getBoundingClientRect().width;
      fixedElement.style.width = parentElementWidth + 'px';
    }
    
    0 讨论(0)
  • 2021-02-01 13:15

    The width is changing because the object when static is receiving its percentage width from its parent. Once you set the object to fixed it is no longer in flow and resizes.

    You're gonna have to set a size to your nav menu on its own and not expect the element to get its width from the parent.

    .nav {
        position: fixed;
        width: 20%;
        border: 1px solid green;
        padding: 0px;
        list-style-type:none;
        background:lightblue;
    }
    

    http://tinker.io/3458e/5

    0 讨论(0)
提交回复
热议问题