esther h
esther h

Reputation: 1468

Can a position:fixed element with percentage width be calculated from body width?

I have a sidebar that starts halfway down the page with position:absolute. When you scroll down and hit the top of the sidebar, some js runs to make it position:fixed, so it will stay in view as you scroll further along.

The problem is, I wanted the width of the page to be fluid, so I made the sidebar width:25%, and the rest of the content width:75%. The body of the page has width:100% with some padding on the sides.

This works until the sidebar gets a fixed width, all of a sudden it stretches out, now the 25% width seems to be calculated from the screen width instead of the body width. That makes sense, but it's not a desired result - I want the width to stay the same as you scroll.

What can I do? css or js (jquery) solutions. Thanks

Upvotes: 0

Views: 147

Answers (1)

G-Cyrillus
G-Cyrillus

Reputation: 106038

What you can do is to set min-width to nav and content. wrap nav within your absolute/fixed element. fixed will always take screen width/height as reference , it's meant to stick in this area :) If you set a min-width, you'll need to add scroll to ccontent in fixed area wider than screen.

http://jsfiddle.net/GCyrillus/GfSM6/

   nav, section {
        width:80%;
        margin:auto; } html, body {
        height:100%;
        margin:0; } section {
        min-height:100%;
        background:#333;
        color:#def;
        padding-top:4em;
        box-sizing:border-box; }
    #posabsfxd {
        position:fixed;
        left:0;
        right:0;
        top:2em;
        text-align:center; } nav {
        background:tomato; } a {
        color:gold; }

Upvotes: 1

Related Questions