Search code examples
htmlcsscss-transforms

Prevent margin or padding of outer elements from moving absolute element at a fixed position relatively to its parent


I have read questions about the absolute positioning of elements like this or this. I assume that using the transform function is a way to make the element static inside a parent. I did this CSS:

#container
{
  width: 25%;
  aspect-ratio: 1;
  background-color: purple;
}

#element
{
  position: absolute;
  width: 2%;
  aspect-ratio: 1;
  background-color: violet;
  transform:translate(1151.5%, 0%);
}

With HTML:

<div id="container">
  <div id="element"></div>
</div>

The problem is that this only works fine when I use:

* {
    margin: 0;
    padding: 0;
} 

to prevent the outer elements such as the body or HTML from applying their margins. Without the zero margin/padding the position of the absolute element changes when the window is resized.

For example, changing the margin of the body also changes the position of the child element.

My question is: How do I create a container with an absolutely positioned child that will keep its exact position even when the window is resized or even when the margin is changed? So that the container is independent and the child inside is affected only by the container size change. Like having an independent world inside the container which scales along with its children keeping their positions such as image with various objects or something.

Fiddle here.


Solution

  • You should always use

    * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
    } 
    

    It is a common practice because it removes default margins and paddings. That way you won't get any unexpected moves of your elements.

    The other thing to notice is that you are using position: absolute, but your parent (container) doesn't have set position: relative. They always "come in pair".