# Code Snippet: Centering Arbitrary DisplayObjects

**URL:** <https://forum.kirupa.com/t/code-snippet-centering-arbitrary-displayobjects/326717>\
**Category:** flash\
**Created:** [January 6, 2012, 7:33pm UTC](https://forum.kirupa.com/t/code-snippet-centering-arbitrary-displayobjects/326717 "2012-01-06T19:33:18Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![DoomGoober](https://avatars.discourse-cdn.com/v4/letter/d/839c29/32.png) [@DoomGoober](https://forum.kirupa.com/u/DoomGoober)\
**Post date:** [January 6, 2012, 7:33pm UTC](https://forum.kirupa.com/t/code-snippet-centering-arbitrary-displayobjects/326717/1 "2012-01-06T19:33:18Z")

</div>

The math for centering a DisplayObject whose registration point is not at 0,0 can be a little tricky. I’ve recalculated this algorithm too many times, so I thought I’d share it here.

Assume you want to center the DisplayObject “sprite” in the DisplayObjectContainer “container.” Assume container has a 0,0 registration point, but sprite may not.

```auto
container.addChild(sprite); //Important to do this first!
sprite.x = container.x + container.width * 0.5;
sprite.y = container.y + container.height * 0.5;
var bounds:Rectangle = sprite.getBounds(container);
sprite.x += sprite.x - (bounds.left + 0.5 * bounds.width);
sprite.y += sprite.y - (bounds.top + 0.5 * bounds.height);

```

Or, more generally, to place the center of a display object at (desiredX, desiredY):

```auto

var bounds:Rectangle = sprite.getBounds(desiredCoordinateSpaceDisplayObject);
sprite.x = desiredX - (bounds.left + 0.5 * bounds.width);
sprite.y = desiredY - (bounds.top + 0.5 * bounds.height);

```

I hope this helps someone!
