How to implement fixed sidebar correctly?

后端 未结 3 1770
梦谈多话
梦谈多话 2021-01-30 11:32

I\'m trying to accomplish this design: \"example Where the sidebar will be fixed, but the right side (the main con

相关标签:
3条回答
  • 2021-01-30 11:47

    Use the content div as your container for the page.

     .sidebar {
         position: fixed;
         width: 200px;
         height: 400px;
         background: #000;
     }
     .content {
         margin-left: 200px;
         height: 500px;
         width: auto;
         position: relative;
         background: #f00;
         overflow: auto;
         z-index: 1;
     }
     .info {
         width: 1440px;
         height: 300px;
         position: relative;
         background: #f55;
     }
    
    <div class="sidebar"></div>
    <div class="content">
        <div class="info"></div>
    </div>
    

    Your content will need to be the container to put the page in. The values here are my test to see if I am correct in this. If your width and height exceeds the values you set for content, the scroll bars will appear.

    Have a fiddle: http://jsfiddle.net/djwave28/JZ52u/


    edit: responsive sidebar

    To have a responsive fixed sidebar, simply add a media-query.

    Example:

    @media (min-width:600px) {
       .sidebar {
         width: 250px;
       }
       .content {
         margin-left: 250px;
       }
     }
    

    Here's another fiddle: http://jsfiddle.net/djwave28/JZ52u/363/

    0 讨论(0)
  • 2021-01-30 11:52

    Here is an alternative: http://jsfiddle.net/BoyWonder/8mVQX/embedded/result/

    body{
        padding-left:200px;
        margin:0;
    }
    div#sidebar{
       position:fixed;
       height:100%;
       width:200px; 
       top:0;
       left:0;
       background:grey; 
    }
    div#content{
        background:black;
        width:100%;
        height:1600px;
    }
    
    0 讨论(0)
  • 2021-01-30 12:00

    Here is another alternative by using only two CSS lines

    .sidebar { position: sticky; top: 0; }

    and the credit goes to this post.

    You can also experiment with the code over here.

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