Search code examples
htmlcssangularfrontendclient

Make a position fixed not scrollable


I was wondering if there is a way to make a div with position fixed immobile, so if the user scrolls the div will be immobile to the initial position. I need it because I have a toast spawning inside another div, and I need this toast in foreground otherwise it will spawn inside the div (with scrollbar and partially visible).

That's an example image to explain better:

With position absolute: enter image description here

With position fixed (the desired effect): enter image description here

That's my component code (it's a child component):

        <div class="toast" role="alert" aria-live="assertive" aria-atomic="true" style="position:absolute; z-index:999; left:80%; width:300px;opacity:1;cursor:unset !important" *ngIf="!isCollapsed && onlyOnePopup == dataItem.Id">
          <div class="toast-header" style="background-color: #00549F;">
            <strong class="mr-auto" style="color:#fff;"></strong>
            <button (click)="onlyOnePopup = null && isCollapsed = true" type="button" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="Close">
              <span aria-hidden="true" class="close" style="color:white;">&times;</span>
            </button>
          </div>
          <div class="toast-body" style="font-family:Font; white-space:pre-line; color:black; cursor:unset">
            TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST TEST
          </div>
        </div>

Solution

  • Use position: fixed, and then set the exact position that you want. Here's a snippet showing you an example of how to do it.

    body {
      height: 2000px;
      background-color: aqua;
    }
    
    .fixed-div {
      width: 200px;
      heigth: 200px;
      background-color: white;
      padding: 50px;
      
      position: fixed;
      top: 0px;
      right: 0px;
      margin-right: 20px;
      margin-top: 20px;
    }
    <html>
    <head></head>
    <body>
      <div class="fixed-div">
         Fixed Div
      </div>
    </body>
    </html>