Align Content Vertically Center with CSS

We know text-align: center & margin: 0 auto to have the text or content block to put horizontally center. But many time we come across a situation where we need to align the whole content vertically center.

With CSS3 in action we can achieve things which were not possible before. In CSS3, we have transform property which helps us to put the content vertically center.

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

First, we are keeping he value at 50% height from the start of the div with top property and then we are keeping the content half-pixel upper side with translate value in transform property to -50%, so it will positioned the content at the half way in the wrapper block.

Usually, transform property used to rotate the content by giving X and/or Y angle with translate.

For all browser compatibility we will need to use browser vendor prefix with transform property.

div {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
  -webkit-transform: translateY(-50%);
  -moz-transform: translateY(-50%);
  -ms-transform: translateY(-50%);
}

Also the content block which positioned absolute with CSS can also be align vertically and/or horizontally center. In this case we need to have the wrapper block with relative position so the absolute block will position accordingly.

.wrapper-div {
  position: relative;
}
div {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  -webkit-transform: translateY(-50%);
  -moz-transform: translateY(-50%);
  -ms-transform: translateY(-50%);
}

Note: Sometimes it may appear that the fonts are little blurry because we are keeping the content half-pixel up. If this happens, we can fix it by using preserve-3d value of transform property for the wrapper content block.

.wrapper-div {
  position: relative;
  transform-style: preserve-3d;
  -webkit-transform-style: preserve-3d;
  -moz-transform-style: preserve-3d;
  -ms-transform-style: preserve-3d;
}
div {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  -webkit-transform: translateY(-50%);
  -moz-transform: translateY(-50%);
  -ms-transform: translateY(-50%);
}

Hope this is helpful, let me know your feedback/suggestion in comment box below.

Web/ UI & Front-end developer based in Ahmedabad, GJ, India. Here to help/ discuss community to spread web awareness.

Leave a reply:

Your email address will not be published.