Center Your HTML Elements Horizontally and Vertically

 

Center your text, image and div from both axis

Centering an element is a most common task, you have to do it a lot in your project. 

Different CSS properties can help you to center inline-element and block from both axis. 

I am mentioning here four different CSS properties -

  • CSS table 
  • Flexbox 
  • Absolute 
  • Margin 

1. CSS table:

You can use table-cell with vertical-align property to center your content vertically and text-align property to center your content horizontally. 

Example - 


.item {
    display : table;
  } 
  
.item p {
       display : table-cell;
       vertical-align : middle;
       text-align :center;
     } 
     

2. Absolute:

You can place your block level element center from both axis to its nearest relative parent. 

Using top, right, bottom and left properties -

Example - 


.parent {
     position : relative;
   } 
  
.child {
     position : absolute;
     top : 0;
     right : 0;
     bottom : 0;
     left : 0;
     margin : auto;
     width : 100px;
     height : 100px;
   } 
  

Note: please specify the width and height.

Using transform for responsive behavior -

translate(-50%, - 50%) pair with top and left property and move your box to center. 

Example - 


.parent {
     position : relative;
   } 
   
.child-elem {
     position : absolute;
     top : 50%;
     left : 50%;
     -webkit-transform : translate(-50%, -50%);
     transform : translate(-50%, -50%);
   } 
   

3. Flexbox:

It is a simple and easy way to place the element center from both axis. Apply it to the parent and see the magic.


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

4. Margin:

If your parent element is flex or grid, you can also use margin to center your child element horizontally and vertically. It will work for both inline and block elements. 

Example - 


.parent {
     display : flex;
   } 
   
.item {
     margin : auto;
   } 
   


Related Topic


0 Comments:

Post a Comment