Dynamically Centering an Element in a Container Using CSS One way to use CSS transforms to center an element within a container.

When it comes to writing about development, I don’t often talk about things beyond PHP and JavaScript mainly because I work with those languages more than others.

I mean, yeah, CSS is part of the deal as is HTML, but it’s expected these days, right?

So if there was ever a quick tip for me to offer regarding CSS, this is it (though maybe I should write more?). It’s hard when Chris does such an awesome job running CSS Tricks, but I digress.

Anyway, here’s the problem and the solution.

Dynamically Centering an Element in a Container

The idea of dynamically centering an element is based on the following scenario:

  • You’re making a call to an API that will be responding with a set of, say, images once the call completes.
  • You need to center each image within its container.
  • The images are not going to have a fixed height and will need to be dynamically positioned and centered within containers in the UI.

Perhaps this is still a bit general. If so, let’s assume that you have a list (ordered or unordered, it doesn’t matter). They have a fixed height and width, and you’re going to be placing the images, scaled, within each element.

Remember: you can’t place things like div elements within li elements (because a div is a block-level element) without changing it via some CSS. And we want to avoid doing that.

So ultimately, the UI may look something like this (crude, I know):

Dynamically Centering An Element

If you want each image to be placed within the list item, you want it to have a certain scaled height, and you want it to be centered, try the following bit of code:

The key to this, really, is the transform style. According to MDN:

The translateY() CSS function repositions an element vertically on the 2D plane. Its result is a <transform-function> data type.

Make sense?

Think of it this way: The translateY function will take a given element (identified by its selector) and position it using the specified value.

It’s About Transforms

You can use pixels, percentages, or whatever it is you need to make it happen. In this case, it’s percentages (and they are negative). Though I’m using an example of my implementation, it’s also meant to be a tip on how to use the transformY function with relation to transforms.

If browser compatibility matters – which, in some cases, it should – check out this chart. You’re pretty well covered.