4 quickest way to center div Element by CSS

Method 1: The first and simple method by using flex layout.Simply add to the div parentes element.It quickest way to center multiple element in a single div.


justify-content:center;(horizontal alignment)

align-items:center;(vertical alignment)

Method 2:Second method is to use margin auto.Add parent element margin:auto.But there has a lots of limitation that have width set and define have block or table display and position not should be absolute or fixed.It does  not work for vertical alignment.so you can make center in only horzontally.This is not a good option to use make div element to center because it is not quite flexible and should used for certain scenario .



Method 3: The third method is to use a combination of text-align and inline-block display.Simply add parent element text-align:center and then make child element display :inline-block.The different between second and this method is you don't need to specify width wih this.Still you cant not use it for vertical alignment.

Method 4:The fourth method is to use the 2d transform .Firs we need set child element position:absolute and then set top and left:50% and then set transform:transalate(-50%,-50%) for offset x and y.The div will be always center and ignore all other elements.





transform:transalate(-50%,-50%) //for offset x and y set.


Post a Comment