Search code examples
cssscrollfixedcentering

CSS: Centering a content with fixed position


I'm having trouble with keeping a layer both fixed and centered at the same time. I can't apply margin: auto as my layer doesn't have any width value, it's a fulid thing.

I found this one: https://stackoverflow.com/a/1777282/2114455

It's a great solution to center the layer, but how do I keep this centered layer fixed (I mean, no move when scrolling)

I put them all in a position: fixed; div but this did not work. Any solution?


Solution

  • Maybe I'm not understanding your question, but if you change the position of the outer div from the solution you linked to "fixed" it should work.

    <div style="position: fixed; left: 50%;">
        <div style="position: relative; left: -50%; border: dotted red 1px;">
            I am some centered shrink-to-fit content! <br />
            tum te tum
        </div>
    </div>
    

    (fiddle of this in action: http://jsfiddle.net/Rykus0/TQw2j/)