BlogVideos
#react
#css
#javascript
#mongodb
#tech talks
#codepen
#Logrocket Blog

Center align content vertically and horizontally in CSS

April 07, 2019 • 🍿 1 min read • Edit this post on Github
Follow me on twitter. I share quick tips, my reading list and also about free workshop and webinars around web and mobile development everyday.

Center aligning content vertically and horizontally are usual requirement in any website. There are several ways to achieve it using CSS.

  • using CSS transform
  • using flexbox

CSS transform

.content {
  position: relative;
  top: 50%;
  left: 50%;
  // shifts or translate the center point (X, Y) by (X - 50% of outerWidth, Y - 50% of outerHeight)
  transform: translate(-50%, -50%);
}

Limitations

  • It works very well for centering content block with fixed width in both directions ✅
  • For non fixed width, the content block assumes 100% of parent’s width. It expands the whole width of parent container horizontally. You can check this by removing width for content in codepen example ❌
  • this technique won’t work if the content is inline level element, it only works for block level elements ❌

Modern flexbox way

.parent {
  display: flex;
  // centering along main axis - X axis - Horizontal
  justify-content: center;
  // centering along cross axis - Y axis - Vertical
  align-items: center;
}

Note: main and cross axis depends on flex-direction property. By default flex-direction is row. If it is set as column, then main axis is Y and cross axis is X.

This approach works on almost every use cases perfectly

  • fixed width of content block ✅
  • non fixed width of content block ✅
  • content can be inline level element or block level element ✅

Flexbox is so powerful and you can easily develop more styles and components using it. Its supported on all major browsers, no excuse to not using it 😊

Get Weekly Developer Tips

I send out a short email each friday with code snippets, tools, techniques, and interesting stuff from around the web. Join 2,600+ subscribers.

Share:

Made with ❤️ in Tallinn, Estonia

Paramanantham Harrison's DEV Profile