Search code examples
cssposition

Center fixed element inside container


I am currently working on a form that is supposed to be embedded into different websites via web components. When the form was send and the API returned an error, a popup/modal/alert is supposed to show up centred horizontally at the top of the page. Since you can scroll the form and the error should always be visible i thought about positioning it fixed. However, this fixes it to the viewport. Since i have no influence on where the form is embedded, i would like to fix it to the form itself and not appear "somewhere" on the website.

I found that you can do that by positioning the container relative and using margin-top instead of top and that works for absolute values, but not for i.e 50%. I assume it uses 50% of the viewport width and not of the container with since it is really far off of the center. Here is an example of what i tried:

.container {
  width: 400px;
  height: 5000px;
  background-color: lightblue;
  position: relative;
  width: min(100%, 300px);
  margin: auto 200px;
}

.child {
  background-color: blue;
  position: fixed;
  margin-top: 3rem;
  margin-left: 50%;
}
<div class="container">
  <div class="child">test</div>
</div>

https://codepen.io/Nils-B-/pen/ZEZLMZm

Is there any way to actually do that in css or do i need js to position it absolutely on scroll?


Solution

  • Can you please check the below solution? Hope it will work for you.

    You can give position: sticky; to child element and other top value of this element.

    .container {
      width: 400px;
      height: 5000px;
      background-color: lightblue;
      position: relative;
      width: min(100%, 300px);
      margin: auto 200px;
    }
    
    .child {
      background-color: blue;
      position: sticky;
      top: 50%;
      transform: translateY(-50%);
    }
    <div class="container">
      <div class="child">test</div>
    </div>