3 methods to vertically align elements using CSS

by Jay Mistry · Aug 16, 2019

Tutorial Web-Development

Vertically aligning elements using CSS can be a pain.

One would expect the vertical-align property to work as it is expected - align the elements vertically to top, middle or bottom.

But it doesn’t. It doesn’t come to your rescue if you need to center a div block vertically.

I have a good news for you, though!

Today, I will be sharing 3 methods, which you can use to vertically align elements in CSS.

Vertical align using top, bottom and transform properties

To vertically align elements using this method, you need to add position: absolute; or position: relative; properties to the parent element.

Then to vertically align the elements in the middle, you need to add the following rules-

.selector {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}

To vertically align the elements to the bottom, you need to add the following rules-

.selector {
  position: absolute;
  bottom: 0;
}

Vertical align the elements using CSS Flex

To vertically align elements using CSS Flex property, you need to add the following styles to the parent element-

.selector {
  display: flex;
  align-items: center;
  justify-content: center;
}

Here, the elements will be vertically aligned in the middle.

To vertically align the elements at the start, add the following rule to the element-

.selector {
  align-self: flex-start;
}

To vertically align the elements at the end, add the following rule to the element-

.selector {
  align-self: flex-end;
}

Vertically align elements using CSS Grid

This method is my personal favourite!

You need to add a display: grid; property to the parent element.

Then, to vertically align the blocks in the middle, you need to add the following rule-

.selector {
  align-self: center;
}

To vertically align the blocks at the end, you need to add the following rule-

.selector {
  align-self: end;
}
Code in action

You can test out all these three methods in the following Pen-

See the Pen Vertical align items using CSS by Tech no Kami (@technokami) on CodePen.

Thank you :)

See you in the next post!