How to make a fixed column in CSS using CSS Grid Layout?

前端 未结 8 1839
南方客
南方客 2020-12-04 18:35

I\'ve made a simple site with a #container div that is parent to two divs: #left and #right, by using Grid Layout:

Is there an

8条回答
  •  日久生厌
    2020-12-04 18:53

    You can achieve this by adding these CSS rules to your id #left:

    position: sticky; // See link
    top: 0; //to make it stick to the top of the screen
    height: 100vh; // make the height equal to 100 view height
    

    Link for sticky position: Sticky position with nothing but CSS

    sticky is a new value for the position property, added as part of CSS3 Layout Module Spec. It acts similarly to relative positioning, in that it doesn’t remove anything from the document flow. In other words, a sticky element has no effect on the position of adjacent elements and doesn't collapse its parent element.

    Hope it helps you

    EDIT (fix jumpy behaviour)

    In order to avoid the left part to jump up at the end of the page, just add the following CSS rule to your id #left:

    box-sizing: border-box;
    

    See updated code snippet:

    body {
        margin: 0 0 0 0;
    }
    
    #container {
        display: grid;
        grid-template-columns: 50% 50%;
    }
    
    .section {
        padding: 5% 5% 5% 5%;
    }
    
    #left {
        background-color: aquamarine;
        position: sticky;
        top: 0;
        height: 100vh;
        box-sizing: border-box;
    }
    
    #right {
        background-color: beige;
    }
      

    This should not scroll

提交回复
热议问题