Fluid width fixed position

20,377

Solution 1

.outer {
    position: relative;
    width: %;
}
.inner {
    position: fixed;
    width: inherit;
}

That should do the trick.

Solution 2

position: fixed is always relative to the window/browser, thus it cannot be used to solve your problem. Fixed positioning removes the element from the natural order of the DOM, and thus does not remain within your outer div anymore, hence why it takes the full width of the browser and not of your container. What you need to use is position: absolute to place .inner relative to .outer. You'll be able to position your element as well as have its width be contained by the .outer div.

Solution 3

Fixed elements take only absolute values as width. If your parent container is fluid (width is a percentage), you need to set the width of the fixed element dynamically. You need to get the width of the wrapping container and set it on the sticky element.

CSS

.outer {width: 25%;}
.inner {position: fixed;}

JS

var fixedWidth = $('.outer').css('width');
$('.inner').css('width', fixedWidth);

Additionally, you can add an event listener in case window resizes.

JS

window.addEventListener('resize', resize);
function resize() {
    var fixedWidth = $('.outer').css('width');
    $('.inner').css('width', fixedWidth);
}
Share:
20,377
nderjung
Author by

nderjung

Updated on June 20, 2020

Comments

  • nderjung
    nderjung about 4 years

    Imagine:

    <div class="outer">
        <div class="inner">
        </div>
    </div>
    

    Where:

    • .outer is part of a column structure, and its width is a percentile and therefore fluid.
    • .inner represents a fixed position element that should fill with a 100% width the .outer element. However its position vertically remains the same, therefore fixed.

    I’ve tried to implement this layout with the following CSS:

    .outer {
        position: relative;
        width: %;
    }
    .inner {
        position: fixed;
        width: 100%;
    }
    

    However, .inner does not calculate its width as a percentage of its relative parent. Instead it fills the full width of the window/document. Attempting any left or right properties result in the same parent-ignoring qualities.

    Is there any way around this?

  • Dan
    Dan about 11 years
    How is your JSFiddle related to position:fixed?
  • Ilan Biala
    Ilan Biala over 10 years
    I gave a fix, I didn't say it relates to position:fixed;. It's related to his problem and my answer proposes a solution.
  • Joseph Shambrook
    Joseph Shambrook about 9 years
    Was having this issue, and this actually solved it. For reference, the inherit property is inheriting the width set by its nearest parent.
  • T J
    T J over 7 years
    This doesn't hold anymore once transform is applied in modern browsers...