level up some UI chops

How to Pin an Element to the Center of its Parent

Apr 19 2017

Centering things in CSS can sometimes seem impossible. Especially if the child to be centered has a dynamic width or height, or is actually larger than its parent element.

Pinning a child element to the center of its parent has a lot of uses. While building the zombie bones in my game I needed a way for the container (parent element) to take up a specific height and width regardless of the size of its content, and have the animation canvas (child element) be centered perfectly even though it’s larger than its parent. This allows the zombies in my game to take up a predictable space, but let their animations bleed outside the set space without getting clipped.

pinning element to parent's center

Luckily for us, this is actually pretty easy with a little flexbox magic!

Pin Child to Parent

On the parent element all we have to do is:

  1. set the parent container element to use flexbox
  2. center its children horizontally with justify-content
  3. center its children vertically with align-items

.parent-container {
  display: flex;
  justify-content: center;
  align-items: center;

One important thing not to miss on the child element is to tell it not to shrink. Otherwise the child will squish down to the width of its parent instead of staying its full width like we want.

.child-canvas {
  flex-shrink: 0;

Here is an example codepen you can play with:

See the pen by Dave Geddes (@geddski) on CodePen.

Shifting the Position of the Child

Once you have this setup, you can easily make adjustments to the position of the child element. For example if you’d rather you can pin it to the top of the parent:

See the pen by Dave Geddes (@geddski) on CodePen.

Or pin it to the bottom left:

See the pen by Dave Geddes (@geddski) on CodePen.

Even after you’ve pinned it, you can make tiny little adjustments using relative positioning on the child to get it just where you want it:

See the pen by Dave Geddes (@geddski) on CodePen.

Sweet right?

Now that you know how to pin elements to their parents you can center layouts quite easily. Flexbox is super powerful for this and many other UI needs. Flexbox Zombies covers it all in gritty (gory?) detail!

Here’s your homework: Go play with the codepen examples above and look for a way to use this to simplify one of your existing centering hacks.

Dead Tired of Looking up Flexbox?

Flexbox is incredibly powerful. But it's also crazy hard to master. So we all end up depending on a cheat sheet and guessing in the dev tools. Enough of that! Time to master it once and for all, in a way that actually sticks, so you can build any layout you can imagine with flexbox.