CSTLdesign News

Centering Percentage Width/Height Elements

If you know the exact width/height of an element, you can center it smack dab in the middle of its parent element easily with this classic trick: top and left set to 50% and negative margins half the width and height of the element. That’s great if you know the width and height of the element you’re trying to center, but what if they are percentages?

You’d think you could just use negative percentage margins. That works for horizontal margins, but margins are based on width (even vertical margins) so it breaks down when you try to use negative top margin to pull things into place.

There is a little trick involving a “ghost” pseudo element and inline-block/vertical-align that is pretty darn clever. But that requires the element you are centering to be inline-block and that’s not a real common scenario. More likely you’re trying to center something like a modal window right in the center. And with small screens / responsive design being big business, it’s highly likely you’ll want your dialog box to be of percentage width (or otherwise unknown like have just a max-width).

There is a way! I saw this trick used by Mary Lou over at Codrops and her article/demo Nifty Modal Window Effects.

Instead of using negative margins, you use negative translate() transforms.

.center { position: absolute; left: 50%; top: 50%; /* Nope =( margin-left: -25%; margin-top: -25%; */ /* Yep! */ transform: translate(-50%, -50%); /* Not even necessary really. e.g. Height could be left out! */ width: 40%; height: 50%;

Use whatever prefixes you need these days.