Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

transform-origin equivalent for position absolute

Tags:

html

css

I got an element with unknown size with position=absolute, top=1000, left=1000.

Right now, the top left of that element is at position (1000,1000) but I'd want the center of the element to be (1000,1000).

Is there a way to do that with CSS alone?

like image 778
RainingChain Avatar asked Nov 12 '15 23:11

RainingChain


People also ask

What can I use instead of absolute position?

We can use CSS absolute positioning to overlap elements, but there's some advantages to using CSS grid instead.

When should you use Translate () instead of absolute positioning?

Moving elements with translate() is better than absolute positioning (top, left, right, bottom) If you plan to make an animation by using position: absolute and set top, left, right or bottom please don't. Just use translate.

What is the transform origin?

The transform origin is the point around which a transformation is applied. For example, the transform origin of the rotate() function is the center of rotation.

What is the default value for transform origin?

The default value of the transform origin is at 50% 50%, which is exactly the center of any given element. The transform-origin can be specified using offset keywords, length values, or percentage values.


1 Answers

As pointed out in the comments, you can simply use transform: translate(-50%,-50%) in order to center the element vertically/horizontally. Fortunately, this method works for dynamic values, which means that it will work well in your case since you don't know the width/height of the element.

For example:

.element {
  background: #f00;
  width: 100px;
  height: 100px;
  transform: translate(-50%,-50%);
  position: absolute;
  top: 50%;
  left: 50%;
}
<div class="element"></div>

For what it's worth, here are some alternative methods for vertical/horizontal centering.

like image 172
Josh Crozier Avatar answered Sep 28 '22 03:09

Josh Crozier