Vertical alignment

19.04.19

There are several ways of vertical alignment. In different situations, different ways are suitable. Consider some of them.

1. With display: flex

It's the most convenient and modern way.

.parent{
	display: flex;
	align-items: center;	
}

2. With table-cell

In table cells, vertical-align applies to any content.

.parent{
   display: table;
}
.child{
   display: table-cell;
   vertical-align: middle;
}

3. With position: absolute и top

It is suitable for cases with a known height of the child block. The principle of operation lies in top: 50% (half of the parent block) and a negative indent from above into half of the child block. In the same way, you can center the block horizontally, using only left: 50% and a negative margin on the left.

.parent{
    position: relative;
}
.child{
    position: absolute;
    height: 50px;
    top: 50%;
    margin-top: -25px;
}

4. With position: absolute and margin

There is another way to center using absolute positioning. The height of the child block must be fixed. You can also center the child unit horizontally. Then the width must also be fixed.

.parent{
    position: relative;
}
.child{
    position: absolute;
    top: 0; 
    bottom: 0; 
    left: 0; 
    right: 0; 
    margin: auto;
    height: 30px; /*your value*/
    width: 200px; /*your value*/
}

5. Align one line

The block height and row height must be the same.

height: 30px;
line-height: 30px;
display: inline-block;
text-align: center;
text-transform: uppercase;
blog comments powered by Disqus