How to center elements using css

As developers we often find it difficult and challenging when we do not know how to center an element and what method we need to use.

Below are ways on how to center an element with css

  • Method 1
el{
display: flex;
justify-content: center;
align-item: center;
height: 100vh;
}
  • Method 2
el {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
  • Method 3
el {
width: 500px;
min-height: 100vh;
margin: auto;
// NB: Without a specified width, setting your margin to auto will not work
}
  • Method 4
el{
text-align: center
}