skip to Main Content

I have a div container with a responsive width and height when I start minimizing the page. It also has a min-width. I want add a floating action button that is 24px from the bottom and 24px from the right of the div container. I’ve tried making the container’s position relative, while the button will have a position of fixed, but the button is still relative to the viewport.

Is what I’m trying to accomplish even possible with fixed position?

Is there another way to do this, or possibly recalculate the position of the button based on the containers width?

<div class="container">
<button class="button" type="button">
    I want to be relative to my container and not the viewport
</button>
</div>

.container {
    position: relative;
    min-height:500px;
    min-width: 1500px;
}

.button {
    position: fixed;
    bottom: 24px;
   right: 24px;
}

2

Answers


  1. Why not position: absolute on the button?

    .container {
      position: relative;
      min-height: 130px;
      border: 1px solid tomato;
    }
    
    .button {
      position: absolute;
      bottom: 24px;
      right: 24px;
    }
    <div class="container">
      <button class="button" type="button">
        I want to be relative to my container and not the viewport
    </button>
    </div>
    Login or Signup to reply.
  2. For the desired effect, you should use position: absolute instead of position: fixed.

    MDN position
    CSS property
    The absolutely positioned element is positioned relative to its nearest positioned ancestor (i.e., the nearest ancestor that is not static). Fixed positioning is similar to absolute positioning, with the exception that the element’s containing block is the initial containing block established by the viewport [i.e., body]

    .container {
      position: relative;
      min-height: 500px;
      min-width: 1500px;
    }
    
    .button {
      position: absolute;
      bottom: 24px;
      right: 24px;
    }
    <div class="container">
      <button class="button" type="button">
        I want to be relative to my container and not the viewport
      </button>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search