Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I implement a fixed sidebar? [duplicate]

I have a situation like this:

<!DOCTYPE HTML>
<html>
    <head>
        <title>test</title>
    </head>
    <style>
        #wrapper { width: 1100px; margin: 0px auto; }
        #wrapper #stream { width: 790px; float: left; border: 1px solid red;  }
        #wrapper aside { width: 270px; float: left;  border: 1px solid red; }
    </style>
    <body>
        <section id="wrapper">
            <section id="stream">
                some text...
            </section>
            <aside>
                <ul>    
                    <li>something</li>
                    <li>something</li>
                    <li>something</li>
                    <li>something</li>
                </ul>
            </aside>
        </section>
    </body>
</html>

and I don't want the sidebar to move even if the page scrolls down.

I tried setting the aside's position to fixed but so I can't set properly the distance from left.

I found a solution with jQuery:

$(document).ready(function () {
    $(window).scroll(function () {
        $("aside").css('top', $(window).scrollTop()+'px');
    });
})

but with Chrome and Safari the scroll of the aside is piecewise.

Any help?

========================

SOLUTION:

<!DOCTYPE HTML>
<html>
    <head>
        <title>test</title>
    </head>
    <style>
    #wrapper {

        width: 1100px;
        margin: 0px auto;
    }
    #stream {
      width: 800px;
      background: #ccc;
      float: left;
    }
    #sidebar {
    float: left;
      border: 1px solid red;
      width: 200px;
    }
    aside {
      position: fixed;
      top: 20px;
      border: 1px solid red;
    }
    </style>
    <body>
    <section id="wrapper">
        <section id="stream">
                some text...
        </section>
        <section id="sidebar">
          <aside>
                <ul>    
                    <li>something</li>
                    <li>something</li>
                    <li>something</li>
                    <li>something</li>
                </ul>
          </aside>
        </section>
    </body>
</html>
like image 788
Gnamm Avatar asked Jun 02 '26 09:06

Gnamm


1 Answers

In order to use the top, right, bottom or left properties, you have to set the object's display property to absolute, relative or fixed.

Either way, by setting position: fixed; it won't move when you scroll.

like image 154
Tim S. Avatar answered Jun 03 '26 22:06

Tim S.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!