skip to Main Content

I want to be able to keep elements on the right side of a div within the same location (similar to position: fixed), however I want to keep the div within its parent. required format
I want the "Stays in view" element to not leave its parents div but stay within the viewport.

I’ve tried position: fixed however its very hard to keep it from overlapping other elements with multiple viewports and will leave its parents div.

Thanks Parth M for the help. With your suggested edits:
latest output

2

Answers


  1. The position: sticky property on the .sticky element makes it stick to the top of its parent .sidebar when you scroll within the .container.

    The top: 0; specifies that the element should stick to the top of the container. You can adjust this value to change where the element sticks within the viewport.

    The position: relative; on the .sidebar ensures that the sticky element is constrained within the bounds of the .sidebar as you scroll.

    .container {
        display: flex;
        height: 200vh;
    }
    
    .content {
        flex: 1;
    }
    
    .sidebar {
        width: 200px;
        position: relative;
    }
    
    .sticky {
        position: -webkit-sticky;
        position: sticky;
        top: 0;
        background: lightgray;
        padding: 10px;
        border: 1px solid #ccc;
    }
    <div class="container">
        <div class="content">
            scrollable child
        </div>
        <div class="sidebar">
            <div class="sticky">
                Stays in view
            </div>
        </div>
    </div>
    Login or Signup to reply.
  2. Use position: sticky;

    .left_col{
      width:25%;
      background:linear-gradient(to bottom, red, orange);
      height:2000px;
      margin-right:20px;
        float:left;
    }
    
    .right_col{
      width:calc(75% - 20px);
      background:grey;
      height:2000px;
      float:left;
      position:relative;
      display:flex;
      padding:20px;
      box-sizing: border-box;
      justify-content: space-between;
    }
    
    .left_content{
      height:100%;
      width:48%;
       background:linear-gradient(to bottom, yellow, orange);
    }
    
    .right_content{
      width:48%;
      height:200px;
      background:green;
      position: sticky;
      right:0;
      top:20px;
    }
    <div class="left_col"></div>
    
    <div class="right_col">
        
      <div class="left_content"></div>
      <div class="right_content"></div>
      
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search