Center Your HTML Elements Vertically With CSS

 

Center inline-element or block-element Vertically.

There are multiple CSS properties you can choose to center your item vertically in different situations. 

Let's explore it one by one. 

1. line-height:

You can center your inline-element vertically by using this property like - link, text and image.

Set your line-height property value equal to the height property. 

Example - 


.item {
    height : 100px;
    line-height : 100px;
  }

Center vertically your text with line-height property


2. Padding:

Padding used to add the space around your content. You can use this property for multiple lines. 

For centering your element vertically, give the same value to top and bottom. It will set the amount of space above and below to your content.

Example -


.item{
    padding-top : 20px;
    padding-bottom : 20px;
  } 



3. Absolute:

You can apply this property to center your block level element in vertically using position. 

- Using top, bottom and auto-margin:


.parent {
    position : relative;
  } 
  
.item {
    position : absolute;
    top : 0;
    bottom : 0;
    margin : auto;
  } 
It will work great when you know the height of the item.

Note: It will not work if there is more child on the same level.

- Using transform for responsive behavior

.parent {
    position : relative;
  } 
  
.item {
    position : absolute;
    top : 50%;
    -webkit-transform : translateY(-50%);
    transform : translateY(-50%);
  } 

Top:50% is relative to the parent element and transform is relative to the block you are working with.

Center vertically your div with position

4. Flexbox:

Make your item flex and use it with align-items to center your item vertically.

Example - 


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

Center vertically using flexbox

0 Comments:

Post a Comment