Applying a different position for each child of a parent element with a formula?

26 views Asked by At

I have a parent element with relative positioning and three children elements with absolute positioning. What I wanted to figure out is if there's a way to make each child element have different top/left positioning by their index.

It doesn't have to be strictly this way but what I imagined could be possible would be...

.parent-element .child-element {
    position: absolute;
    top: 50% - (5 * n);
    left: 50% - (5 * n);
}

Where n stands for the child's index in the parent element. So the first child would have an index of one, the fifth would have an index of five and so on.

1

There are 1 answers

2
A Haworth On BEST ANSWER

Here's a simple example.

Each child sets a css variable to its index and this is used in the calculation.

Note I've assumed % is the unit to use as it will be responsive to viewport changes.

.parent-element {
  position: relative;
  width: 50vmin;
  height: 50vmin;
}

.parent-element .child-element {
  position: absolute;
  top: calc(50% - (5% * var(--n)));
  left: calc(50% - (5% * var(--n)));
}

.child-element:nth-child(1) {
  --n: 1;
}

.child-element:nth-child(2) {
  --n: 2;
}

.child-element:nth-child(3) {
  --n: 3;
}
<div class="parent-element">
  <div class="child-element">1</div>
  <div class="child-element">2</div>
  <div class="child-element">3</div>
</div>