Search code examples
cssangularabsolute

Position absolute not working correctly when wrapped by an Angular component


I would like to position an element absolute relative to a parent outside of an Angular component. But this does not work. I have the following structure:

<div id="div1" style="position:relative; padding-left: 20px">
  <some-angular-component>
    <div id="div2" style="position: absolute">
      ...
    </div>
  </some-angular-component>
</div>

I would like to have div2 to be positioned relative to div1 (and therefore not be affected by the padding-left) but this does not seem to work. It seems to be positioned relative to the angular component HTML tag.

Here is a Stackblitz link below showing this.

https://stackblitz.com/edit/angular-ivy-j3estd?file=src/app/hello.component.ts

Does anyone know how I can position 'div2' relative to 'div1', with the Angular component tag in between them?

Cheers :)


Solution

  • The problem is that you only specified position: absolute – and no values for any of the corners.

    If you leave top, bottom, left and right all at their default value auto, then the element gets absolutely positioned, at the position it would already have in normal flow. And since an ancestor has 20px padding here, that normal flow position is 20px from the top left corner of the ancestor in both directions.

    So specify top: 0; left: 0; as well for the absolutely positioned element - and it will be where you want it to be, in the top left corner.