6 ways to Align Elements Vertically

6 ways to Align Elements Vertically

Almost all of us has no problems with align elements horizontally via text-align: center; or with margin: 0 auto;
But if we need to align elements vertically it’s not the same easy! we have some cases to achieve this

1- Align a single line text knowing its container height

if we have a single line text such like a heading of a topic and we know the height of its container so we could handling vertical align with line-height : height of container

See the Pen OMXRqw by peter (@w34) on CodePen.0

2- Align a multible line text knowing its container height

In this case we can’t use line-height property because it will cause in very large distance between lines so we need a different way which is display: table; for the container and display: table-cell;
vertical-align: middle;
for the content we want to align.

See the Pen jWyXLB by Peter Wilson (@w34) on CodePen.0

3- Align none text elements (div, image ..etc)

In this case display:table will not be helpful we need something else to be able to align the element, so in this case we need a pseudo element to adjust the main element to it which mean we need to add before or after pseudo elements with 100% height and vertical-align set to middle as we can see below

See the Pen Bjpvrz by Peter Wilson (@w34) on CodePen.0

4- Align with padding top when knowing element’s height

Here we can use padding top to reach the vertical alignment by simple calculation padding-top: 1/2 container height - 1/2 element height;which in this example padding-top : 1/2 * 218 - 1/2 * 50
109 - 25 = 84
so padding top property will be
padding-top: 84px;

See the Pen EPbajq by Peter Wilson (@w34) on CodePen.0

5- FlexBox a New Way

The main idea behind the display:flex; layout is to give the container the ability to alter its items’ width/height (and order) to best fill the available space (mostly to accommodate to all kind of display devices and screen sizes). A flex container expands items to fill available free space, or shrinks them to prevent overflow.

See the Pen pgmzPV by Peter Wilson (@w34) on CodePen.0

6- Align using jQuery

It’s not good idea at all to align using javascript but some times and for some reasons we have no choices and CSS become not efficient, but please try as much as you can to put this option as the last choice you will choose.

via JavaScript or JQuery you have to do the same as the last thing.

First you will have to get the height of the container and the height of the element and do the same calculation to get the padding-top property value then finally assign it to the container.

See the Pen mVqyWw by Peter Wilson (@w34) on CodePen.0