Search code examples
cssscrollposition

Position relative to scroll area


I want to absolutely position a div at the top and bottom of a scrolling area so they stay in place while I scroll inside the div.

They the scroll area has position: relative; set and the div's I want pinned to the top and bottom are absolutely positioned at top: 0; and bottom: 0;

Initially they are positioned as expected but when you scroll they scroll inside the scroll area.

Here is a code pen showing my problem: http://codepen.io/JoeHastings/pen/wKJzNb


Solution

  • I do not know of any way to fix an element inside another without using javascript. If you know the position of the box, you can used fixed positioning like this:

    http://codepen.io/anon/pen/pjeRQQ

    .transcript {
        position: relative;
        width: 400px;
        height: 150px;
        background: #ffcc00;
        overflow-y: scroll;
    
        &:before {
            content: '';
            position: fixed;
            width: 400px; height: 20px;
            margin-top: 0; margin-left: 0;
    
            background: -webkit-linear-gradient(rgba(255, 255, 255, 1) 0%, rgba(255, 255, 255, 0.7) 50%, rgba(255, 255, 255, 0) 100%);
            background: -moz-linear-gradient(rgba(255, 255, 255, 1) 0%, rgba(255, 255, 255, 0.7) 50%, rgba(255, 255, 255, 0) 100%);
            background: -o-linear-gradient(rgba(255, 255, 255, 1) 0%, rgba(255, 255, 255, 0.7) 50%, rgba(255, 255, 255, 0) 100%);
            background: linear-gradient(rgba(255, 255, 255, 1) 0%, rgba(255, 255, 255, 0.7) 50%, rgba(255, 255, 255, 0) 100%);
        }
    
        &:after {
            content: '';
            position: fixed;
            top: 140px; left: 0;
            width: 400px; height: 20px;
    
            background: -webkit-linear-gradient(rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.7) 50%, rgba(255, 255, 255, 1) 100%);
            background: -moz-linear-gradient(rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.7) 50%, rgba(255, 255, 255, 1) 100%);
            background: -o-linear-gradient(rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.7) 50%, rgba(255, 255, 255, 1) 100%);
            background: linear-gradient(rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.7) 50%, rgba(255, 255, 255, 1) 100%);
        }
    }