Vertical align anything with just 3 lines of CSS

.element {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}

Same goes for horizontal centering. Where one – back in the day – would abuse margin-left by setting a negative margin to half of the width, we can now use translateX(-50%) to horizontally center a fluid-width box.

.element {
  position: relative;
  width: 400px;
  left: 50%;
  margin-left: -200px;
}
.element {
  position: relative;
  left: 50%;
  transform: translateX(-50%);
}

Some great demos of modals using this technique, along with some fancy animations, can be found on Codrops

Vertical align anything with just 3 lines of CSS →
Modal Window Effects →

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.