Dynamically position and center an HTML element with CSS, based on percentage

Niklas Klein
The Startup
Published in
2 min readMay 2, 2020

Our goal is to provide a value from 0% to 100% and have the element perfectly positioned, e.g. sticking to the top for 0%, sticking to the bottom for 100%, or being perfectly centered for 50%. At first glance this might seem trivial: position: absolute & top: 50% and we’re good to go. However, that leaves us with a few problems:

  • top: 100% pushes the element completely out of the viewport
  • top: 50% does not perfectly center the element, it just aligns it to the center

Transform to the rescue

You might already know the CSS transform: translate trick to center arbitrary elements horizontally or vertically:

.element {
position: absolute;
top: 50%;
transform: translateY(-50%);
}

And it turns out we can solve our initial problem with those mechanics quite easily! For any position X between 0% and 100% you can perfectly place your element at this vertical position:

.element {
position: absolute;
top: X%;
transform: translateY(-X%);
}
Vertical positioning

Similarly you can do the same for the horizontal axis:

.element {
position: absolute;
left: X%;
transform: translateX(-X%);
}
Horizontal positioning

Motivation

Of course it would have been possible to solve the examples above in different ways, e.g. top: 0 for 0%, bottom: 0 for 100% and an alternative vertical centering approach for 50%. But I needed a solution that works for every value between 0% and 100% and that can easily be generated by a script. On the plus side this also allows us to run animations!

--

--