To center inline elements we can use text-align
.box{
text-align:center;
}
By default block level elements take 100% width. To center block level elements we can set its margin-left and margin-right to zero.
.box{
margin:0 auto;
}
We can use equal padding above and below the inline element
.box{
padding-top:20px;
padding-bottom:20px;
}
We need to set parent element's display as flex and justify-content to center flex-direction by default is set to row so we need to modify it to column.
.parent {
display: flex;
flex-direction: column;
justify-content: center;
}
Set parent's position as relative and that of child element as absolute.
Child element is pushed off from parent's top by 50%, using top and brought up by 50% of the height of the child element using transform.
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
transform: translateY(-50%);
}
We can combine above techinques
Using flex box we can implement this. Setting parent elements display to flex and justify-content and align-items to center.
.parent {
display: flex;
justify-content: center;
align-items: center;
}
We can center elements vertically and horizontally using grid too.
body, html {
height: 100%;
display: grid;
}
span {
margin: auto;
}
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
Built with TypeScript, Tailwind and Next.js ♥