How to center align vertically or horizontally element within CSS?

To align it horizontally, use:

classname{
   left:0;
   right:0;
   width: 200px;
   position: absolute;
   margin: auto;
   overflow: auto;
} 

 

However, to align it vertically use:

.classname{
   top:0;
   bottom:0;
   height:200px;
   position: absolute;
   margin: auto;
   overflow: auto;
}

 

Inorder to use them in combination

.classname{
   position: absolute;
   margin: auto;
   top:0;
   bottom: 0;
   left: 0;
   right: 0;
   width:200px;
   height: 200px;
   overflow: auto;
}

Try out with JS Fiddle

Only drawback using this is, height or width properties are mandatory. If you miss it, the element will show 100% width and height.

Cheers

How to center align absolute element

Leave a Reply

Your email address will not be published. Required fields are marked *