skip to Main Content

The html struct

<div class="main">
  <div class="sticky">
    sticky menu
  </div>
  <div class="body">
    body
  </div>
  <div class="other">
    other body
  </div>
</div>

The css style

<style>
 html body {
     margin: 0;
     padding:0 ;
     height: 100%;
     width: 100%;
 }
 .main {
     width:100%;
     max-width: 300px;
     height: 480px;
     margin: 0 auto;
     background-color: yellow;
     position: relative;
     margin-top: 50px;
 }
 .body {
     height: 720px;
 }
 .sticky {
     position: sticky;
     z-index:10;
     top: 0;
     background-color: blue;
     display: inline-block;
     transform: translate(-100%,0);
 }
</style>

sticky

I want to remove the space occupied by the red box, One of the solutions is make .sticky inside position: absolute, but I can’t change html struct, any solution to make it work? Thanks

4

Answers


  1. One idea is to use float and then use shape-outside to make the element takes 0 space.

    body {
      margin: 0;
    }
    
    .main {
      max-width: 300px;
      height: 480px;
      margin: 0 auto;
      background-color: yellow;
      position: relative;
      margin-top: 50px;
    }
    
    .body {
      height: 720px;
    }
    
    .sticky {
      position: sticky;
      z-index: 10;
      top: 0;
      background-color: blue;
      float: left; /* here */
      shape-outside: inset(50%); /* and here */
      transform: translate(-100%, 0);
    }
    <div class="main">
      <div class="sticky">
        sticky menu
      </div>
      <div class="body">
        body
      </div>
      <div class="other">
        other body
      </div>
    </div>
    Login or Signup to reply.
  2. Instead of position sticky, use position fixed and add padding to the body container

    Login or Signup to reply.
  3. You can use position: fixed; insted of position: sticky;

    Login or Signup to reply.
  4. If the main block is made flex, then all the blocks in it will be pressed to the very top.

     html body {
        margin: 0;
        padding:0 ;
        height: 100%;
        width: 100%;
        }
        .main {
        display:flex; /* main pushes up */
        width:100%;
        max-width: 300px;
        height: 480px;
        margin: 0 auto;
        background-color: yellow;
        position: relative;
        margin-top: 50px;
        }
        .body {
        height: 720px;
        }
    .sticky {
        position: sticky;
        z-index:10;
        top: 0;
        height:100px; /* height container */
        background-color: blue;
        display: inline-block;
        transform: translate(-100%,0);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search